The media chain as mesh modules, in one catalogue
sonarr, radarr, lidarr, bazarr, nzbget, qbittorrent, jackett, bookshelf, plex, tautulli, kometa and ombi, taken from the novox/mesh-catalog branches that prepared them for ace (PRs 145-168), consolidated in stack order. kometa gains a minimal runtime sidecar (kometa_status, kometa_config) and declares its tmdb key as an own secret instead of a "secret" requirement.
This commit is contained in:
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# mesh-media-catalog
|
||||||
|
|
||||||
|
The media chain as Novox Mesh modules, one per directory under [`modules/`](modules/): the
|
||||||
|
servarr trio (sonarr, radarr, lidarr), bazarr, the downloaders (nzbget, qbittorrent), jackett,
|
||||||
|
bookshelf, plex and its companions (tautulli, kometa), and ombi.
|
||||||
|
|
||||||
|
It is a catalogue in the exact shape of [`novox/mesh-catalog`](https://git.novox.be/novox/mesh-catalog):
|
||||||
|
the same manifest vocabulary, the same rules, checked the same way. It is separate because this
|
||||||
|
chain is one system that only talks to itself — jackett-api, sonarr-api, radarr-api, lidarr-api
|
||||||
|
and plex-api are exchanged among these modules and consumed by nothing else except
|
||||||
|
home-assistant — and because what runs here is one operator's media stack, pinned to the builds
|
||||||
|
in use, not shared infrastructure. Provisions cross repositories freely: lidarr requires
|
||||||
|
`postgres-database` from the catalogue's postgres, every module requires `route`; the mesh
|
||||||
|
resolves a requirement by name and never by where the manifest lives.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- A manifest names the software's own ports and nothing of the machine: machine ports are
|
||||||
|
assigned by the mesh, per node. No `host:container` pairs, no pins in an assignment.
|
||||||
|
- A manifest names no installation: no hostnames, paths of a particular machine, or people.
|
||||||
|
Names come from `${bound:route:name}`, places from `${dir:<id>}`, values from settings.
|
||||||
|
- Every secret a module needs is declared under `own-secrets` (minted, or accepted once for an
|
||||||
|
adopted instance); a provision's credential arrives with its binding.
|
||||||
|
- Each module carries a small runtime sidecar (`tools/index.ts`, built by its `Dockerfile` on the
|
||||||
|
mesh-tools bases) with a few query tools — the working example to extend.
|
||||||
|
|
||||||
|
Before pushing, check every manifest together, the way registration does:
|
||||||
|
|
||||||
|
```
|
||||||
|
mesh-controller module check modules/*/module.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Register a module from this repository through the forge seat:
|
||||||
|
|
||||||
|
```
|
||||||
|
module add /<m>.json --source novox/mesh-media-catalog --self --path modules/<m> --ref main --commit <sha>
|
||||||
|
build novox/mesh-media-catalog --self --path modules/<m> --ref main
|
||||||
|
```
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# bazarr's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/bazarr
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc apikey.ts client.ts index.ts tools/index.ts servarr/settings.ts servarr/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/bazarr/dist /app/modules/bazarr/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/bazarr/dist/index.js,/app/modules/bazarr/dist/tools/index.js
|
||||||
|
# NOT dist/servarr/index.js: that is a step the host runs to completion, named by the `servarr`
|
||||||
|
# container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run inside the
|
||||||
|
# serving sidecar too, and exit it.
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
// bazarr's own API key, found where bazarr keeps it. Shared by the client (tools, events) and the
|
||||||
|
// Servarr step, and kept apart from client.ts so the step and its test load it without the client.
|
||||||
|
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* bazarr's own API key, read from where bazarr keeps it: `auth.apikey` in `config/config.yaml` under
|
||||||
|
* its config directory. bazarr makes this key itself on first start and nothing lets the mesh set it,
|
||||||
|
* so a key the mesh minted could never work; reading bazarr's own file needs nothing accepted and
|
||||||
|
* stays right if the operator regenerates the key in bazarr's settings screen. The file is read, never
|
||||||
|
* written. Undefined when the file or the key is not there.
|
||||||
|
*/
|
||||||
|
export function apiKeyFromConfigDir(configDir?: string): string | undefined {
|
||||||
|
if (!configDir) return undefined;
|
||||||
|
let text: string;
|
||||||
|
try { text = readFileSync(`${configDir.replace(/\/$/, "")}/config/config.yaml`, "utf8"); }
|
||||||
|
catch { return undefined; }
|
||||||
|
return apiKeyFromConfigYaml(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `auth.apikey` from the text of bazarr's config.yaml — a top-level `auth:` mapping, one level deep. */
|
||||||
|
export function apiKeyFromConfigYaml(text: string): string | undefined {
|
||||||
|
let inAuth = false;
|
||||||
|
for (const line of text.split(/\r?\n/)) {
|
||||||
|
if (/^\S/.test(line)) {
|
||||||
|
inAuth = /^auth:\s*$/.test(line);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!inAuth) continue;
|
||||||
|
const m = line.match(/^\s+apikey:\s*(.*?)\s*$/);
|
||||||
|
if (m) {
|
||||||
|
const v = m[1].replace(/^(['"])(.*)\1$/, "$2").trim();
|
||||||
|
return v || undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
// The Bazarr API client — bazarr's own code, living in the module (novox/hq ADR 0039). Bazarr
|
||||||
|
// manages subtitles for a Sonarr/Radarr library: it tracks which episodes and movies are still
|
||||||
|
// missing subtitles, searches providers for them, and records what it downloaded. This client
|
||||||
|
// talks its /api surface (keyed by an X-API-KEY header); bazarr's tools and events import it.
|
||||||
|
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
import { apiKeyFromConfigDir } from "./apikey.js";
|
||||||
|
|
||||||
|
export interface WantedSubtitle {
|
||||||
|
kind: "episode" | "movie";
|
||||||
|
title: string; // series + episode, or movie title
|
||||||
|
path?: string;
|
||||||
|
seriesId?: number; // sonarr series id (episodes)
|
||||||
|
episodeId?: number; // sonarr episode id (episodes)
|
||||||
|
radarrId?: number; // radarr movie id (movies)
|
||||||
|
missing: string[]; // language names still missing
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProviderSubtitle {
|
||||||
|
provider: string;
|
||||||
|
language: string;
|
||||||
|
hearingImpaired: boolean;
|
||||||
|
forced: boolean;
|
||||||
|
score?: number;
|
||||||
|
release?: string;
|
||||||
|
subtitle: string; // the opaque token Bazarr uses to download this exact result
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HistoryEntry {
|
||||||
|
kind: "episode" | "movie";
|
||||||
|
id: string; // stable dedup key across polls
|
||||||
|
title: string;
|
||||||
|
language?: string;
|
||||||
|
provider?: string;
|
||||||
|
path?: string;
|
||||||
|
timestamp?: string;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
|
||||||
|
function meshConfig(file?: string): Record<string, string> {
|
||||||
|
if (!file) return {};
|
||||||
|
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
|
||||||
|
catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read a secret the mesh mounted at a file path (an own-secret delivered by `secret accept`);
|
||||||
|
* absent or unreadable yields undefined so callers fall back rather than crash. */
|
||||||
|
function readSecret(file?: string): string | undefined {
|
||||||
|
if (!file) return undefined;
|
||||||
|
try { return readFileSync(file, "utf8").trim() || undefined; }
|
||||||
|
catch { return undefined; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BazarrClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly apiKey: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build from the module's resolved environment. Bazarr's API is keyed; without URL and key
|
||||||
|
* there is nothing to talk to, so this throws rather than run half-configured. */
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): BazarrClient {
|
||||||
|
const cfg = meshConfig(env.MESH_BAZARR_CONFIG_FILE);
|
||||||
|
const url = cfg.url ?? env.MESH_BAZARR_URL;
|
||||||
|
const apiKey =
|
||||||
|
cfg.apiKey ??
|
||||||
|
apiKeyFromConfigDir(env.MESH_BAZARR_CONFIG_DIR) ??
|
||||||
|
readSecret(env.MESH_BAZARR_API_KEY_FILE) ??
|
||||||
|
env.MESH_BAZARR_API_KEY;
|
||||||
|
if (!url) throw new Error("no Bazarr URL — set MESH_BAZARR_URL");
|
||||||
|
if (!apiKey) throw new Error("no Bazarr API key — bazarr's config/config.yaml under MESH_BAZARR_CONFIG_DIR has none");
|
||||||
|
return new BazarrClient(url, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async request(method: string, path: string, params: Record<string, string> = {}): Promise<any> {
|
||||||
|
const url = new URL(`${this.baseUrl}/api${path}`);
|
||||||
|
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||||
|
const res = await fetch(url.toString(), { method, headers: { "X-API-KEY": this.apiKey, Accept: "application/json" } });
|
||||||
|
if (!res.ok) throw new Error(`Bazarr API ${method} ${path}: ${res.status} ${await res.text()}`);
|
||||||
|
// Downloads/patches return an empty body; only GETs carry JSON.
|
||||||
|
const text = await res.text();
|
||||||
|
return text ? JSON.parse(text) : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
private get(path: string, params?: Record<string, string>): Promise<any> {
|
||||||
|
return this.request("GET", path, params);
|
||||||
|
}
|
||||||
|
|
||||||
|
private languageNames(missing: any[]): string[] {
|
||||||
|
return (missing ?? []).map((m: any) => m?.name ?? m?.code2 ?? m?.code3).filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Episodes and movies still missing subtitles — Bazarr's core "what's left to do" list. */
|
||||||
|
async getWanted(limit = 50): Promise<WantedSubtitle[]> {
|
||||||
|
const [eps, movies] = await Promise.all([
|
||||||
|
this.get("/episodes/wanted", { start: "0", length: String(limit) }),
|
||||||
|
this.get("/movies/wanted", { start: "0", length: String(limit) }),
|
||||||
|
]);
|
||||||
|
const episodes: WantedSubtitle[] = (eps?.data ?? []).map((e: any) => ({
|
||||||
|
kind: "episode" as const,
|
||||||
|
title: `${e.seriesTitle ?? e.series ?? "Unknown"} — ${e.episodeTitle ?? e.episode_title ?? ""}`.trim(),
|
||||||
|
path: e.path,
|
||||||
|
seriesId: e.sonarrSeriesId,
|
||||||
|
episodeId: e.sonarrEpisodeId,
|
||||||
|
missing: this.languageNames(e.missing_subtitles),
|
||||||
|
}));
|
||||||
|
const films: WantedSubtitle[] = (movies?.data ?? []).map((m: any) => ({
|
||||||
|
kind: "movie" as const,
|
||||||
|
title: m.title ?? "Unknown",
|
||||||
|
path: m.path,
|
||||||
|
radarrId: m.radarrId,
|
||||||
|
missing: this.languageNames(m.missing_subtitles),
|
||||||
|
}));
|
||||||
|
return [...episodes, ...films];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ask providers what subtitles are available for one wanted episode — a manual search. */
|
||||||
|
async searchEpisode(episodeId: number): Promise<ProviderSubtitle[]> {
|
||||||
|
const raw = await this.get("/providers/episodes", { episodeid: String(episodeId) });
|
||||||
|
return this.mapProviderResults(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ask providers what subtitles are available for one movie — a manual search. */
|
||||||
|
async searchMovie(radarrId: number): Promise<ProviderSubtitle[]> {
|
||||||
|
const raw = await this.get("/providers/movies", { radarrid: String(radarrId) });
|
||||||
|
return this.mapProviderResults(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapProviderResults(raw: any): ProviderSubtitle[] {
|
||||||
|
const list = Array.isArray(raw) ? raw : (raw?.data ?? []);
|
||||||
|
return list.map((r: any) => ({
|
||||||
|
provider: r.provider,
|
||||||
|
language: r.language?.name ?? r.language ?? "unknown",
|
||||||
|
hearingImpaired: Boolean(r.hearing_impaired ?? r.hi),
|
||||||
|
forced: Boolean(r.forced),
|
||||||
|
score: r.score,
|
||||||
|
release: r.release_info?.[0] ?? r.release_info,
|
||||||
|
subtitle: r.subtitle,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recent subtitle-download history, episodes and movies together, newest first. Each entry
|
||||||
|
* carries a stable id so the events poller can tell a fresh download from one already seen. */
|
||||||
|
async getHistory(limit = 40): Promise<HistoryEntry[]> {
|
||||||
|
const [eps, movies] = await Promise.all([
|
||||||
|
this.get("/episodes/history", { start: "0", length: String(limit) }),
|
||||||
|
this.get("/movies/history", { start: "0", length: String(limit) }),
|
||||||
|
]);
|
||||||
|
const key = (kind: string, r: any): string =>
|
||||||
|
`${kind}:${r.timestamp ?? r.parsed_timestamp ?? ""}:${r.subtitles_path ?? r.path ?? ""}:${r.language?.code3 ?? r.language ?? ""}`;
|
||||||
|
const episodes: HistoryEntry[] = (eps?.data ?? []).map((r: any) => ({
|
||||||
|
kind: "episode" as const,
|
||||||
|
id: key("episode", r),
|
||||||
|
title: `${r.seriesTitle ?? "Unknown"} — ${r.episodeTitle ?? ""}`.trim(),
|
||||||
|
language: r.language?.name ?? r.language,
|
||||||
|
provider: r.provider,
|
||||||
|
path: r.subtitles_path,
|
||||||
|
timestamp: r.timestamp,
|
||||||
|
description: r.description,
|
||||||
|
}));
|
||||||
|
const films: HistoryEntry[] = (movies?.data ?? []).map((r: any) => ({
|
||||||
|
kind: "movie" as const,
|
||||||
|
id: key("movie", r),
|
||||||
|
title: r.title ?? "Unknown",
|
||||||
|
language: r.language?.name ?? r.language,
|
||||||
|
provider: r.provider,
|
||||||
|
path: r.subtitles_path,
|
||||||
|
timestamp: r.timestamp,
|
||||||
|
description: r.description,
|
||||||
|
}));
|
||||||
|
return [...episodes, ...films];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// bazarr's events. The tool runtime imports this once the broker is bound. Bazarr's one genuinely
|
||||||
|
// observable thing is a subtitle arriving: it works away in the background, searching providers for
|
||||||
|
// the missing-subtitle list, and when it succeeds a subtitle appears in its history. That is worth
|
||||||
|
// announcing to the mesh.
|
||||||
|
//
|
||||||
|
// Emits (novox/hq ADR 0041/0042):
|
||||||
|
// module.bazarr.subtitle.downloaded — a subtitle was fetched for an episode or movie
|
||||||
|
//
|
||||||
|
// Bazarr has nothing on the mesh it usefully reacts to (a download completing is Sonarr/Radarr's
|
||||||
|
// business, and they trigger Bazarr directly), so it consumes nothing — a pure emitter.
|
||||||
|
//
|
||||||
|
// The event is observation-based: poll history and diff. Primed silently on the first look, or a
|
||||||
|
// restart would re-announce the whole recent history as freshly downloaded.
|
||||||
|
|
||||||
|
import { emit } from "@novox/mesh-sdk/events";
|
||||||
|
import { BazarrClient } from "./client.js";
|
||||||
|
|
||||||
|
const bazarr = BazarrClient.fromEnv();
|
||||||
|
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let primed = false;
|
||||||
|
async function pollHistory(): Promise<void> {
|
||||||
|
const entries = await bazarr.getHistory(40);
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (seen.has(entry.id)) continue;
|
||||||
|
if (primed) {
|
||||||
|
await emit("subtitle.downloaded", {
|
||||||
|
kind: entry.kind,
|
||||||
|
title: entry.title,
|
||||||
|
language: entry.language,
|
||||||
|
provider: entry.provider,
|
||||||
|
path: entry.path,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
seen.add(entry.id);
|
||||||
|
}
|
||||||
|
primed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||||
|
const run = (): void => void fn().catch((err) => console.error(`[bazarr] ${err}`));
|
||||||
|
setInterval(run, everyMs);
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
tick(pollHistory, 60_000);
|
||||||
|
|
||||||
|
console.log("[bazarr] watching subtitle-download history");
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
{
|
||||||
|
"module": "bazarr",
|
||||||
|
"version": "1",
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"subtitle.downloaded"
|
||||||
|
],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/bazarr/broker"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 6767,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "managing subtitles"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accesses": [
|
||||||
|
{
|
||||||
|
"path": "/services/media/movies",
|
||||||
|
"mode": "read-write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/series",
|
||||||
|
"mode": "read-write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/anime",
|
||||||
|
"mode": "read-write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/downloads",
|
||||||
|
"mode": "read"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/bazarr",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "bazarr",
|
||||||
|
"image": "lscr.io/linuxserver/bazarr@sha256:d24bd0048c759a468970989e9df11a6b96a7628d556d00f923e60a35ba59237b",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC"
|
||||||
|
},
|
||||||
|
"ports": [
|
||||||
|
"6767"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"/services/media/movies:/movies",
|
||||||
|
"/services/media/series:/series",
|
||||||
|
"/services/media/anime:/anime",
|
||||||
|
"/services/media/downloads:/downloads"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/config.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-bazarr",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/bazarr/broker:/run/secrets/broker:ro",
|
||||||
|
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||||
|
"${dir:config}:/var/lib/bazarr/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_BAZARR_URL": "http://127.0.0.1:${port:6767}",
|
||||||
|
"MESH_BAZARR_CONFIG_FILE": "/run/config/config.json",
|
||||||
|
"MESH_BAZARR_CONFIG_DIR": "/var/lib/bazarr/config"
|
||||||
|
},
|
||||||
|
"restart-on": [
|
||||||
|
"runtime-config"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "servarr",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-bazarr-servarr",
|
||||||
|
"network": "host",
|
||||||
|
"run-once": true,
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/var/lib/bazarr/config:ro",
|
||||||
|
"${dir:state}/sonarr-api.json:/run/servarr/sonarr-api.json:ro",
|
||||||
|
"${dir:state}/sonarr-api.secret:/run/servarr/sonarr-api.secret:ro",
|
||||||
|
"${dir:state}/radarr-api.json:/run/servarr/radarr-api.json:ro",
|
||||||
|
"${dir:state}/radarr-api.secret:/run/servarr/radarr-api.secret:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BAZARR_URL": "http://127.0.0.1:${port:6767}",
|
||||||
|
"MESH_BAZARR_CONFIG_DIR": "/var/lib/bazarr/config",
|
||||||
|
"MESH_SERVARR_DIR": "/run/servarr"
|
||||||
|
},
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"/app/modules/bazarr/dist/servarr/index.js"
|
||||||
|
],
|
||||||
|
"restart-on": [
|
||||||
|
"bound-sonarr-api",
|
||||||
|
"secret-sonarr-api",
|
||||||
|
"bound-radarr-api",
|
||||||
|
"secret-radarr-api"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requires": [
|
||||||
|
"radarr-api",
|
||||||
|
"route",
|
||||||
|
"sonarr-api"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "subs",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json",
|
||||||
|
"sonarr-api": "${dir:state}/sonarr-api.json",
|
||||||
|
"radarr-api": "${dir:state}/radarr-api.json"
|
||||||
|
},
|
||||||
|
"secrets": {
|
||||||
|
"sonarr-api": "${dir:state}/sonarr-api.secret",
|
||||||
|
"radarr-api": "${dir:state}/radarr-api.secret"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-bazarr",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "bazarr — subtitle management. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc apikey.ts client.ts index.ts tools/index.ts servarr/settings.ts servarr/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist",
|
||||||
|
"typecheck": "tsc -p tsconfig.json",
|
||||||
|
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
// bazarr's Servarr step — run once by the host after bazarr's server starts, and run again whenever a
|
||||||
|
// binding or pair credential it reads changes (the container's `restart-on`, novox/hq ADR 0099).
|
||||||
|
//
|
||||||
|
// **A step, not a loop**: everything it does is a function of files the mesh writes, and the host
|
||||||
|
// already knows when they change. It connects to no broker.
|
||||||
|
//
|
||||||
|
// Exits non-zero when any app could not be put right — a refused credential, an unreachable app, a
|
||||||
|
// bazarr that would not keep the settings — so the node reports the step failed and the host runs it
|
||||||
|
// again on the next apply. Declared last in the manifest, so its failing gates nothing else of
|
||||||
|
// bazarr's (novox/hq ADR 0136).
|
||||||
|
//
|
||||||
|
// Reads, per app, `<dir>/<provision>.json` (the binding) and `<dir>/<provision>.secret` (the pair
|
||||||
|
// credential), where <dir> is MESH_SERVARR_DIR; and bazarr's own key from bazarr's own config.yaml
|
||||||
|
// under MESH_BAZARR_CONFIG_DIR. Never prints a key.
|
||||||
|
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import { apiKeyFromConfigDir } from "../apikey.js";
|
||||||
|
import { APPS, bazarrReady, readBinding, readIfThere, reconcileApp, type Http } from "./settings.js";
|
||||||
|
|
||||||
|
const dir = process.env.MESH_SERVARR_DIR ?? "/run/servarr";
|
||||||
|
const url = process.env.MESH_BAZARR_URL ?? "http://127.0.0.1:6767";
|
||||||
|
const waitSeconds = Number(process.env.MESH_BAZARR_WAIT_SECONDS ?? "180");
|
||||||
|
|
||||||
|
const http: Http = { fetch: (u, init) => fetch(u, init) };
|
||||||
|
|
||||||
|
const bazarrUp = await bazarrReady(http, { url, apiKey: "" }, waitSeconds * 1000);
|
||||||
|
if (!bazarrUp) {
|
||||||
|
console.error(`[bazarr-servarr] bazarr did not answer at ${url} within ${waitSeconds}s`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read after bazarr answers: on a first start bazarr writes its config.yaml, key included, as it boots.
|
||||||
|
const apiKey = apiKeyFromConfigDir(process.env.MESH_BAZARR_CONFIG_DIR);
|
||||||
|
if (!apiKey) {
|
||||||
|
console.error("[bazarr-servarr] no bazarr API key in bazarr's config/config.yaml under MESH_BAZARR_CONFIG_DIR");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const bazarr = { url, apiKey };
|
||||||
|
|
||||||
|
let failed = 0;
|
||||||
|
for (const spec of APPS) {
|
||||||
|
const outcome = await reconcileApp(
|
||||||
|
http,
|
||||||
|
bazarr,
|
||||||
|
spec,
|
||||||
|
await readBinding(join(dir, `${spec.provision}.json`)),
|
||||||
|
await readIfThere(join(dir, `${spec.provision}.secret`)),
|
||||||
|
);
|
||||||
|
switch (outcome.result) {
|
||||||
|
case "unchanged":
|
||||||
|
console.log(`[bazarr-servarr] ${outcome.app}: already as the mesh says; key taken by ${outcome.app}`);
|
||||||
|
break;
|
||||||
|
case "written":
|
||||||
|
console.log(`[bazarr-servarr] ${outcome.app}: wrote ${outcome.fields.join(", ")}; key taken by ${outcome.app}`);
|
||||||
|
break;
|
||||||
|
case "refused":
|
||||||
|
failed++;
|
||||||
|
console.error(`[bazarr-servarr] ${outcome.app}: ${outcome.problem}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.exitCode = failed > 0 ? 1 : 0;
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
// Where bazarr reaches Sonarr and Radarr — decided by the mesh, written into bazarr by bazarr's own
|
||||||
|
// API.
|
||||||
|
//
|
||||||
|
// **Why this exists.** bazarr keeps its connection to each app in its own `config/config.yaml`, which
|
||||||
|
// it holds in memory and writes back whenever its settings change — so the mesh cannot own that file
|
||||||
|
// without the two overwriting each other. bazarr requires `sonarr-api` and `radarr-api`; the mesh
|
||||||
|
// delivers, for each, a binding (where the app is: `at`, and what it serves: `port`, `scheme`,
|
||||||
|
// `url-base`) and a pair credential (the app's API key, accepted by the operator — a Servarr app has
|
||||||
|
// exactly one key and the mesh cannot mint it, novox/hq ADR 0092). This step reads those files and
|
||||||
|
// makes bazarr's settings say the same thing, through `POST /api/system/settings` — the call bazarr's
|
||||||
|
// own settings screen makes, which also restarts bazarr's SignalR feed from the app.
|
||||||
|
//
|
||||||
|
// **Only the connection, and only when it differs.** Host, port, TLS, base path and API key. Whether
|
||||||
|
// bazarr uses the app at all (`general.use_sonarr`), sync intervals, excluded tags, path mappings and
|
||||||
|
// every other choice the operator made are left exactly as they are: the mesh knows where the app is,
|
||||||
|
// not what bazarr should do with it.
|
||||||
|
//
|
||||||
|
// **A credential the app refuses is never written.** Until the operator accepts the app's key for this
|
||||||
|
// pair the mesh delivers a value it minted, which no Servarr app accepts. Writing it would replace a
|
||||||
|
// working key in bazarr with a dead one, so the key is tried against the app first; refused, nothing
|
||||||
|
// for that app is written and the step fails naming the `secret accept` that fixes it.
|
||||||
|
//
|
||||||
|
// The same shape as ombi's step (modules/ombi/servarr), repeated rather than shared because a module
|
||||||
|
// is built from its own directory and nothing else (novox/hq ADR 0069). Pure logic and a small HTTP
|
||||||
|
// seam, tested against fakes (test/servarr.test.ts).
|
||||||
|
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
|
||||||
|
/** One Servarr app bazarr connects to. */
|
||||||
|
export interface ServarrApp {
|
||||||
|
/** The section of bazarr's settings that holds the connection: settings.<app>.* */
|
||||||
|
app: "sonarr" | "radarr";
|
||||||
|
/** The provision it is required as — the manifest's `requires`, `binds` and `secrets` key. */
|
||||||
|
provision: string;
|
||||||
|
/** The app's own status endpoint, which answers 401 to a wrong key. */
|
||||||
|
statusPath: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const APPS: readonly ServarrApp[] = [
|
||||||
|
{ app: "sonarr", provision: "sonarr-api", statusPath: "/api/v3/system/status" },
|
||||||
|
{ app: "radarr", provision: "radarr-api", statusPath: "/api/v3/system/status" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** The connection fields bazarr keeps for an app — the only ones this step ever writes. */
|
||||||
|
export interface Connection {
|
||||||
|
ip: string;
|
||||||
|
port: number;
|
||||||
|
ssl: boolean;
|
||||||
|
/** bazarr's base_url: "" at the root, otherwise "/base". */
|
||||||
|
base_url: string;
|
||||||
|
apikey: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the mesh wrote at `binds.<provision>`: the binding document. */
|
||||||
|
export interface Binding {
|
||||||
|
provision?: string;
|
||||||
|
from?: string;
|
||||||
|
at?: string;
|
||||||
|
as?: string;
|
||||||
|
serves?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Wanted = { ok: true; connection: Connection; from: string } | { ok: false; problem: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The connection the mesh says bazarr should use. Refused rather than guessed when the binding cannot
|
||||||
|
* be dialled from bazarr's own container: a loopback `at` is bazarr's container itself.
|
||||||
|
*/
|
||||||
|
export function wanted(spec: ServarrApp, binding: Binding | undefined, credential: string | undefined): Wanted {
|
||||||
|
if (!binding) {
|
||||||
|
return { ok: false, problem: `no binding for ${spec.provision} was delivered — the mesh writes it before this step runs` };
|
||||||
|
}
|
||||||
|
const at = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||||
|
const serves = binding.serves ?? {};
|
||||||
|
const port = Number(serves.port);
|
||||||
|
if (!at) return { ok: false, problem: `the ${spec.provision} binding names no host (at)` };
|
||||||
|
if (isLoopback(at)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
problem:
|
||||||
|
`the ${spec.provision} binding says ${spec.app} is at ${at}, which from bazarr's own container is ` +
|
||||||
|
`bazarr itself. The mesh hands loopback to a machine that is not on the private network; put it ` +
|
||||||
|
`on the private network so ${spec.app} has an address bazarr can dial`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||||
|
return { ok: false, problem: `the ${spec.provision} binding serves no usable port (${String(serves.port)})` };
|
||||||
|
}
|
||||||
|
const scheme = typeof serves.scheme === "string" && serves.scheme ? serves.scheme : "http";
|
||||||
|
if (scheme !== "http" && scheme !== "https") {
|
||||||
|
return { ok: false, problem: `the ${spec.provision} binding serves scheme ${scheme}, which bazarr cannot dial` };
|
||||||
|
}
|
||||||
|
const key = (credential ?? "").trim();
|
||||||
|
if (!key) return { ok: false, problem: `the ${spec.provision} credential is empty or was not delivered` };
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
from: typeof binding.from === "string" ? binding.from : "",
|
||||||
|
connection: { ip: at, port, ssl: scheme === "https", base_url: baseUrlOf(serves["url-base"]), apikey: key },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A URL base as bazarr stores it: "" for none, else one leading slash and no trailing one. */
|
||||||
|
export function baseUrlOf(urlBase: unknown): string {
|
||||||
|
const trimmed = typeof urlBase === "string" ? urlBase.trim().replace(/^\/+|\/+$/g, "") : "";
|
||||||
|
return trimmed === "" ? "" : `/${trimmed}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLoopback(host: string): boolean {
|
||||||
|
const h = host.toLowerCase();
|
||||||
|
return h === "localhost" || h === "::1" || h === "[::1]" || /^127\./.test(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which connection fields differ between what bazarr holds and what the mesh says. Names only. */
|
||||||
|
export function differing(current: Record<string, unknown> | undefined, want: Connection): (keyof Connection)[] {
|
||||||
|
const now = current ?? {};
|
||||||
|
const out: (keyof Connection)[] = [];
|
||||||
|
if (String(now.ip ?? "") !== want.ip) out.push("ip");
|
||||||
|
if (Number(now.port ?? 0) !== want.port) out.push("port");
|
||||||
|
if (Boolean(now.ssl) !== want.ssl) out.push("ssl");
|
||||||
|
if (baseUrlOf(now.base_url) !== want.base_url) out.push("base_url");
|
||||||
|
if (String(now.apikey ?? "") !== want.apikey) out.push("apikey");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form bazarr's settings endpoint takes for the differing fields: `settings-<app>-<field>`.
|
||||||
|
* bazarr casts "true"/"false" to booleans and digit strings to integers itself.
|
||||||
|
*/
|
||||||
|
export function settingsForm(spec: ServarrApp, want: Connection, fields: readonly (keyof Connection)[]): URLSearchParams {
|
||||||
|
const form = new URLSearchParams();
|
||||||
|
for (const f of fields) {
|
||||||
|
const v = want[f];
|
||||||
|
form.append(`settings-${spec.app}-${f}`, typeof v === "boolean" ? (v ? "true" : "false") : String(v));
|
||||||
|
}
|
||||||
|
return form;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's base URL as the step dials it — the same host and port bazarr will be given. */
|
||||||
|
export function appUrl(want: Connection): string {
|
||||||
|
const scheme = want.ssl ? "https" : "http";
|
||||||
|
const host = want.ip.includes(":") && !want.ip.startsWith("[") ? `[${want.ip}]` : want.ip;
|
||||||
|
return `${scheme}://${host}:${want.port}${want.base_url}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How one app came out. */
|
||||||
|
export type Outcome =
|
||||||
|
| { app: string; result: "unchanged" }
|
||||||
|
| { app: string; result: "written"; fields: string[] }
|
||||||
|
| { app: string; result: "refused"; problem: string };
|
||||||
|
|
||||||
|
/** The HTTP the step needs, so a test can stand fakes in for bazarr and the apps. */
|
||||||
|
export interface Http {
|
||||||
|
fetch(url: string, init?: { method?: string; headers?: Record<string, string>; body?: string }): Promise<{
|
||||||
|
status: number;
|
||||||
|
text(): Promise<string>;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Bazarr {
|
||||||
|
url: string;
|
||||||
|
apiKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bazarrCall(http: Http, bazarr: Bazarr, method: string, path: string, form?: URLSearchParams): Promise<unknown> {
|
||||||
|
const res = await http.fetch(`${bazarr.url.replace(/\/$/, "")}/api${path}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
"X-API-KEY": bazarr.apiKey,
|
||||||
|
Accept: "application/json",
|
||||||
|
...(form ? { "Content-Type": "application/x-www-form-urlencoded" } : {}),
|
||||||
|
},
|
||||||
|
body: form ? form.toString() : undefined,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
if (res.status < 200 || res.status >= 300) {
|
||||||
|
// bazarr's error body is a message, never a request echo, so it carries no key.
|
||||||
|
throw new Error(`bazarr ${method} ${path} answered ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
||||||
|
}
|
||||||
|
return text ? (JSON.parse(text) as unknown) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does the app take this key? `true` it does, `false` it refused it (401/403), and a thrown error
|
||||||
|
* when it could not be asked.
|
||||||
|
*/
|
||||||
|
export async function appTakes(http: Http, spec: ServarrApp, want: Connection): Promise<boolean> {
|
||||||
|
const res = await http.fetch(`${appUrl(want)}${spec.statusPath}`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: { "X-Api-Key": want.apikey, Accept: "application/json" },
|
||||||
|
});
|
||||||
|
if (res.status === 401 || res.status === 403) return false;
|
||||||
|
if (res.status >= 200 && res.status < 300) return true;
|
||||||
|
throw new Error(`${spec.app} answered ${res.status} at ${spec.statusPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The remedy for a refused key, in the controller's own words (ADR 0092). */
|
||||||
|
export function acceptRemedy(spec: ServarrApp, from: string): string {
|
||||||
|
return (
|
||||||
|
`${spec.app} refuses the ${spec.provision} credential the mesh delivered, so it was not written ` +
|
||||||
|
`into bazarr. A Servarr app has one API key and the mesh cannot make it: accept ${spec.app}'s own ` +
|
||||||
|
`key for this pair — \`secret accept <this node> bazarr ${spec.provision} --provider ${from || "<its node>"} ` +
|
||||||
|
`--from <file holding ${spec.app}'s ApiKey>\``
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring bazarr's connection to one app in line with the mesh: check the key against the app, compare,
|
||||||
|
* write only the differing connection fields, then read bazarr's settings back to confirm they took.
|
||||||
|
* Never throws: every failure is an outcome with a reason.
|
||||||
|
*/
|
||||||
|
export async function reconcileApp(
|
||||||
|
http: Http,
|
||||||
|
bazarr: Bazarr,
|
||||||
|
spec: ServarrApp,
|
||||||
|
binding: Binding | undefined,
|
||||||
|
credential: string | undefined,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
const w = wanted(spec, binding, credential);
|
||||||
|
// `in`, not `!w.ok`: the Dockerfile compiles without strict, where a boolean discriminant does not
|
||||||
|
// narrow.
|
||||||
|
if ("problem" in w) return { app: spec.app, result: "refused", problem: w.problem };
|
||||||
|
const want = w.connection;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!(await appTakes(http, spec, want))) {
|
||||||
|
return { app: spec.app, result: "refused", problem: acceptRemedy(spec, w.from) };
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return {
|
||||||
|
app: spec.app,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${spec.app} could not be asked whether it takes the key at ${want.ip}:${want.port}: ${message(err)}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const before = await sectionOf(http, bazarr, spec);
|
||||||
|
const fields = differing(before, want);
|
||||||
|
if (fields.length === 0) return { app: spec.app, result: "unchanged" };
|
||||||
|
await bazarrCall(http, bazarr, "POST", "/system/settings", settingsForm(spec, want, fields));
|
||||||
|
const still = differing(await sectionOf(http, bazarr, spec), want);
|
||||||
|
if (still.length > 0) {
|
||||||
|
return { app: spec.app, result: "refused", problem: `bazarr did not keep its ${spec.app} settings (${still.join(", ")})` };
|
||||||
|
}
|
||||||
|
return { app: spec.app, result: "written", fields };
|
||||||
|
} catch (err) {
|
||||||
|
return { app: spec.app, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sectionOf(http: Http, bazarr: Bazarr, spec: ServarrApp): Promise<Record<string, unknown> | undefined> {
|
||||||
|
const doc = (await bazarrCall(http, bazarr, "GET", "/system/settings")) as Record<string, unknown> | undefined;
|
||||||
|
return doc?.[spec.app] as Record<string, unknown> | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait for bazarr to answer, because the step runs right after its container starts. */
|
||||||
|
export async function bazarrReady(http: Http, bazarr: Bazarr, waitMs: number, pauseMs = 2000): Promise<boolean> {
|
||||||
|
const until = Date.now() + waitMs;
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
const res = await http.fetch(`${bazarr.url.replace(/\/$/, "")}/api/system/ping`, { method: "GET" });
|
||||||
|
if (res.status === 200) return true;
|
||||||
|
} catch {
|
||||||
|
// not listening yet
|
||||||
|
}
|
||||||
|
if (Date.now() >= until) return false;
|
||||||
|
await new Promise((r) => setTimeout(r, pauseMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A file the mesh wrote, or undefined when it is not there. */
|
||||||
|
export async function readIfThere(path: string | undefined): Promise<string | undefined> {
|
||||||
|
if (!path) return undefined;
|
||||||
|
return readFile(path, "utf8").catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A binding file parsed, or undefined when absent or not JSON. */
|
||||||
|
export async function readBinding(path: string | undefined): Promise<Binding | undefined> {
|
||||||
|
const raw = await readIfThere(path);
|
||||||
|
if (raw === undefined) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as Binding;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(err: unknown): string {
|
||||||
|
return err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// What holds bazarr's Servarr step (servarr/settings.ts): the connection bazarr keeps for Sonarr and
|
||||||
|
// Radarr is made to say what the mesh bound — host, port, TLS, base path, key — and nothing else
|
||||||
|
// bazarr keeps is sent; nothing is written when nothing differs; and a key the app refuses (the mesh's
|
||||||
|
// own minted value, before the operator accepts the app's key) is never written, with the
|
||||||
|
// `secret accept` that fixes it named. Also: bazarr's own key is found in its config.yaml's `auth`
|
||||||
|
// section and not in the `sonarr`/`radarr` sections that also carry an `apikey`.
|
||||||
|
//
|
||||||
|
// bazarr and the apps are fakes answering as the real ones do (checked against
|
||||||
|
// lscr.io/linuxserver/bazarr v1.6.1-ls364: GET/POST /api/system/settings with X-API-KEY, the form
|
||||||
|
// keys `settings-<section>-<field>`, 204 on save).
|
||||||
|
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
|
||||||
|
import { apiKeyFromConfigYaml } from "../apikey.ts";
|
||||||
|
import { APPS, baseUrlOf, differing, reconcileApp, wanted, type Binding, type Http, type ServarrApp } from "../servarr/settings.ts";
|
||||||
|
|
||||||
|
const SONARR = APPS.find((a) => a.app === "sonarr") as ServarrApp;
|
||||||
|
const RADARR = APPS.find((a) => a.app === "radarr") as ServarrApp;
|
||||||
|
const THE_KEY = "the-apps-own-key";
|
||||||
|
const BAZARR = { url: "http://127.0.0.1:6767", apiKey: "bazarr-key" };
|
||||||
|
|
||||||
|
function binding(provision: string, port: number, at = "ace.internal"): Binding {
|
||||||
|
return { binding: 1, provision, from: "ace", at, as: "mesh_ace_bazarr", serves: { scheme: "http", port, "url-base": "" } } as Binding;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Call {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
body?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** bazarr's settings (one document, sections per app) and the apps' key check, behind one fetch. */
|
||||||
|
function fakes(settings: Record<string, Record<string, unknown>>, opts: { appKey?: string; reachable?: boolean } = {}) {
|
||||||
|
const calls: Call[] = [];
|
||||||
|
const appKey = opts.appKey ?? THE_KEY;
|
||||||
|
const http: Http = {
|
||||||
|
async fetch(url, init) {
|
||||||
|
const method = init?.method ?? "GET";
|
||||||
|
calls.push({ method, url, body: init?.body });
|
||||||
|
const reply = (status: number, value?: unknown) => ({
|
||||||
|
status,
|
||||||
|
text: async () => (value === undefined ? "" : JSON.stringify(value)),
|
||||||
|
});
|
||||||
|
const u = new URL(url);
|
||||||
|
if (u.pathname.endsWith("/system/status")) {
|
||||||
|
if (opts.reachable === false) throw new Error("connect ECONNREFUSED");
|
||||||
|
return init?.headers?.["X-Api-Key"] === appKey ? reply(200, { version: "4" }) : reply(401);
|
||||||
|
}
|
||||||
|
if (init?.headers?.["X-API-KEY"] !== BAZARR.apiKey) return reply(401);
|
||||||
|
if (u.pathname !== "/api/system/settings") return reply(404);
|
||||||
|
if (method === "GET") return reply(200, settings);
|
||||||
|
// bazarr's save_settings: split the key, cast as bazarr casts, store.
|
||||||
|
for (const [k, raw] of new URLSearchParams(init?.body ?? "")) {
|
||||||
|
const [, section, field] = k.split("-");
|
||||||
|
let v: unknown = raw;
|
||||||
|
if (raw === "true") v = true;
|
||||||
|
else if (raw === "false") v = false;
|
||||||
|
else if (/^\d+$/.test(raw)) v = Number(raw);
|
||||||
|
settings[section] = { ...(settings[section] ?? {}), [field]: v };
|
||||||
|
}
|
||||||
|
return reply(204);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { http, calls, settings };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ace's bazarr today: the apps by container name on HAL's shared network. */
|
||||||
|
function aceToday(): Record<string, Record<string, unknown>> {
|
||||||
|
return {
|
||||||
|
general: { use_sonarr: true, use_radarr: true, port: 6767 },
|
||||||
|
sonarr: { ip: "sonarr", port: 8989, ssl: false, base_url: "", apikey: THE_KEY, series_sync: 15, excluded_series_types: ["anime"] },
|
||||||
|
radarr: { ip: "radarr", port: 7878, ssl: false, base_url: "", apikey: THE_KEY, movies_sync: 15 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test("moving an app writes only host and port, and leaves every other setting alone", async () => {
|
||||||
|
const f = fakes(aceToday());
|
||||||
|
const out = await reconcileApp(f.http, BAZARR, SONARR, binding("sonarr-api", 20010), THE_KEY);
|
||||||
|
assert.deepEqual(out, { app: "sonarr", result: "written", fields: ["ip", "port"] });
|
||||||
|
const post = f.calls.find((c) => c.method === "POST");
|
||||||
|
assert.ok(post);
|
||||||
|
assert.deepEqual([...new URLSearchParams(post.body ?? "").keys()].sort(), ["settings-sonarr-ip", "settings-sonarr-port"]);
|
||||||
|
assert.equal(f.settings.sonarr.ip, "ace.internal");
|
||||||
|
assert.equal(f.settings.sonarr.port, 20010);
|
||||||
|
assert.deepEqual(f.settings.sonarr.excluded_series_types, ["anime"]);
|
||||||
|
assert.equal(f.settings.radarr.ip, "radarr", "radarr is its own app and was not touched");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("nothing is written when bazarr already says what the mesh says", async () => {
|
||||||
|
const s = aceToday();
|
||||||
|
s.radarr = { ...s.radarr, ip: "ace.internal", port: 20011 };
|
||||||
|
const f = fakes(s);
|
||||||
|
const out = await reconcileApp(f.http, BAZARR, RADARR, binding("radarr-api", 20011), THE_KEY);
|
||||||
|
assert.deepEqual(out, { app: "radarr", result: "unchanged" });
|
||||||
|
assert.equal(f.calls.filter((c) => c.method === "POST").length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a key the app refuses is never written, and the remedy is named", async () => {
|
||||||
|
const f = fakes(aceToday());
|
||||||
|
const out = await reconcileApp(f.http, BAZARR, SONARR, binding("sonarr-api", 20010), "a-value-the-mesh-minted");
|
||||||
|
assert.equal(out.result, "refused");
|
||||||
|
assert.match((out as { problem: string }).problem, /secret accept <this node> bazarr sonarr-api --provider ace/);
|
||||||
|
assert.equal(f.calls.filter((c) => c.method === "POST").length, 0);
|
||||||
|
assert.equal(f.settings.sonarr.apikey, THE_KEY, "the working key stays");
|
||||||
|
assert.equal(f.settings.sonarr.ip, "sonarr", "nothing moved either");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an unreachable app writes nothing", async () => {
|
||||||
|
const f = fakes(aceToday(), { reachable: false });
|
||||||
|
const out = await reconcileApp(f.http, BAZARR, SONARR, binding("sonarr-api", 20010), THE_KEY);
|
||||||
|
assert.equal(out.result, "refused");
|
||||||
|
assert.equal(f.calls.filter((c) => c.method === "POST").length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a loopback binding is refused: from bazarr's container that is bazarr", () => {
|
||||||
|
const w = wanted(SONARR, binding("sonarr-api", 8989, "127.0.0.1"), THE_KEY);
|
||||||
|
assert.equal(w.ok, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a new key is written when the operator accepted a different one", async () => {
|
||||||
|
const s = aceToday();
|
||||||
|
s.sonarr = { ...s.sonarr, ip: "ace.internal", port: 20010, apikey: "an-old-key" };
|
||||||
|
const f = fakes(s);
|
||||||
|
const out = await reconcileApp(f.http, BAZARR, SONARR, binding("sonarr-api", 20010), THE_KEY);
|
||||||
|
assert.deepEqual(out, { app: "sonarr", result: "written", fields: ["apikey"] });
|
||||||
|
assert.equal(f.settings.sonarr.apikey, THE_KEY);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("base paths compare as bazarr stores them", () => {
|
||||||
|
assert.equal(baseUrlOf(""), "");
|
||||||
|
assert.equal(baseUrlOf("/"), "");
|
||||||
|
assert.equal(baseUrlOf("sonarr/"), "/sonarr");
|
||||||
|
const want = { ip: "a", port: 1, ssl: false, base_url: "", apikey: "k" };
|
||||||
|
assert.deepEqual(differing({ ip: "a", port: 1, ssl: false, base_url: "/", apikey: "k" }, want), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("bazarr's own key is auth.apikey, not an app's", () => {
|
||||||
|
const yaml = [
|
||||||
|
"analytics:",
|
||||||
|
" enabled: false",
|
||||||
|
"auth:",
|
||||||
|
" apikey: 0123456789abcdef0123456789abcdef",
|
||||||
|
" password: ''",
|
||||||
|
" type: form",
|
||||||
|
"general:",
|
||||||
|
" port: 6767",
|
||||||
|
"sonarr:",
|
||||||
|
" apikey: not-this-one",
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
assert.equal(apiKeyFromConfigYaml(yaml), "0123456789abcdef0123456789abcdef");
|
||||||
|
assert.equal(apiKeyFromConfigYaml("sonarr:\n apikey: x\n"), undefined);
|
||||||
|
assert.equal(apiKeyFromConfigYaml("auth:\n apikey: ''\n"), undefined);
|
||||||
|
assert.equal(apiKeyFromConfigYaml("auth:\r\n apikey: 'abc'\r\n"), "abc");
|
||||||
|
});
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
// bazarr's tools — its own code (novox/hq ADR 0039), importing bazarr's 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 { BazarrClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getBazarrTools(bazarr: BazarrClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "bazarr_wanted",
|
||||||
|
description: "Episodes and movies still missing subtitles, with the languages each still needs.",
|
||||||
|
input: { limit: { type: "number", description: "max items per kind (default 50)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const wanted = await bazarr.getWanted(args.limit ? Number(args.limit) : 50);
|
||||||
|
return { count: wanted.length, wanted };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bazarr_search_subtitles",
|
||||||
|
description: "Manually search subtitle providers for one wanted item — pass an episodeId or a radarrId.",
|
||||||
|
input: {
|
||||||
|
episodeId: { type: "number", description: "a Sonarr episode id (from bazarr_wanted)" },
|
||||||
|
radarrId: { type: "number", description: "a Radarr movie id (from bazarr_wanted)" },
|
||||||
|
},
|
||||||
|
run: async (args) => {
|
||||||
|
if (args.episodeId !== undefined) {
|
||||||
|
const results = await bazarr.searchEpisode(Number(args.episodeId));
|
||||||
|
return { kind: "episode", episodeId: Number(args.episodeId), count: results.length, results };
|
||||||
|
}
|
||||||
|
if (args.radarrId !== undefined) {
|
||||||
|
const results = await bazarr.searchMovie(Number(args.radarrId));
|
||||||
|
return { kind: "movie", radarrId: Number(args.radarrId), count: results.length, results };
|
||||||
|
}
|
||||||
|
throw new Error("pass either episodeId or radarrId");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bazarr_history",
|
||||||
|
description: "Recent subtitle-download history — what was downloaded, for which title, from which provider.",
|
||||||
|
input: { limit: { type: "number", description: "max entries per kind (default 40)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const history = await bazarr.getHistory(args.limit ? Number(args.limit) : 40);
|
||||||
|
return { count: history.length, history };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exposed only when Bazarr is configured; otherwise bazarr contributes no tools rather than
|
||||||
|
// failing the whole runtime.
|
||||||
|
registerModuleTools("bazarr", (env) => {
|
||||||
|
try {
|
||||||
|
return getBazarrTools(BazarrClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"noEmit": true
|
||||||
|
},
|
||||||
|
"include": ["apikey.ts", "client.ts", "index.ts", "tools/index.ts", "servarr/settings.ts", "servarr/index.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# bookshelf's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/bookshelf
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts downloads/settings.ts downloads/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/bookshelf/dist /app/modules/bookshelf/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/bookshelf/dist/index.js,/app/modules/bookshelf/dist/tools/index.js
|
||||||
|
# NOT dist/downloads/index.js: that is a step the host runs to completion, named by the `downloads`
|
||||||
|
# container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run inside the
|
||||||
|
# serving sidecar too, and exit it.
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
// The Bookshelf API client — bookshelf's own code, living in the module (novox/hq ADR 0039).
|
||||||
|
// Ported from the shared hal `arr` client, but self-contained: in nox each Servarr app owns its own
|
||||||
|
// copy, so a change to Bookshelf's API rebuilds only bookshelf and nothing else. Both this module's
|
||||||
|
// tools and its events entrypoint import it, and nothing outside bookshelf does.
|
||||||
|
//
|
||||||
|
// Bookshelf is a Readarr fork (ghcr.io/pennydreadful/bookshelf). It speaks the Servarr v1 API; its
|
||||||
|
// content is "book". Unlike Sonarr/Radarr it exposes no calendar endpoint, so there is no calendar
|
||||||
|
// tool here — matching hal, which excluded bookshelf from its calendar-capable apps.
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
// Bookshelf speaks the v1 API; its content is "book".
|
||||||
|
const API_VERSION = "v1";
|
||||||
|
const CONTENT_ENDPOINT = "book";
|
||||||
|
const APP_NAME = "Bookshelf";
|
||||||
|
|
||||||
|
export interface BookshelfQueueItem {
|
||||||
|
/** The queue record id — stable while the item is in the queue, so events can diff on it. */
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
status: string;
|
||||||
|
size: string;
|
||||||
|
sizeleft: string;
|
||||||
|
timeleft?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookshelfContentItem {
|
||||||
|
title: string;
|
||||||
|
author?: string;
|
||||||
|
year?: number;
|
||||||
|
status?: string;
|
||||||
|
monitored: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BookshelfClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly apiKey: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the module's resolved environment. The URL defaults to the server on this node (the
|
||||||
|
* runtime shares its network), and the API key is read from MESH_BOOKSHELF_API_KEY or, failing
|
||||||
|
* that, discovered from the server's own config.xml under MESH_BOOKSHELF_CONFIG_DIR — the same
|
||||||
|
* file Bookshelf writes it to, so a running server needs nothing configured by hand. Throws when
|
||||||
|
* no key can be found, so the tools/events simply do not load (the harness treats the throw as
|
||||||
|
* "exposes nothing").
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): BookshelfClient {
|
||||||
|
const url = env.MESH_BOOKSHELF_URL ?? `http://127.0.0.1:${env.MESH_BOOKSHELF_PORT ?? "8787"}`;
|
||||||
|
const configDir = env.MESH_BOOKSHELF_CONFIG_DIR ?? "/config";
|
||||||
|
const apiKey = env.MESH_BOOKSHELF_API_KEY ?? BookshelfClient.detectApiKey(configDir);
|
||||||
|
if (!apiKey) {
|
||||||
|
throw new Error("Bookshelf not configured — set MESH_BOOKSHELF_API_KEY or make the config dir readable");
|
||||||
|
}
|
||||||
|
return new BookshelfClient(url, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Discover the API key from the server's config.xml, falling back to null. Every Servarr app
|
||||||
|
* writes <ApiKey> into config.xml at the root of its config directory. */
|
||||||
|
static detectApiKey(configDir: string): string | null {
|
||||||
|
const config = join(configDir, "config.xml");
|
||||||
|
if (existsSync(config)) {
|
||||||
|
const match = readFileSync(config, "utf8").match(/<ApiKey>([^<]+)<\/ApiKey>/);
|
||||||
|
if (match) return match[1];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async get(endpoint: string, params?: Record<string, string>): Promise<unknown> {
|
||||||
|
const url = new URL(`${this.baseUrl}/api/${API_VERSION}/${endpoint}`);
|
||||||
|
if (params) {
|
||||||
|
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||||
|
}
|
||||||
|
const res = await fetch(url.toString(), { headers: { "X-Api-Key": this.apiKey } });
|
||||||
|
if (!res.ok) throw new Error(`${APP_NAME} API /${endpoint}: ${res.status} ${await res.text()}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getStatus(): Promise<{ appName: string; version: string }> {
|
||||||
|
const data = (await this.get("system/status")) as { appName?: string; version?: string };
|
||||||
|
return { appName: data.appName || APP_NAME, version: data.version ?? "unknown" };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getContent(limit?: number): Promise<BookshelfContentItem[]> {
|
||||||
|
const data = await this.get(CONTENT_ENDPOINT);
|
||||||
|
const items: any[] = Array.isArray(data) ? data : ((data as any)?.records ?? []);
|
||||||
|
const mapped = items.map((item) => ({
|
||||||
|
title: item.title ?? "Unknown",
|
||||||
|
author: item.author?.authorName ?? item.authorName,
|
||||||
|
year: item.releaseDate ? new Date(item.releaseDate).getFullYear() : item.year,
|
||||||
|
status: item.status,
|
||||||
|
monitored: item.monitored ?? true,
|
||||||
|
}));
|
||||||
|
return limit ? mapped.slice(0, limit) : mapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Library search is a filter over existing content, not an indexer lookup — same as hal's. */
|
||||||
|
async searchContent(term: string): Promise<BookshelfContentItem[]> {
|
||||||
|
const all = await this.getContent();
|
||||||
|
const lower = term.toLowerCase();
|
||||||
|
return all.filter(
|
||||||
|
(item) =>
|
||||||
|
item.title.toLowerCase().includes(lower) ||
|
||||||
|
(item.author?.toLowerCase().includes(lower) ?? false),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getQueue(): Promise<{ totalRecords: number; items: BookshelfQueueItem[] }> {
|
||||||
|
const data = (await this.get("queue", { pageSize: "50" })) as { totalRecords?: number; records?: any[] };
|
||||||
|
const records = data.records ?? [];
|
||||||
|
return {
|
||||||
|
totalRecords: data.totalRecords ?? records.length,
|
||||||
|
items: records.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
title: r.title ?? r.book?.title ?? r.author?.authorName ?? "Unknown",
|
||||||
|
status: r.status ?? "unknown",
|
||||||
|
size: formatBytes(r.size ?? 0),
|
||||||
|
sizeleft: formatBytes(r.sizeleft ?? 0),
|
||||||
|
timeleft: r.timeleft,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes === 0) return "0 B";
|
||||||
|
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||||
|
return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
// The downloads step — run once by the host after the app's server starts, and again whenever a
|
||||||
|
// binding, a pair credential or the step's settings change (the container's `restart-on`,
|
||||||
|
// novox/hq ADR 0099). Byte-identical in sonarr, radarr, lidarr and bookshelf; see settings.ts.
|
||||||
|
//
|
||||||
|
// **A step, not a loop**: everything it does is a function of files the mesh writes, and the host
|
||||||
|
// already knows when they change. It connects to no broker.
|
||||||
|
//
|
||||||
|
// Exits non-zero when anything could not be put right — a refused credential, an unreachable
|
||||||
|
// provider, an entry the app would not save — so the node reports the step failed and the host
|
||||||
|
// runs it again on the next apply. Declared last in the manifest, so its failing gates nothing
|
||||||
|
// else of the module's (novox/hq ADR 0136).
|
||||||
|
//
|
||||||
|
// Reads, in MESH_DOWNLOADS_DIR, `<provision>.json` (the binding), `<provision>.secret` (the pair
|
||||||
|
// credential) and the settings file; remembers in MESH_DOWNLOADS_MEMORY the jackett hosts it has
|
||||||
|
// pointed feeds at, so a jackett that moves takes its feeds with it. Never prints a credential.
|
||||||
|
|
||||||
|
import { mkdir, rename, writeFile } from "node:fs/promises";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CLIENTS,
|
||||||
|
JACKETT,
|
||||||
|
acceptRemedy,
|
||||||
|
appConfig,
|
||||||
|
appReady,
|
||||||
|
listEntries,
|
||||||
|
providerTakes,
|
||||||
|
readIfThere,
|
||||||
|
readJson,
|
||||||
|
reconcileClient,
|
||||||
|
reconcileIndexers,
|
||||||
|
scrub,
|
||||||
|
stepSettings,
|
||||||
|
wanted,
|
||||||
|
type App,
|
||||||
|
type Binding,
|
||||||
|
type Http,
|
||||||
|
type Entry,
|
||||||
|
type Outcome,
|
||||||
|
type Took,
|
||||||
|
} from "./settings.js";
|
||||||
|
|
||||||
|
const module = process.env.MESH_DOWNLOADS_APP ?? "app";
|
||||||
|
const dir = process.env.MESH_DOWNLOADS_DIR ?? "/run/downloads";
|
||||||
|
const settingsFile = process.env.MESH_DOWNLOADS_SETTINGS ?? join(dir, "downloads.json");
|
||||||
|
const memoryFile = process.env.MESH_DOWNLOADS_MEMORY ?? "/var/lib/downloads/memory.json";
|
||||||
|
const waitSeconds = Number(process.env.MESH_DOWNLOADS_WAIT_SECONDS ?? "180");
|
||||||
|
const tag = `[${module}-downloads]`;
|
||||||
|
|
||||||
|
const http: Http = { fetch: (u, init) => fetch(u, init) };
|
||||||
|
const secrets: string[] = [];
|
||||||
|
const say = (line: string) => console.log(scrub(`${tag} ${line}`, secrets));
|
||||||
|
const fail = (line: string) => console.error(scrub(`${tag} ${line}`, secrets));
|
||||||
|
|
||||||
|
const config = appConfig((await readIfThere(process.env.MESH_DOWNLOADS_APP_CONFIG)) ?? "");
|
||||||
|
if (!config.apiKey) {
|
||||||
|
fail(`no API key in ${module}'s config.xml yet — ${module} writes it on its first start; the step runs again on the next apply`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
secrets.push(config.apiKey);
|
||||||
|
const app: App = {
|
||||||
|
module,
|
||||||
|
url: `${(process.env.MESH_DOWNLOADS_APP_URL ?? "http://127.0.0.1").replace(/\/$/, "")}${config.urlBase}`,
|
||||||
|
apiKey: config.apiKey,
|
||||||
|
api: process.env.MESH_DOWNLOADS_API ?? "v3",
|
||||||
|
};
|
||||||
|
const settings = stepSettings(await readJson(settingsFile));
|
||||||
|
|
||||||
|
if (!(await appReady(http, app, waitSeconds * 1000))) {
|
||||||
|
fail(`${module} did not answer at ${app.url} within ${waitSeconds}s`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
|
||||||
|
// The download clients.
|
||||||
|
let clients: Entry[];
|
||||||
|
try {
|
||||||
|
clients = await listEntries(http, app, "downloadclient");
|
||||||
|
} catch (err) {
|
||||||
|
fail(err instanceof Error ? err.message : String(err));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
for (const kind of CLIENTS) {
|
||||||
|
const credential = await readIfThere(join(dir, `${kind.provision}.secret`));
|
||||||
|
if (credential) secrets.push(credential.trim());
|
||||||
|
const w = wanted(kind.provision, (await readJson(join(dir, `${kind.provision}.json`))) as Binding | undefined, credential, true);
|
||||||
|
// `in`, not `!w.ok`: the Dockerfile compiles without strict, where a boolean discriminant does not
|
||||||
|
// narrow.
|
||||||
|
if ("problem" in w) {
|
||||||
|
outcomes.push({ what: kind.provision, result: "refused", problem: w.problem });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const ep = w.endpoint;
|
||||||
|
try {
|
||||||
|
if (!(await providerTakes(http, kind.provision, ep)).took) {
|
||||||
|
outcomes.push({
|
||||||
|
what: kind.provision,
|
||||||
|
result: "refused",
|
||||||
|
problem: acceptRemedy(app, settings.node, kind.provision, kind.provider, kind.secretName, ep.from),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: kind.provision,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${kind.provider} could not be asked whether it takes the credential at ${ep.host}:${ep.port}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
outcomes.push(...(await reconcileClient(http, app, kind, settings.names[kind.provision], ep, clients)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The indexers, through jackett.
|
||||||
|
{
|
||||||
|
const credential = await readIfThere(join(dir, `${JACKETT}.secret`));
|
||||||
|
if (credential) secrets.push(credential.trim());
|
||||||
|
const w = wanted(JACKETT, (await readJson(join(dir, `${JACKETT}.json`))) as Binding | undefined, credential, false);
|
||||||
|
if ("problem" in w) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: w.problem });
|
||||||
|
} else {
|
||||||
|
const ep = w.endpoint;
|
||||||
|
let took: Took | undefined;
|
||||||
|
try {
|
||||||
|
took = await providerTakes(http, JACKETT, ep);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: JACKETT,
|
||||||
|
result: "refused",
|
||||||
|
problem: `jackett could not be asked whether it takes the key at ${ep.host}:${ep.port}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (took && !took.took) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: acceptRemedy(app, settings.node, JACKETT, "jackett", "API key", ep.from) });
|
||||||
|
} else if (took) {
|
||||||
|
const memory = ((await readJson(memoryFile)) ?? {}) as Record<string, { hosts?: string[] } | undefined>;
|
||||||
|
const remembered = Array.isArray(memory[JACKETT]?.hosts) ? (memory[JACKETT]?.hosts as string[]) : [];
|
||||||
|
try {
|
||||||
|
const indexers = await listEntries(http, app, "indexer");
|
||||||
|
outcomes.push(
|
||||||
|
...(await reconcileIndexers(http, app, ep, took.configured ?? new Map(), settings.indexers, remembered, indexers)),
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: err instanceof Error ? err.message : String(err) });
|
||||||
|
}
|
||||||
|
// Remember where the feeds now point, so they are still recognised as the mesh's if jackett
|
||||||
|
// moves. Written whole and renamed, so a crash leaves the old memory, never half of one.
|
||||||
|
const hosts = [...new Set([...remembered, ep.host.toLowerCase()])].sort();
|
||||||
|
if (hosts.join() !== [...remembered].sort().join()) {
|
||||||
|
try {
|
||||||
|
await mkdir(dirname(memoryFile), { recursive: true });
|
||||||
|
await writeFile(`${memoryFile}.tmp`, JSON.stringify({ ...memory, [JACKETT]: { hosts } }, null, 2) + "\n", { mode: 0o600 });
|
||||||
|
await rename(`${memoryFile}.tmp`, memoryFile);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: JACKETT,
|
||||||
|
result: "notice",
|
||||||
|
note: `could not remember ${ep.host} as a jackett host (${err instanceof Error ? err.message : String(err)}); if jackett moves, list it in downloads.jackett-api.adopt-hosts`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let failed = 0;
|
||||||
|
for (const o of outcomes) {
|
||||||
|
switch (o.result) {
|
||||||
|
case "unchanged":
|
||||||
|
say(`${o.what}: already as the mesh says${o.untested ? "" : "; connection tested"}`);
|
||||||
|
break;
|
||||||
|
case "written":
|
||||||
|
say(`${o.what}: wrote ${o.fields.join(", ")}${o.untested ? "" : "; connection tested"}`);
|
||||||
|
break;
|
||||||
|
case "created":
|
||||||
|
say(`${o.what}: registered; connection tested`);
|
||||||
|
break;
|
||||||
|
case "notice":
|
||||||
|
say(`${o.what}: ${o.note}`);
|
||||||
|
break;
|
||||||
|
case "refused":
|
||||||
|
failed++;
|
||||||
|
fail(`${o.what}: ${o.problem}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.exitCode = failed > 0 ? 1 : 0;
|
||||||
@@ -0,0 +1,778 @@
|
|||||||
|
// Where a Servarr app reaches its download clients and its indexer proxy — decided by the mesh,
|
||||||
|
// written into the app by the app's own API.
|
||||||
|
//
|
||||||
|
// **One file, four copies.** sonarr, radarr, lidarr and bookshelf (a Readarr fork) keep their
|
||||||
|
// download clients and indexers behind the same API — `/api/v3/…` for the first two, `/api/v1/…`
|
||||||
|
// for the others — so this step is the same code in each. Each module builds from its own
|
||||||
|
// directory (novox/hq ADR 0069), so each carries a byte-identical copy under `downloads/`;
|
||||||
|
// `test/downloads.test.ts` checks the copies agree wherever the siblings are checked out beside
|
||||||
|
// it. Change all four together.
|
||||||
|
//
|
||||||
|
// **Why this exists.** The app keeps its connection to nzbget, qBittorrent and jackett in its own
|
||||||
|
// database, not in a file, so the mesh has nowhere to write `${bound:nzbget-api:at}` for it. The
|
||||||
|
// module requires `nzbget-api`, `qbittorrent-api` and `jackett-api`; the mesh delivers, for each,
|
||||||
|
// a binding (where the provider is — `at` — and what it serves: `port`, `scheme`, `url-base`, and
|
||||||
|
// for a download client the `username`) and a pair credential (nzbget's ControlPassword,
|
||||||
|
// qBittorrent's WebUI password, jackett's API key — each the provider's one and only, accepted by
|
||||||
|
// the operator per pair; the mesh cannot mint them). This step reads those files and makes the
|
||||||
|
// app's entries say the same thing.
|
||||||
|
//
|
||||||
|
// **Which entries are the mesh's.** Never a guess from what an entry looks like:
|
||||||
|
// - a download client is the mesh's when its name is the one the module's settings give for
|
||||||
|
// that provision (`downloads.<provision>.name`) and its kind is that provider's. On a fresh
|
||||||
|
// machine the step registers it under that name; on a migrated one the assignment names the
|
||||||
|
// entry the migration adopts ("NZBGet" on ace).
|
||||||
|
// - a Torznab indexer is the mesh's when it reads a jackett feed
|
||||||
|
// (`…/api/v2.0/indexers/<id>/results/torznab`) on a host the mesh put there — the bound `at`,
|
||||||
|
// one it bound before (remembered by the step), or one the settings adopt
|
||||||
|
// (`downloads.jackett-api.adopt-hosts`, which is how a migration names the entries that pointed
|
||||||
|
// at the old container). `downloads.jackett-api.indexers` lists the jackett indexers the app
|
||||||
|
// should have; one missing is registered.
|
||||||
|
// Everything else — every entry a person made, an nzbget elsewhere, a seedbox's jackett, a Newznab
|
||||||
|
// indexer — is left exactly as it is. **Nothing is ever deleted.**
|
||||||
|
//
|
||||||
|
// **Only the connection, and only when it differs.** Host, port, TLS, base path, user name and
|
||||||
|
// the credential. Categories, priorities, "enabled", seed criteria and every other choice made in
|
||||||
|
// the app are left alone. The stored credential cannot be read back (the app masks it), so the
|
||||||
|
// step asks the app to test the entry with the mesh's host and port and the credential it already
|
||||||
|
// holds: passing, the credential is already the provider's one and only; failing, the delivered
|
||||||
|
// credential is written.
|
||||||
|
//
|
||||||
|
// **A credential the provider refuses is never written.** Until the operator accepts the
|
||||||
|
// provider's secret for this pair, the mesh delivers a value it minted itself, which no provider
|
||||||
|
// will ever accept (novox/hq ADR 0092). Writing it would replace a working password with a dead
|
||||||
|
// one. So it is tried against the provider first; refused, nothing of that provision is written
|
||||||
|
// and the step fails naming the `secret accept` that fixes it.
|
||||||
|
//
|
||||||
|
// Pure logic and a small HTTP seam, so it is tested against fake servers (test/downloads.test.ts).
|
||||||
|
// Never prints a credential, an API key, or a URL carrying one.
|
||||||
|
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
|
||||||
|
/** A download-client provision and the shape of its entry in the app. */
|
||||||
|
export interface ClientKind {
|
||||||
|
provision: "nzbget-api" | "qbittorrent-api";
|
||||||
|
/** The app's `implementation` for it. */
|
||||||
|
implementation: "Nzbget" | "QBittorrent";
|
||||||
|
/** The provider, as a person calls it. */
|
||||||
|
provider: string;
|
||||||
|
/** What the pair credential is, in the provider's words. */
|
||||||
|
secretName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CLIENTS: readonly ClientKind[] = [
|
||||||
|
{ provision: "nzbget-api", implementation: "Nzbget", provider: "nzbget", secretName: "ControlPassword" },
|
||||||
|
{ provision: "qbittorrent-api", implementation: "QBittorrent", provider: "qBittorrent", secretName: "WebUI password" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const JACKETT = "jackett-api";
|
||||||
|
|
||||||
|
/** What the mesh wrote at `binds.<provision>`: the binding document. */
|
||||||
|
export interface Binding {
|
||||||
|
provision?: string;
|
||||||
|
from?: string;
|
||||||
|
at?: string;
|
||||||
|
as?: string;
|
||||||
|
serves?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a provider is, as the mesh bound it, and the credential for it. */
|
||||||
|
export interface Endpoint {
|
||||||
|
scheme: "http" | "https";
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
/** "" at the root, otherwise "/base" — one leading slash, none trailing. */
|
||||||
|
urlBase: string;
|
||||||
|
/** The user a download client logs in as; "" for jackett, which takes a key. */
|
||||||
|
username: string;
|
||||||
|
credential: string;
|
||||||
|
/** The provider's node, for the `secret accept` remedy. */
|
||||||
|
from: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Wanted = { ok: true; endpoint: Endpoint } | { ok: false; problem: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The endpoint the mesh says to use, from a binding and its pair credential.
|
||||||
|
*
|
||||||
|
* Refused rather than guessed when the binding cannot be dialled from the app's own container: a
|
||||||
|
* loopback `at` — what the mesh hands a machine that is not on the private network — is the app's
|
||||||
|
* container itself.
|
||||||
|
*/
|
||||||
|
export function wanted(
|
||||||
|
provision: string,
|
||||||
|
binding: Binding | undefined,
|
||||||
|
credential: string | undefined,
|
||||||
|
needsUser: boolean,
|
||||||
|
): Wanted {
|
||||||
|
if (!binding) {
|
||||||
|
return { ok: false, problem: `no binding for ${provision} was delivered — the mesh writes it before this step runs` };
|
||||||
|
}
|
||||||
|
const host = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||||
|
const serves = binding.serves ?? {};
|
||||||
|
const port = Number(serves.port);
|
||||||
|
if (!host) return { ok: false, problem: `the ${provision} binding names no host (at)` };
|
||||||
|
if (isLoopback(host)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
problem:
|
||||||
|
`the ${provision} binding says the provider is at ${host}, which from the app's own container is the ` +
|
||||||
|
`app itself. The mesh hands loopback to a machine that is not on the private network; put it on the ` +
|
||||||
|
`private network so the provider has an address the app can dial`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves no usable port (${String(serves.port)})` };
|
||||||
|
}
|
||||||
|
const scheme = typeof serves.scheme === "string" && serves.scheme ? serves.scheme : "http";
|
||||||
|
if (scheme !== "http" && scheme !== "https") {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves scheme ${scheme}, which the app cannot dial` };
|
||||||
|
}
|
||||||
|
const username = typeof serves.username === "string" ? serves.username.trim() : "";
|
||||||
|
if (needsUser && !username) {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves no username for the app to log in as` };
|
||||||
|
}
|
||||||
|
const key = (credential ?? "").trim();
|
||||||
|
if (!key) return { ok: false, problem: `the ${provision} credential is empty or was not delivered` };
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
endpoint: {
|
||||||
|
scheme,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
urlBase: normBase(serves["url-base"]),
|
||||||
|
username,
|
||||||
|
credential: key,
|
||||||
|
from: typeof binding.from === "string" ? binding.from : "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A URL base as "" or "/x/y": slashes trimmed, one put back in front. */
|
||||||
|
export function normBase(v: unknown): string {
|
||||||
|
const s = typeof v === "string" ? v.trim().replace(/^\/+|\/+$/g, "") : "";
|
||||||
|
return s === "" ? "" : `/${s}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLoopback(host: string): boolean {
|
||||||
|
const h = host.toLowerCase();
|
||||||
|
return h === "localhost" || h === "::1" || h === "[::1]" || /^127\./.test(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hostForUrl(host: string): string {
|
||||||
|
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The provider's base URL, as the step dials it and as the app is given it. */
|
||||||
|
export function baseUrl(ep: Endpoint): string {
|
||||||
|
return `${ep.scheme}://${hostForUrl(ep.host)}:${ep.port}${ep.urlBase}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// HTTP
|
||||||
|
|
||||||
|
/** The HTTP the step needs, so a test can stand fakes in for the app and the providers. */
|
||||||
|
export interface Http {
|
||||||
|
fetch(
|
||||||
|
url: string,
|
||||||
|
init?: { method?: string; headers?: Record<string, string>; body?: string },
|
||||||
|
): Promise<{ status: number; text(): Promise<string> }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app, as the step reaches it from the host. */
|
||||||
|
export interface App {
|
||||||
|
/** The module, for messages and the remedy: sonarr, radarr, lidarr, bookshelf. */
|
||||||
|
module: string;
|
||||||
|
/** Its own URL, base path included. */
|
||||||
|
url: string;
|
||||||
|
apiKey: string;
|
||||||
|
/** v3 (sonarr, radarr) or v1 (lidarr, bookshelf). */
|
||||||
|
api: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Answer {
|
||||||
|
status: number;
|
||||||
|
body: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function appCall(http: Http, app: App, method: string, path: string, body?: unknown): Promise<Answer> {
|
||||||
|
const res = await http.fetch(`${app.url.replace(/\/$/, "")}/api/${app.api}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
"X-Api-Key": app.apiKey,
|
||||||
|
Accept: "application/json",
|
||||||
|
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||||
|
},
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
let parsed: unknown = undefined;
|
||||||
|
if (text) {
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(text) as unknown;
|
||||||
|
} catch {
|
||||||
|
parsed = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { status: res.status, body: parsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function appGet(http: Http, app: App, path: string): Promise<unknown> {
|
||||||
|
const a = await appCall(http, app, "GET", path);
|
||||||
|
if (a.status < 200 || a.status >= 300) throw new Error(`${app.module} GET ${path} answered ${a.status}`);
|
||||||
|
return a.body;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One of the app's validation failures: the only parts of an answer the step ever prints. */
|
||||||
|
interface Failure {
|
||||||
|
property: string;
|
||||||
|
message: string;
|
||||||
|
warning: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function failuresOf(body: unknown): Failure[] {
|
||||||
|
const list = Array.isArray(body) ? body : [];
|
||||||
|
return list.map((f) => {
|
||||||
|
const o = (f ?? {}) as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
property: String(o.propertyName ?? ""),
|
||||||
|
message: String(o.errorMessage ?? ""),
|
||||||
|
warning: o.isWarning === true,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One shape rather than a union on `ok`: the Dockerfile compiles without strict, where a boolean
|
||||||
|
* discriminant does not narrow.
|
||||||
|
*/
|
||||||
|
interface Verdict {
|
||||||
|
ok: boolean;
|
||||||
|
/** Warnings the app raised on a pass; errors (and any warnings) on a failure. */
|
||||||
|
failures: Failure[];
|
||||||
|
status: number;
|
||||||
|
saved?: Entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function verdict(a: Answer): Verdict {
|
||||||
|
if (a.status >= 200 && a.status < 300) return { ok: true, failures: [], status: a.status };
|
||||||
|
const failures = failuresOf(a.body);
|
||||||
|
if (a.status === 400 && failures.length > 0 && failures.every((f) => f.warning)) return { ok: true, failures, status: a.status };
|
||||||
|
return { ok: false, failures, status: a.status };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's own test of an entry, from the app's own container. */
|
||||||
|
async function appTest(http: Http, app: App, resource: string, entry: Entry): Promise<Verdict> {
|
||||||
|
return verdict(await appCall(http, app, "POST", `/${resource}/test`, entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save an entry. The app tests an enabled entry before saving it; a test that passes with only
|
||||||
|
* warnings ("a category is recommended") is saved with `forceSave`, the same as pressing "save
|
||||||
|
* anyway" in its screen. An error is never forced.
|
||||||
|
*/
|
||||||
|
async function appSave(http: Http, app: App, resource: string, entry: Entry, create: boolean): Promise<Verdict> {
|
||||||
|
const path = create ? `/${resource}` : `/${resource}/${entry.id}`;
|
||||||
|
const method = create ? "POST" : "PUT";
|
||||||
|
let a = await appCall(http, app, method, path, entry);
|
||||||
|
let v = verdict(a);
|
||||||
|
if (v.ok && (a.status < 200 || a.status >= 300)) {
|
||||||
|
a = await appCall(http, app, method, `${path}?forceSave=true`, entry);
|
||||||
|
v = verdict(a);
|
||||||
|
if (v.ok && (a.status < 200 || a.status >= 300)) {
|
||||||
|
return { ok: false, failures: failuresOf(a.body), status: a.status };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!v.ok) return v;
|
||||||
|
return { ...v, saved: (a.body ?? undefined) as Entry | undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Entries
|
||||||
|
|
||||||
|
/** An entry as the app's API gives it: a download client or an indexer. */
|
||||||
|
export interface Entry {
|
||||||
|
id?: number;
|
||||||
|
name?: string;
|
||||||
|
implementation?: string;
|
||||||
|
enable?: boolean;
|
||||||
|
enableRss?: boolean;
|
||||||
|
enableAutomaticSearch?: boolean;
|
||||||
|
enableInteractiveSearch?: boolean;
|
||||||
|
supportsRss?: boolean;
|
||||||
|
supportsSearch?: boolean;
|
||||||
|
fields?: { name: string; value?: unknown; [k: string]: unknown }[];
|
||||||
|
[k: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function field(e: Entry, name: string): unknown {
|
||||||
|
return e.fields?.find((f) => f.name === name)?.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The entry with these fields' values replaced — added when the app's shape lacks one. */
|
||||||
|
export function withFields(e: Entry, values: Record<string, unknown>): Entry {
|
||||||
|
const fields = (e.fields ?? []).map((f) => (f.name in values ? { ...f, value: values[f.name] } : { ...f }));
|
||||||
|
for (const [name, value] of Object.entries(values)) {
|
||||||
|
if (!fields.some((f) => f.name === name)) fields.push({ name, value });
|
||||||
|
}
|
||||||
|
return { ...e, fields };
|
||||||
|
}
|
||||||
|
|
||||||
|
function enabled(e: Entry): boolean {
|
||||||
|
return e.enable === true || e.enableRss === true || e.enableAutomaticSearch === true || e.enableInteractiveSearch === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What one provision, or one entry of it, came to. */
|
||||||
|
export type Outcome =
|
||||||
|
| { what: string; result: "unchanged"; untested?: boolean }
|
||||||
|
| { what: string; result: "written"; fields: string[]; untested?: boolean }
|
||||||
|
| { what: string; result: "created"; fields: string[] }
|
||||||
|
| { what: string; result: "notice"; note: string }
|
||||||
|
| { what: string; result: "refused"; problem: string };
|
||||||
|
|
||||||
|
function said(fs: Failure[]): string {
|
||||||
|
return fs.length === 0 ? "no reason given" : fs.map((f) => (f.property ? `${f.property}: ${f.message}` : f.message)).join("; ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring one of the mesh's entries in line: `connection` is the non-secret fields as the mesh says
|
||||||
|
* them, `differs` which of them the entry does not already say, `secretField` where the credential
|
||||||
|
* goes. Never throws: every failure is an outcome with a reason.
|
||||||
|
*/
|
||||||
|
export async function reconcileEntry(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
resource: "downloadclient" | "indexer",
|
||||||
|
what: string,
|
||||||
|
current: Entry,
|
||||||
|
connection: Record<string, unknown>,
|
||||||
|
differs: string[],
|
||||||
|
secretField: string,
|
||||||
|
credential: string,
|
||||||
|
testable = true,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
try {
|
||||||
|
const base = withFields(current, connection); // the credential as the app holds it — masked
|
||||||
|
if (!testable) {
|
||||||
|
// Nothing to test against (jackett no longer has the indexer it names): the connection is
|
||||||
|
// still the mesh's to state, and the key goes with it when the address changes.
|
||||||
|
if (differs.length === 0) return { what, result: "unchanged", untested: true };
|
||||||
|
const s = await appSave(http, app, resource, withFields(base, { [secretField]: credential }), false);
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not save it: ${said(s.failures)}` };
|
||||||
|
return { what, result: "written", fields: [...differs, secretField], untested: true };
|
||||||
|
}
|
||||||
|
const first = await appTest(http, app, resource, base);
|
||||||
|
if (first.ok) {
|
||||||
|
// The credential the app holds already works against the provider at the mesh's address —
|
||||||
|
// and the provider has exactly one, so it is the delivered one.
|
||||||
|
if (differs.length === 0) return { what, result: "unchanged" };
|
||||||
|
const s = await appSave(http, app, resource, base, false);
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not save it: ${said(s.failures)}` };
|
||||||
|
return { what, result: "written", fields: differs };
|
||||||
|
}
|
||||||
|
// The app's test failed with what it holds. The delivered credential was already checked
|
||||||
|
// against the provider, so writing it is safe; the app tests an enabled entry again on save.
|
||||||
|
const s = await appSave(http, app, resource, withFields(base, { [secretField]: credential }), false);
|
||||||
|
if (!s.ok) {
|
||||||
|
return {
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${app.module} tested it at the mesh's address and would not save it (nothing was written): ${said(s.failures)}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const stored = (await appGet(http, app, `/${resource}/${current.id}`)) as Entry;
|
||||||
|
const second = await appTest(http, app, resource, stored);
|
||||||
|
const fields = [...differs, secretField];
|
||||||
|
if (second.ok) return { what, result: "written", fields };
|
||||||
|
const why = `written (${fields.join(", ")}), and ${app.module}'s own test still fails: ${said(second.failures)}`;
|
||||||
|
return enabled(stored) ? { what, result: "refused", problem: why } : { what, result: "notice", note: `${why} — it is disabled, so nothing uses it` };
|
||||||
|
} catch (err) {
|
||||||
|
return { what, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a new entry from the app's own template for that kind: its defaults, the name, the
|
||||||
|
* connection and the credential. A category the provider does not have (nzbget refuses one it was
|
||||||
|
* not told about) is left empty rather than failing the registration, and said.
|
||||||
|
*/
|
||||||
|
export async function createEntry(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
resource: "downloadclient" | "indexer",
|
||||||
|
what: string,
|
||||||
|
implementation: string,
|
||||||
|
name: string,
|
||||||
|
values: Record<string, unknown>,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
try {
|
||||||
|
const schema = (await appGet(http, app, `/${resource}/schema`)) as Entry[];
|
||||||
|
const template = (schema ?? []).find((s) => s.implementation === implementation);
|
||||||
|
if (!template) return { what, result: "refused", problem: `${app.module} has no ${implementation} to register` };
|
||||||
|
let entry: Entry = withFields({ ...template, id: undefined, name }, values);
|
||||||
|
if (resource === "downloadclient") entry.enable = true;
|
||||||
|
else {
|
||||||
|
entry.enableRss = template.supportsRss !== false;
|
||||||
|
entry.enableAutomaticSearch = template.supportsSearch !== false;
|
||||||
|
entry.enableInteractiveSearch = template.supportsSearch !== false;
|
||||||
|
}
|
||||||
|
let s = await appSave(http, app, resource, entry, true);
|
||||||
|
let note = "";
|
||||||
|
if (!s.ok && s.failures.length > 0 && s.failures.every((f) => /category/i.test(f.property))) {
|
||||||
|
const emptied: Record<string, unknown> = {};
|
||||||
|
for (const f of entry.fields ?? []) if (/category$/i.test(f.name) && !/imported/i.test(f.name)) emptied[f.name] = "";
|
||||||
|
entry = withFields(entry, emptied);
|
||||||
|
s = await appSave(http, app, resource, entry, true);
|
||||||
|
note = " with its category left empty — the provider has none by the app's default name; set one in both";
|
||||||
|
}
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not register it: ${said(s.failures)}` };
|
||||||
|
const created = s.saved;
|
||||||
|
if (created?.id !== undefined) {
|
||||||
|
const t = await appTest(http, app, resource, (await appGet(http, app, `/${resource}/${created.id}`)) as Entry);
|
||||||
|
if (!t.ok) {
|
||||||
|
return { what, result: "refused", problem: `registered as "${name}"${note}, and ${app.module}'s own test fails: ${said(t.failures)}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return note
|
||||||
|
? { what, result: "notice", note: `registered as "${name}"${note}` }
|
||||||
|
: { what, result: "created", fields: Object.keys(values) };
|
||||||
|
} catch (err) {
|
||||||
|
return { what, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Providers: does it take the credential?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does the provider take this credential? `took` it does (for jackett, with the ids of the indexers
|
||||||
|
* it has configured); `refused` it said no; a thrown error when it could not be asked.
|
||||||
|
*/
|
||||||
|
export interface Took {
|
||||||
|
took: boolean;
|
||||||
|
configured?: Map<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function providerTakes(http: Http, provision: string, ep: Endpoint): Promise<Took> {
|
||||||
|
const base = baseUrl(ep);
|
||||||
|
if (provision === "nzbget-api") {
|
||||||
|
const auth = Buffer.from(`${ep.username}:${ep.credential}`).toString("base64");
|
||||||
|
const res = await http.fetch(`${base}/jsonrpc/version`, { method: "GET", headers: { Authorization: `Basic ${auth}` } });
|
||||||
|
await res.text();
|
||||||
|
if (res.status === 401 || res.status === 403) return { took: false };
|
||||||
|
if (res.status >= 200 && res.status < 300) return { took: true };
|
||||||
|
throw new Error(`nzbget answered ${res.status}`);
|
||||||
|
}
|
||||||
|
if (provision === "qbittorrent-api") {
|
||||||
|
const form = `username=${encodeURIComponent(ep.username)}&password=${encodeURIComponent(ep.credential)}`;
|
||||||
|
const res = await http.fetch(`${base}/api/v2/auth/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: form,
|
||||||
|
});
|
||||||
|
const text = (await res.text()).trim();
|
||||||
|
if (res.status === 401 || /^fails\.?$/i.test(text)) return { took: false };
|
||||||
|
if (res.status === 403) {
|
||||||
|
throw new Error(
|
||||||
|
"qBittorrent answered 403: it has banned this address after failed logins (WebUI\\BanDuration); it lifts by itself",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (res.status >= 200 && res.status < 300) return { took: true };
|
||||||
|
throw new Error(`qBittorrent answered ${res.status}`);
|
||||||
|
}
|
||||||
|
if (provision === JACKETT) {
|
||||||
|
const url = `${base}/api/v2.0/indexers/all/results/torznab/api?t=indexers&configured=true&apikey=${encodeURIComponent(ep.credential)}`;
|
||||||
|
const res = await http.fetch(url, { method: "GET" });
|
||||||
|
const text = await res.text();
|
||||||
|
if (res.status === 401 || res.status === 403) return { took: false };
|
||||||
|
if (res.status < 200 || res.status >= 300) throw new Error(`jackett answered ${res.status}`);
|
||||||
|
// jackett answers a wrong key 200 with an error document: code 100, "Invalid API Key".
|
||||||
|
if (/<error\b[^>]*\bcode="100"/i.test(text)) return { took: false };
|
||||||
|
if (/<error\b/i.test(text)) throw new Error("jackett answered with an error document");
|
||||||
|
return { took: true, configured: configuredIndexers(text) };
|
||||||
|
}
|
||||||
|
throw new Error(`no check for ${provision}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** jackett's configured indexers, id → title, from its `t=indexers` feed. */
|
||||||
|
export function configuredIndexers(xml: string): Map<string, string> {
|
||||||
|
const out = new Map<string, string>();
|
||||||
|
const re = /<indexer\b[^>]*\bid="([^"]+)"[^>]*>([\s\S]*?)<\/indexer>/g;
|
||||||
|
for (let m = re.exec(xml); m; m = re.exec(xml)) {
|
||||||
|
const title = /<title>([\s\S]*?)<\/title>/.exec(m[2])?.[1]?.trim() ?? m[1];
|
||||||
|
out.set(m[1], decodeXml(title));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeXml(s: string): string {
|
||||||
|
return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The remedy for a refused credential, in the controller's own words (ADR 0092). */
|
||||||
|
export function acceptRemedy(app: App, node: string, provision: string, provider: string, secretName: string, from: string): string {
|
||||||
|
return (
|
||||||
|
`${provider} refuses the ${provision} credential the mesh delivered, so nothing of ${provision} was written ` +
|
||||||
|
`into ${app.module}. ${provider} has one ${secretName} and the mesh cannot make it: accept it for this pair — ` +
|
||||||
|
`\`secret accept ${node || "<this node>"} ${app.module} ${provision} --provider ${from || "<its node>"} ` +
|
||||||
|
`--from <file holding ${provider}'s ${secretName}>\``
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Download clients
|
||||||
|
|
||||||
|
/** The non-secret fields of a download client as the mesh says them. */
|
||||||
|
export function clientConnection(ep: Endpoint): Record<string, unknown> {
|
||||||
|
return { host: ep.host, port: ep.port, useSsl: ep.scheme === "https", urlBase: ep.urlBase === "" ? null : ep.urlBase, username: ep.username };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which of them the entry does not already say. Names only. */
|
||||||
|
export function clientDiffers(e: Entry, ep: Endpoint): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
if (String(field(e, "host") ?? "").toLowerCase() !== ep.host.toLowerCase()) out.push("host");
|
||||||
|
if (Number(field(e, "port") ?? 0) !== ep.port) out.push("port");
|
||||||
|
if (Boolean(field(e, "useSsl")) !== (ep.scheme === "https")) out.push("useSsl");
|
||||||
|
if (normBase(field(e, "urlBase")) !== ep.urlBase) out.push("urlBase");
|
||||||
|
if (String(field(e, "username") ?? "") !== ep.username) out.push("username");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the app's download client for one provision in line: the entry by that name and kind is
|
||||||
|
* the mesh's and is updated; none, it is registered. An entry by that name of another kind, or by
|
||||||
|
* that name in another case, is somebody else's and is refused rather than touched.
|
||||||
|
*/
|
||||||
|
export async function reconcileClient(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
kind: ClientKind,
|
||||||
|
name: string,
|
||||||
|
ep: Endpoint,
|
||||||
|
entries: Entry[],
|
||||||
|
): Promise<Outcome[]> {
|
||||||
|
const what = `${kind.provision} ("${name}")`;
|
||||||
|
const exact = entries.filter((e) => e.name === name);
|
||||||
|
const alike = entries.filter((e) => e.name !== name && String(e.name ?? "").toLowerCase() === name.toLowerCase());
|
||||||
|
if (exact.length > 0 && exact[0].implementation !== kind.implementation) {
|
||||||
|
return [{
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `the download client named "${name}" is a ${exact[0].implementation}, not ${kind.implementation}; it is not the mesh's and was left alone. Name the mesh's entry otherwise in downloads.${kind.provision}.name`,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
if (exact.length === 0 && alike.length > 0) {
|
||||||
|
return [{
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${app.module} already has "${alike[0].name}", which is not the mesh's name ("${name}") and was left alone. To have the mesh manage it, set downloads.${kind.provision}.name to "${alike[0].name}"`,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
const others = entries.filter((e) => e.implementation === kind.implementation && e.name !== name);
|
||||||
|
if (others.length > 0) {
|
||||||
|
outcomes.push({
|
||||||
|
what,
|
||||||
|
result: "notice",
|
||||||
|
note: `also present and not the mesh's, left alone: ${others.map((o) => `"${o.name}"`).join(", ")}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (exact.length === 0) {
|
||||||
|
outcomes.push(
|
||||||
|
await createEntry(http, app, "downloadclient", what, kind.implementation, name, {
|
||||||
|
...clientConnection(ep),
|
||||||
|
password: ep.credential,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
outcomes.push(
|
||||||
|
await reconcileEntry(http, app, "downloadclient", what, exact[0], clientConnection(ep), clientDiffers(exact[0], ep), "password", ep.credential),
|
||||||
|
);
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Indexers
|
||||||
|
|
||||||
|
const FEED = /\/api\/v2\.0\/indexers\/([^/]+)\/results\/torznab\/?$/;
|
||||||
|
|
||||||
|
/** A Torznab entry reading a jackett feed: the host it points at and the jackett indexer's id. */
|
||||||
|
export function jackettFeed(e: Entry): { host: string; id: string } | undefined {
|
||||||
|
if (e.implementation !== "Torznab") return undefined;
|
||||||
|
const raw = String(field(e, "baseUrl") ?? "").trim();
|
||||||
|
if (!raw) return undefined;
|
||||||
|
let u: URL;
|
||||||
|
try {
|
||||||
|
u = new URL(raw);
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const path = `${u.pathname.replace(/\/+$/, "")}/${String(field(e, "apiPath") ?? "").replace(/^\/+/, "")}`;
|
||||||
|
const m = FEED.exec(path);
|
||||||
|
if (!m) return undefined;
|
||||||
|
return { host: u.hostname.replace(/^\[|\]$/g, "").toLowerCase(), id: decodeURIComponent(m[1]) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The feed's two fields as the mesh says them. */
|
||||||
|
export function feedConnection(ep: Endpoint, id: string): Record<string, unknown> {
|
||||||
|
return { baseUrl: baseUrl(ep), apiPath: `/api/v2.0/indexers/${id}/results/torznab/` };
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameUrl(a: string, b: string): boolean {
|
||||||
|
try {
|
||||||
|
const x = new URL(a);
|
||||||
|
const y = new URL(b);
|
||||||
|
const port = (u: URL) => u.port || (u.protocol === "https:" ? "443" : "80");
|
||||||
|
return (
|
||||||
|
x.protocol === y.protocol &&
|
||||||
|
x.hostname.toLowerCase() === y.hostname.toLowerCase() &&
|
||||||
|
port(x) === port(y) &&
|
||||||
|
x.pathname.replace(/\/+$/, "") === y.pathname.replace(/\/+$/, "")
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedDiffers(e: Entry, ep: Endpoint, id: string): string[] {
|
||||||
|
const want = feedConnection(ep, id);
|
||||||
|
const out: string[] = [];
|
||||||
|
if (!sameUrl(String(field(e, "baseUrl") ?? ""), String(want.baseUrl))) out.push("baseUrl");
|
||||||
|
const path = (v: unknown) => `/${String(v ?? "").replace(/^\/+|\/+$/g, "")}`;
|
||||||
|
if (path(field(e, "apiPath")) !== path(want.apiPath)) out.push("apiPath");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IndexerSettings {
|
||||||
|
/** Hosts whose jackett feeds the mesh takes over — a migration's old names. */
|
||||||
|
adoptHosts: string[];
|
||||||
|
/** jackett indexer ids the app should have. */
|
||||||
|
indexers: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the app's jackett feeds in line: every one the mesh manages is pointed at the bound jackett
|
||||||
|
* with its key, and every listed jackett indexer the app lacks is registered.
|
||||||
|
*/
|
||||||
|
export async function reconcileIndexers(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
ep: Endpoint,
|
||||||
|
configured: Map<string, string>,
|
||||||
|
settings: IndexerSettings,
|
||||||
|
remembered: string[],
|
||||||
|
entries: Entry[],
|
||||||
|
): Promise<Outcome[]> {
|
||||||
|
const ours = new Set([ep.host, ...settings.adoptHosts, ...remembered].map((h) => h.trim().toLowerCase()).filter(Boolean));
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
const managed = new Set<string>();
|
||||||
|
for (const e of entries) {
|
||||||
|
const feed = jackettFeed(e);
|
||||||
|
if (!feed || !ours.has(feed.host)) continue;
|
||||||
|
managed.add(feed.id);
|
||||||
|
const what = `jackett-api ("${e.name}", jackett indexer ${feed.id})`;
|
||||||
|
const known = feed.id === "all" || configured.has(feed.id);
|
||||||
|
const outcome = await reconcileEntry(
|
||||||
|
http, app, "indexer", what, e, feedConnection(ep, feed.id), feedDiffers(e, ep, feed.id), "apiKey", ep.credential, known,
|
||||||
|
);
|
||||||
|
outcomes.push(outcome);
|
||||||
|
if (!known && outcome.result !== "refused") {
|
||||||
|
outcomes.push({ what, result: "notice", note: `jackett has no indexer "${feed.id}" configured, so it was not tested; configure it in jackett or remove the entry in ${app.module}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const id of settings.indexers) {
|
||||||
|
if (managed.has(id)) continue;
|
||||||
|
const what = `jackett-api (jackett indexer ${id})`;
|
||||||
|
if (id !== "all" && !configured.has(id)) {
|
||||||
|
outcomes.push({ what, result: "refused", problem: `downloads.jackett-api.indexers lists "${id}", and jackett has no indexer by that id configured` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const name = `Jackett - ${id === "all" ? "all" : configured.get(id)}`;
|
||||||
|
outcomes.push(await createEntry(http, app, "indexer", what, "Torznab", name, { ...feedConnection(ep, id), apiKey: ep.credential }));
|
||||||
|
}
|
||||||
|
if (outcomes.length === 0) {
|
||||||
|
outcomes.push({ what: "jackett-api", result: "notice", note: `${app.module} has no jackett feed the mesh manages, and downloads.jackett-api.indexers lists none to register` });
|
||||||
|
}
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Files
|
||||||
|
|
||||||
|
/** The module's settings for this step, from its merged `downloads.json`. */
|
||||||
|
export interface StepSettings {
|
||||||
|
node: string;
|
||||||
|
names: Record<string, string>;
|
||||||
|
indexers: IndexerSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stepSettings(raw: unknown): StepSettings {
|
||||||
|
const doc = (raw ?? {}) as Record<string, unknown>;
|
||||||
|
const d = (doc.downloads ?? {}) as Record<string, Record<string, unknown> | undefined>;
|
||||||
|
const names: Record<string, string> = {};
|
||||||
|
for (const k of CLIENTS) {
|
||||||
|
const n = d[k.provision]?.name;
|
||||||
|
names[k.provision] = typeof n === "string" && n.trim() ? n.trim() : k.provision.replace(/-api$/, "");
|
||||||
|
}
|
||||||
|
const j = d[JACKETT] ?? {};
|
||||||
|
const strings = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && x.trim() !== "").map((x) => x.trim()) : []);
|
||||||
|
return {
|
||||||
|
node: typeof doc.node === "string" ? doc.node : "",
|
||||||
|
names,
|
||||||
|
indexers: { adoptHosts: strings(j["adopt-hosts"]), indexers: strings(j.indexers) },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's own key and base path, from its config.xml. */
|
||||||
|
export function appConfig(xml: string): { apiKey: string; urlBase: string } {
|
||||||
|
const tag = (t: string) => new RegExp(`<${t}>([^<]*)</${t}>`).exec(xml)?.[1]?.trim() ?? "";
|
||||||
|
return { apiKey: tag("ApiKey"), urlBase: normBase(tag("UrlBase")) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A file the mesh wrote, or undefined when it is not there. */
|
||||||
|
export async function readIfThere(path: string | undefined): Promise<string | undefined> {
|
||||||
|
if (!path) return undefined;
|
||||||
|
return readFile(path, "utf8").catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A JSON file parsed, or undefined when absent or not JSON. */
|
||||||
|
export async function readJson(path: string | undefined): Promise<unknown> {
|
||||||
|
const raw = await readIfThere(path);
|
||||||
|
if (raw === undefined) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as unknown;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait for the app to answer, because the step runs right after its container starts. */
|
||||||
|
export async function appReady(http: Http, app: App, waitMs: number, pauseMs = 2000): Promise<boolean> {
|
||||||
|
const until = Date.now() + waitMs;
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
const a = await appCall(http, app, "GET", "/system/status");
|
||||||
|
if (a.status === 200) return true;
|
||||||
|
} catch {
|
||||||
|
// not listening yet
|
||||||
|
}
|
||||||
|
if (Date.now() >= until) return false;
|
||||||
|
await new Promise((r) => setTimeout(r, pauseMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listEntries(http: Http, app: App, resource: "downloadclient" | "indexer"): Promise<Entry[]> {
|
||||||
|
return ((await appGet(http, app, `/${resource}`)) as Entry[]) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Anything printed goes through this: the credentials the step holds never reach a log. */
|
||||||
|
export function scrub(text: string, secrets: string[]): string {
|
||||||
|
let out = text;
|
||||||
|
for (const s of secrets) if (s && s.length >= 4) out = out.split(s).join("<redacted>");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(err: unknown): string {
|
||||||
|
return err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// bookshelf's events. The tool runtime imports this once the broker is bound. It watches the
|
||||||
|
// download queue and turns its comings and goings into mesh events — the same mechanism radarr uses,
|
||||||
|
// applied to a Servarr book manager.
|
||||||
|
//
|
||||||
|
// Emits (novox/hq ADR 0041/0042):
|
||||||
|
// module.bookshelf.book.grabbed — a release entered the queue (Bookshelf grabbed it)
|
||||||
|
// module.bookshelf.download.completed — a release left the queue, imported. This routing key is
|
||||||
|
// what the plex module consumes (module.*.download.completed)
|
||||||
|
// to rescan, so a new audiobook becomes a visible item.
|
||||||
|
// Consumes: none.
|
||||||
|
//
|
||||||
|
// NOTE: the hal bookshelf module emitted no events (its hooks only did install-time provisioning).
|
||||||
|
// This queue watcher is new in nox, modelled exactly on radarr's — bookshelf is a Servarr app with
|
||||||
|
// the same queue semantics, so the diff-and-emit pattern carries over unchanged.
|
||||||
|
//
|
||||||
|
// The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a
|
||||||
|
// restart mid-download does not re-announce everything already in flight as freshly grabbed.
|
||||||
|
|
||||||
|
import { emit } from "@novox/mesh-sdk/events";
|
||||||
|
import { BookshelfClient, type BookshelfQueueItem } from "./client.js";
|
||||||
|
|
||||||
|
// Building the client throws when Bookshelf has no URL/key yet. Like the tools (see tools/index.ts),
|
||||||
|
// the events entrypoint must not crash the runtime for that — it stays idle until configured.
|
||||||
|
function buildClient(): BookshelfClient | null {
|
||||||
|
try {
|
||||||
|
return BookshelfClient.fromEnv();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const bookshelf = buildClient();
|
||||||
|
|
||||||
|
// Bookshelf removes an item from the queue once it has been imported; a "warning"/"failed" status is
|
||||||
|
// how a stuck or broken grab shows itself, so we do not call those a completion when they vanish.
|
||||||
|
const FAILED_STATUSES = new Set(["failed", "warning"]);
|
||||||
|
|
||||||
|
const inQueue = new Map<number, BookshelfQueueItem>();
|
||||||
|
let primed = false;
|
||||||
|
|
||||||
|
async function pollQueue(bookshelf: BookshelfClient): Promise<void> {
|
||||||
|
const { items } = await bookshelf.getQueue();
|
||||||
|
const now = new Map(items.map((i) => [i.id, i]));
|
||||||
|
|
||||||
|
if (primed) {
|
||||||
|
// Entered the queue since last look — Bookshelf grabbed a release.
|
||||||
|
for (const [id, item] of now) {
|
||||||
|
if (!inQueue.has(id)) await emit("book.grabbed", { title: item.title, status: item.status });
|
||||||
|
}
|
||||||
|
// Left the queue — imported and done, unless it was last seen failing.
|
||||||
|
for (const [id, item] of inQueue) {
|
||||||
|
if (!now.has(id) && !FAILED_STATUSES.has(item.status)) {
|
||||||
|
await emit("download.completed", { title: item.title });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inQueue.clear();
|
||||||
|
for (const [id, item] of now) inQueue.set(id, item);
|
||||||
|
primed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||||
|
const run = (): void => void fn().catch((err) => console.error(`[bookshelf] ${err}`));
|
||||||
|
setInterval(run, everyMs);
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (bookshelf) {
|
||||||
|
tick(() => pollQueue(bookshelf), 30_000);
|
||||||
|
console.log("[bookshelf] watching the download queue, emitting grabs and completions");
|
||||||
|
} else {
|
||||||
|
console.log("[bookshelf] not configured — events idle until an API key is available");
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
{
|
||||||
|
"module": "bookshelf",
|
||||||
|
"version": "1",
|
||||||
|
"slug": "books",
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"book.grabbed",
|
||||||
|
"download.completed"
|
||||||
|
],
|
||||||
|
"consumes": [],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/bookshelf/broker"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 8787,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "managing the ebook/audiobook library"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accesses": [
|
||||||
|
{
|
||||||
|
"path": "/services/media/books",
|
||||||
|
"mode": "read-write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/downloads",
|
||||||
|
"mode": "read-write"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/bookshelf",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "bookshelf",
|
||||||
|
"image": "ghcr.io/pennydreadful/bookshelf@sha256:67498dd5ece516867d72ee642abd6c1a66b36a135c8f7da0127109564372beb1",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC"
|
||||||
|
},
|
||||||
|
"ports": [
|
||||||
|
"8787"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"/services/media/books:/books",
|
||||||
|
"/services/media/downloads:/downloads"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-bookshelf",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/bookshelf/broker:/run/secrets/broker:ro",
|
||||||
|
"${dir:config}:/var/lib/bookshelf/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_BOOKSHELF_URL": "http://127.0.0.1:${port:8787}",
|
||||||
|
"MESH_BOOKSHELF_CONFIG_DIR": "/var/lib/bookshelf/config"
|
||||||
|
},
|
||||||
|
"artifact": "runtime"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/downloads.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{\n \"node\": \"${machine:name}\",\n \"downloads\": {\n \"nzbget-api\": {\n \"name\": \"nzbget\"\n },\n \"qbittorrent-api\": {\n \"name\": \"qbittorrent\"\n },\n \"jackett-api\": {\n \"adopt-hosts\": [],\n \"indexers\": []\n }\n }\n}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads-memory",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-bookshelf-downloads",
|
||||||
|
"network": "host",
|
||||||
|
"run-once": true,
|
||||||
|
"volumes": [
|
||||||
|
"${dir:state}/downloads.json:/run/downloads/downloads.json:ro",
|
||||||
|
"${dir:state}/nzbget-api.json:/run/downloads/nzbget-api.json:ro",
|
||||||
|
"${dir:state}/nzbget-api.secret:/run/downloads/nzbget-api.secret:ro",
|
||||||
|
"${dir:state}/qbittorrent-api.json:/run/downloads/qbittorrent-api.json:ro",
|
||||||
|
"${dir:state}/qbittorrent-api.secret:/run/downloads/qbittorrent-api.secret:ro",
|
||||||
|
"${dir:state}/jackett-api.json:/run/downloads/jackett-api.json:ro",
|
||||||
|
"${dir:state}/jackett-api.secret:/run/downloads/jackett-api.secret:ro",
|
||||||
|
"${dir:config}:/var/lib/bookshelf/config:ro",
|
||||||
|
"${dir:downloads-memory}:/var/lib/downloads"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_DOWNLOADS_APP": "bookshelf",
|
||||||
|
"MESH_DOWNLOADS_API": "v1",
|
||||||
|
"MESH_DOWNLOADS_APP_URL": "http://127.0.0.1:${port:8787}",
|
||||||
|
"MESH_DOWNLOADS_APP_CONFIG": "/var/lib/bookshelf/config/config.xml",
|
||||||
|
"MESH_DOWNLOADS_DIR": "/run/downloads",
|
||||||
|
"MESH_DOWNLOADS_SETTINGS": "/run/downloads/downloads.json",
|
||||||
|
"MESH_DOWNLOADS_MEMORY": "/var/lib/downloads/memory.json"
|
||||||
|
},
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"/app/modules/bookshelf/dist/downloads/index.js"
|
||||||
|
],
|
||||||
|
"restart-on": [
|
||||||
|
"downloads-config",
|
||||||
|
"bound-nzbget-api",
|
||||||
|
"secret-nzbget-api",
|
||||||
|
"bound-qbittorrent-api",
|
||||||
|
"secret-qbittorrent-api",
|
||||||
|
"bound-jackett-api",
|
||||||
|
"secret-jackett-api"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requires": [
|
||||||
|
"jackett-api",
|
||||||
|
"nzbget-api",
|
||||||
|
"qbittorrent-api",
|
||||||
|
"route"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "books",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json",
|
||||||
|
"nzbget-api": "${dir:state}/nzbget-api.json",
|
||||||
|
"qbittorrent-api": "${dir:state}/qbittorrent-api.json",
|
||||||
|
"jackett-api": "${dir:state}/jackett-api.json"
|
||||||
|
},
|
||||||
|
"secrets": {
|
||||||
|
"nzbget-api": "${dir:state}/nzbget-api.secret",
|
||||||
|
"qbittorrent-api": "${dir:state}/qbittorrent-api.secret",
|
||||||
|
"jackett-api": "${dir:state}/jackett-api.secret"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-bookshelf",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "bookshelf — ebook/audiobook management (Readarr fork). Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc client.ts index.ts tools/index.ts downloads/settings.ts downloads/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist",
|
||||||
|
"typecheck": "tsc -p tsconfig.json",
|
||||||
|
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
// What holds the downloads step (downloads/settings.ts): the app's download clients and jackett
|
||||||
|
// feeds are made to say what the mesh bound — host, port, TLS, base path, user, credential — and
|
||||||
|
// nothing else they keep is touched; only the mesh's entries are touched, and nothing is ever
|
||||||
|
// deleted; nothing is written when nothing differs; a missing one is registered; and a credential
|
||||||
|
// the provider refuses (the mesh's own minted value, before the operator accepts the provider's)
|
||||||
|
// is never written, with the `secret accept` that fixes it named.
|
||||||
|
//
|
||||||
|
// The app and the providers are fakes: the routes the step touches, answering as the real ones do
|
||||||
|
// (checked against the catalogue's pinned sonarr, radarr, lidarr, bookshelf, nzbget, qBittorrent
|
||||||
|
// and jackett): the app masks a stored password as "********", tests an enabled entry before
|
||||||
|
// saving it, refuses a warning unless forceSave, and jackett answers a wrong key 200 with an error.
|
||||||
|
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CLIENTS,
|
||||||
|
acceptRemedy,
|
||||||
|
jackettFeed,
|
||||||
|
providerTakes,
|
||||||
|
reconcileClient,
|
||||||
|
reconcileIndexers,
|
||||||
|
stepSettings,
|
||||||
|
wanted,
|
||||||
|
type App,
|
||||||
|
type Binding,
|
||||||
|
type Endpoint,
|
||||||
|
type Entry,
|
||||||
|
type Http,
|
||||||
|
} from "../downloads/settings.ts";
|
||||||
|
|
||||||
|
const NZBGET = CLIENTS.find((c) => c.provision === "nzbget-api")!;
|
||||||
|
const QBIT = CLIENTS.find((c) => c.provision === "qbittorrent-api")!;
|
||||||
|
const APP: App = { module: "sonarr", url: "http://127.0.0.1:8989", apiKey: "app-key", api: "v3" };
|
||||||
|
const MASK = "********";
|
||||||
|
|
||||||
|
interface Provider {
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
user?: string;
|
||||||
|
secret: string;
|
||||||
|
configured?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nzbget: Provider = { host: "ace.internal", port: 20201, user: "luffy", secret: "nzb-real" };
|
||||||
|
const qbit: Provider = { host: "ace.internal", port: 8112, user: "luffy", secret: "qbt-real" };
|
||||||
|
const jackett: Provider = { host: "ace.internal", port: 20204, secret: "jackett-real", configured: { rutracker: "RuTracker", torrent9: "Torrent9" } };
|
||||||
|
|
||||||
|
function binding(p: Provider, provision: string, extra: Record<string, unknown> = {}): Binding {
|
||||||
|
return {
|
||||||
|
provision,
|
||||||
|
from: "ace",
|
||||||
|
at: p.host,
|
||||||
|
as: "mesh_ace_sonarr",
|
||||||
|
serves: { scheme: "http", port: p.port, "url-base": "", ...(p.user ? { username: p.user } : {}), ...extra },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function endpoint(p: Provider, provision: string, credential = p.secret): Endpoint {
|
||||||
|
const w = wanted(provision, binding(p, provision), credential, provision !== "jackett-api");
|
||||||
|
if (!w.ok) throw new Error(w.problem);
|
||||||
|
return w.endpoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
const f = (name: string, value: unknown) => ({ name, value });
|
||||||
|
|
||||||
|
function client(id: number, name: string, implementation: string, host: string, port: number, password: string, extra: Record<string, unknown> = {}): Entry {
|
||||||
|
return {
|
||||||
|
id, name, implementation, enable: true, priority: 1, tags: [],
|
||||||
|
fields: [f("host", host), f("port", port), f("useSsl", false), f("urlBase", null), f("username", "luffy"), f("password", password), f("tvCategory", "Series"), ...Object.entries(extra).map(([k, v]) => f(k, v))],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function feed(id: number, name: string, baseUrl: string, jid: string, key: string, on = true): Entry {
|
||||||
|
return {
|
||||||
|
id, name, implementation: "Torznab", enableRss: on, enableAutomaticSearch: on, enableInteractiveSearch: on, priority: 25,
|
||||||
|
fields: [f("baseUrl", baseUrl), f("apiPath", `/api/v2.0/indexers/${jid}/results/torznab/`), f("apiKey", key), f("categories", [5000])],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Call {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
body?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A Servarr app and the three providers behind one fetch. */
|
||||||
|
function fakes(start: { clients?: Entry[]; indexers?: Entry[] }) {
|
||||||
|
const calls: Call[] = [];
|
||||||
|
const store: Record<string, Entry[]> = {
|
||||||
|
downloadclient: structuredClone(start.clients ?? []),
|
||||||
|
indexer: structuredClone(start.indexers ?? []),
|
||||||
|
};
|
||||||
|
let next = 100;
|
||||||
|
const secretOf: Record<string, string> = { downloadclient: "password", indexer: "apiKey" };
|
||||||
|
const masked = (e: Entry): Entry => ({ ...e, fields: e.fields!.map((x) => (x.name === "password" || x.name === "apiKey") && x.value ? { ...x, value: MASK } : { ...x }) });
|
||||||
|
const val = (e: Entry, n: string) => e.fields?.find((x) => x.name === n)?.value;
|
||||||
|
|
||||||
|
/** What the app's own test says: dialled from its container, with its stored secret for a mask. */
|
||||||
|
const appTest = (kind: string, e: Entry): { propertyName: string; errorMessage: string; isWarning: boolean }[] => {
|
||||||
|
let secret = val(e, secretOf[kind]);
|
||||||
|
if (secret === MASK) secret = val(store[kind].find((s) => s.id === e.id) ?? {}, secretOf[kind]);
|
||||||
|
if (kind === "downloadclient") {
|
||||||
|
const p = e.implementation === "Nzbget" ? nzbget : qbit;
|
||||||
|
if (val(e, "host") !== p.host || val(e, "port") !== p.port) return [{ propertyName: "Host", errorMessage: "Unable to connect", isWarning: false }];
|
||||||
|
if (secret !== p.secret || val(e, "username") !== p.user) return [{ propertyName: "Username", errorMessage: "Authentication Failure", isWarning: false }];
|
||||||
|
if (val(e, "tvCategory") === "") return [{ propertyName: "TvCategory", errorMessage: "A category is recommended", isWarning: true }];
|
||||||
|
if (e.implementation === "Nzbget" && val(e, "tvCategory") === "tv") return [{ propertyName: "TvCategory", errorMessage: "Category does not exist", isWarning: false }];
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const u = new URL(String(val(e, "baseUrl")));
|
||||||
|
if (u.hostname !== jackett.host || Number(u.port) !== jackett.port) return [{ propertyName: "BaseUrl", errorMessage: "Unable to connect", isWarning: false }];
|
||||||
|
if (secret !== jackett.secret) return [{ propertyName: "ApiKey", errorMessage: "Invalid API Key", isWarning: false }];
|
||||||
|
const id = /indexers\/([^/]+)\//.exec(String(val(e, "apiPath")))?.[1] ?? "";
|
||||||
|
if (!(id in jackett.configured!)) return [{ propertyName: "", errorMessage: "Unknown indexer", isWarning: false }];
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const http: Http = {
|
||||||
|
async fetch(url, init) {
|
||||||
|
const method = init?.method ?? "GET";
|
||||||
|
const body = init?.body && init.headers?.["Content-Type"] === "application/json" ? (JSON.parse(init.body) as Entry) : init?.body;
|
||||||
|
calls.push({ method, url, body });
|
||||||
|
const reply = (status: number, value?: unknown) => ({ status, text: async () => (value === undefined ? "" : typeof value === "string" ? value : JSON.stringify(value)) });
|
||||||
|
const u = new URL(url);
|
||||||
|
// Providers.
|
||||||
|
if (u.pathname === "/jsonrpc/version") {
|
||||||
|
const want = "Basic " + Buffer.from(`${nzbget.user}:${nzbget.secret}`).toString("base64");
|
||||||
|
return init?.headers?.Authorization === want ? reply(200, { result: "26.0" }) : reply(401);
|
||||||
|
}
|
||||||
|
if (u.pathname === "/api/v2/auth/login") {
|
||||||
|
const form = new URLSearchParams(String(init?.body ?? ""));
|
||||||
|
return form.get("username") === qbit.user && form.get("password") === qbit.secret ? reply(204) : reply(401, "Unauthorized");
|
||||||
|
}
|
||||||
|
if (u.pathname.endsWith("/torznab/api")) {
|
||||||
|
if (u.searchParams.get("apikey") !== jackett.secret) return reply(200, '<?xml version="1.0"?><error code="100" description="Invalid API Key" />');
|
||||||
|
const items = Object.entries(jackett.configured!).map(([id, t]) => `<indexer id="${id}" configured="true"><title>${t}</title></indexer>`).join("");
|
||||||
|
return reply(200, `<?xml version="1.0"?><indexers>${items}</indexers>`);
|
||||||
|
}
|
||||||
|
// The app.
|
||||||
|
if (init?.headers?.["X-Api-Key"] !== APP.apiKey) return reply(401);
|
||||||
|
const m = /^\/api\/v3\/(downloadclient|indexer)(?:\/(schema|test|\d+))?$/.exec(u.pathname);
|
||||||
|
if (!m) return reply(404);
|
||||||
|
const [, kind, sub] = m;
|
||||||
|
const force = u.searchParams.get("forceSave") === "true";
|
||||||
|
if (method === "GET" && !sub) return reply(200, store[kind].map(masked));
|
||||||
|
if (method === "GET" && sub === "schema") {
|
||||||
|
return reply(200, kind === "downloadclient"
|
||||||
|
? [client(0, "", "Nzbget", "localhost", 6789, MASK, {}), client(0, "", "QBittorrent", "localhost", 8080, "", {})].map((e) => ({ ...e, fields: e.fields!.map((x) => x.name === "tvCategory" ? { ...x, value: e.implementation === "Nzbget" ? "tv" : "tv-sonarr" } : x.name === "username" ? { ...x, value: null } : x) }))
|
||||||
|
: [{ ...feed(0, "", "", "x", "", false), supportsRss: true, supportsSearch: true, fields: [f("baseUrl", null), f("apiPath", "/api"), f("apiKey", null), f("categories", [5030, 5040])] }]);
|
||||||
|
}
|
||||||
|
if (method === "GET") {
|
||||||
|
const e = store[kind].find((s) => s.id === Number(sub));
|
||||||
|
return e ? reply(200, masked(e)) : reply(404);
|
||||||
|
}
|
||||||
|
if (method === "POST" && sub === "test") {
|
||||||
|
const fails = appTest(kind, body as Entry);
|
||||||
|
return fails.length ? reply(400, fails) : reply(200);
|
||||||
|
}
|
||||||
|
// Save: tested when enabled; a mask keeps what is stored.
|
||||||
|
const e = body as Entry;
|
||||||
|
const on = e.enable === true || e.enableRss === true || e.enableAutomaticSearch === true;
|
||||||
|
if (on) {
|
||||||
|
const fails = appTest(kind, e);
|
||||||
|
if (fails.some((x) => !x.isWarning) || (fails.length && !force)) return reply(400, fails);
|
||||||
|
}
|
||||||
|
if (method === "POST" && !sub) {
|
||||||
|
if (store[kind].some((s) => String(s.name).toLowerCase() === String(e.name).toLowerCase())) {
|
||||||
|
return reply(400, [{ propertyName: "Name", errorMessage: "Should be unique", isWarning: false }]);
|
||||||
|
}
|
||||||
|
const created = { ...e, id: next++ };
|
||||||
|
store[kind].push(created);
|
||||||
|
return reply(201, masked(created));
|
||||||
|
}
|
||||||
|
if (method === "PUT") {
|
||||||
|
const i = store[kind].findIndex((s) => s.id === Number(sub));
|
||||||
|
if (i < 0) return reply(404);
|
||||||
|
const was = store[kind][i];
|
||||||
|
store[kind][i] = { ...e, fields: e.fields!.map((x) => x.value === MASK ? { ...x, value: val(was, x.name) } : x) };
|
||||||
|
return reply(202, masked(store[kind][i]));
|
||||||
|
}
|
||||||
|
return reply(405);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const saves = () => calls.filter((c) => (c.method === "PUT" || (c.method === "POST" && !c.url.endsWith("/test"))) && c.url.includes("/api/v3/"));
|
||||||
|
return { http, calls, store, saves };
|
||||||
|
}
|
||||||
|
|
||||||
|
const aceClients = () => [
|
||||||
|
client(1, "NZBGet", "Nzbget", "nzbget", 6789, "nzb-real"),
|
||||||
|
client(2, "qBitTorrent", "QBittorrent", "qbittorrent", 8112, "qbt-real"),
|
||||||
|
];
|
||||||
|
|
||||||
|
test("the migration's download client is repointed, its category and everything else kept", async () => {
|
||||||
|
const f = fakes({ clients: aceClients() });
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(nzbget, "nzbget-api"), f.store.downloadclient.map((e) => ({ ...e })));
|
||||||
|
assert.deepEqual(out, [{ what: 'nzbget-api ("NZBGet")', result: "written", fields: ["host", "port"] }]);
|
||||||
|
const saved = f.store.downloadclient.find((e) => e.id === 1)!;
|
||||||
|
const v = (n: string) => saved.fields!.find((x) => x.name === n)?.value;
|
||||||
|
assert.equal(v("host"), "ace.internal");
|
||||||
|
assert.equal(v("port"), 20201);
|
||||||
|
assert.equal(v("tvCategory"), "Series");
|
||||||
|
assert.equal(v("password"), "nzb-real", "the password it held works, so it was kept, not rewritten");
|
||||||
|
assert.equal(saved.priority, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rerun: already as the mesh says, nothing saved", async () => {
|
||||||
|
const f = fakes({ clients: [client(1, "NZBGet", "Nzbget", "ace.internal", 20201, "nzb-real")] });
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(nzbget, "nzbget-api"), f.store.downloadclient);
|
||||||
|
assert.deepEqual(out, [{ what: 'nzbget-api ("NZBGet")', result: "unchanged" }]);
|
||||||
|
assert.equal(f.saves().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a stale password is replaced by the delivered one, which the provider took first", async () => {
|
||||||
|
const f = fakes({ clients: [client(2, "qBitTorrent", "QBittorrent", "ace.internal", 8112, "old-pass")] });
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qBitTorrent", endpoint(qbit, "qbittorrent-api"), f.store.downloadclient);
|
||||||
|
assert.deepEqual(out, [{ what: 'qbittorrent-api ("qBitTorrent")', result: "written", fields: ["password"] }]);
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "password")?.value, "qbt-real");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a minted credential is refused by the provider: nothing written, the accept named", async () => {
|
||||||
|
const f = fakes({ clients: aceClients() });
|
||||||
|
const ep = endpoint(nzbget, "nzbget-api", "a-value-the-mesh-minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "nzbget-api", ep), { took: false });
|
||||||
|
const remedy = acceptRemedy(APP, "ace", "nzbget-api", "nzbget", "ControlPassword", ep.from);
|
||||||
|
assert.match(remedy, /`secret accept ace sonarr nzbget-api --provider ace --from <file holding nzbget's ControlPassword>`/);
|
||||||
|
assert.doesNotMatch(remedy, /minted/);
|
||||||
|
assert.equal(f.calls.some((c) => c.url.includes("/api/v3/")), false, "the app was not even asked");
|
||||||
|
const q = endpoint(qbit, "qbittorrent-api", "minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "qbittorrent-api", q), { took: false });
|
||||||
|
const j = endpoint(jackett, "jackett-api", "minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "jackett-api", j), { took: false });
|
||||||
|
assert.equal(f.calls.find((c) => c.url.includes("apikey="))?.url.includes("jackett-real"), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a fresh app gets the mesh's client registered, under the mesh's name", async () => {
|
||||||
|
const f = fakes({});
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qbittorrent", endpoint(qbit, "qbittorrent-api"), []);
|
||||||
|
assert.equal(out[0].result, "created");
|
||||||
|
const e = f.store.downloadclient[0];
|
||||||
|
assert.equal(e.name, "qbittorrent");
|
||||||
|
assert.equal(e.enable, true);
|
||||||
|
assert.equal(e.fields!.find((x) => x.name === "tvCategory")?.value, "tv-sonarr", "the app's own default category");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("nzbget without the app's default category: registered with none, and said", async () => {
|
||||||
|
const f = fakes({});
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "nzbget", endpoint(nzbget, "nzbget-api"), []);
|
||||||
|
assert.equal(out[0].result, "notice");
|
||||||
|
assert.match((out[0] as { note: string }).note, /category left empty/);
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "tvCategory")?.value, "");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("somebody else's entries are never touched: another name of the same kind, and a clash of names", async () => {
|
||||||
|
const mine = client(7, "My seedbox", "QBittorrent", "seedbox.example", 443, "theirs");
|
||||||
|
const f = fakes({ clients: [mine] });
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qbittorrent", endpoint(qbit, "qbittorrent-api"), f.store.downloadclient);
|
||||||
|
assert.equal(out[0].result, "notice");
|
||||||
|
assert.deepEqual(f.store.downloadclient.find((e) => e.id === 7), mine);
|
||||||
|
// Same name in another case: refused, and the setting that adopts it named.
|
||||||
|
const g = fakes({ clients: aceClients() });
|
||||||
|
const clash = await reconcileClient(g.http, APP, NZBGET, "nzbget", endpoint(nzbget, "nzbget-api"), g.store.downloadclient);
|
||||||
|
assert.equal(clash[0].result, "refused");
|
||||||
|
assert.match((clash[0] as { problem: string }).problem, /downloads\.nzbget-api\.name to "NZBGet"/);
|
||||||
|
assert.equal(g.saves().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("jackett feeds: the migration's are repointed, a person's is left, a listed one is registered", async () => {
|
||||||
|
const personal = feed(9, "Seedbox jackett", "https://jackett.seedbox.example", "rutracker", "their-key");
|
||||||
|
const f = fakes({
|
||||||
|
indexers: [
|
||||||
|
feed(5, "Torznab - RuTracker", "https://indexers.zurag.be", "rutracker-ru", "jackett-real", false),
|
||||||
|
feed(6, "Torznab - Torrent9", "https://indexers.zurag.be", "torrent9", "jackett-real", false),
|
||||||
|
feed(4, "Jackett - RARBG", "http://jackett:9117", "therarbg", "old", false),
|
||||||
|
personal,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const configured = new Map(Object.entries(jackett.configured!));
|
||||||
|
const out = await reconcileIndexers(
|
||||||
|
f.http, APP, endpoint(jackett, "jackett-api"), configured,
|
||||||
|
{ adoptHosts: ["indexers.zurag.be", "jackett"], indexers: ["rutracker"] }, [], f.store.indexer,
|
||||||
|
);
|
||||||
|
const byWhat = Object.fromEntries(out.map((o) => [o.what + ":" + o.result, o]));
|
||||||
|
// torrent9: jackett has it; repointed, key already right, tested.
|
||||||
|
assert.ok(byWhat['jackett-api ("Torznab - Torrent9", jackett indexer torrent9):written']);
|
||||||
|
// rutracker-ru and therarbg: jackett has neither — repointed with the key, untested, and said.
|
||||||
|
assert.ok(byWhat['jackett-api ("Jackett - RARBG", jackett indexer therarbg):written']);
|
||||||
|
assert.ok(byWhat['jackett-api ("Jackett - RARBG", jackett indexer therarbg):notice']);
|
||||||
|
// rutracker is listed and nothing of the mesh's reads it: registered.
|
||||||
|
assert.ok(byWhat["jackett-api (jackett indexer rutracker):created"]);
|
||||||
|
assert.deepEqual(f.store.indexer.find((e) => e.id === 9), personal, "a person's jackett is not the mesh's");
|
||||||
|
const t9 = f.store.indexer.find((e) => e.id === 6)!;
|
||||||
|
assert.equal(t9.fields!.find((x) => x.name === "baseUrl")?.value, "http://ace.internal:20204");
|
||||||
|
assert.equal(t9.enableRss, false, "disabled stays disabled");
|
||||||
|
const created = f.store.indexer.find((e) => e.name === "Jackett - RuTracker")!;
|
||||||
|
assert.equal(created.enableRss, true);
|
||||||
|
assert.equal(f.calls.some((c) => c.method === "DELETE"), false, "nothing is ever deleted");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("jackett feeds rerun: nothing saved, and a remembered host keeps a moved jackett's feeds", async () => {
|
||||||
|
const f = fakes({ indexers: [feed(6, "Torznab - Torrent9", "http://ace.internal:20204", "torrent9", "jackett-real")] });
|
||||||
|
const configured = new Map(Object.entries(jackett.configured!));
|
||||||
|
const out = await reconcileIndexers(f.http, APP, endpoint(jackett, "jackett-api"), configured, { adoptHosts: [], indexers: ["torrent9"] }, [], f.store.indexer);
|
||||||
|
assert.deepEqual(out.map((o) => o.result), ["unchanged"]);
|
||||||
|
assert.equal(f.saves().length, 0);
|
||||||
|
// jackett moved to novox: the feed on ace.internal is still the mesh's because it was remembered.
|
||||||
|
const moved = { ...jackett, host: "novox.internal" };
|
||||||
|
const g = fakes({ indexers: [feed(6, "Torznab - Torrent9", "http://ace.internal:20204", "torrent9", "jackett-real")] });
|
||||||
|
const saved = jackett.host;
|
||||||
|
jackett.host = moved.host;
|
||||||
|
try {
|
||||||
|
const again = await reconcileIndexers(g.http, APP, endpoint(moved, "jackett-api"), configured, { adoptHosts: [], indexers: [] }, ["ace.internal"], g.store.indexer);
|
||||||
|
assert.equal(again[0].result, "written");
|
||||||
|
assert.equal(g.store.indexer[0].fields!.find((x) => x.name === "baseUrl")?.value, "http://novox.internal:20204");
|
||||||
|
} finally {
|
||||||
|
jackett.host = saved;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an enabled entry the app cannot test at the mesh's address is not saved", async () => {
|
||||||
|
const f = fakes({ clients: [client(1, "NZBGet", "Nzbget", "nzbget", 6789, "nzb-real")] });
|
||||||
|
const elsewhere = { ...nzbget, port: 1 };
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(elsewhere, "nzbget-api"), f.store.downloadclient);
|
||||||
|
assert.equal(out[0].result, "refused");
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "host")?.value, "nzbget", "left as it was");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("bindings: loopback, no user, no credential are refused; the base path is normalised", () => {
|
||||||
|
assert.equal(wanted("nzbget-api", { ...binding(nzbget, "nzbget-api"), at: "127.0.0.1" }, "x", true).ok, false);
|
||||||
|
assert.equal(wanted("nzbget-api", binding({ ...nzbget, user: undefined }, "nzbget-api"), "x", true).ok, false);
|
||||||
|
assert.equal(wanted("nzbget-api", binding(nzbget, "nzbget-api"), " \n", true).ok, false);
|
||||||
|
const w = wanted("jackett-api", binding(jackett, "jackett-api", { "url-base": "jackett/" }), "k", false);
|
||||||
|
assert.equal(w.ok && w.endpoint.urlBase, "/jackett");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a feed is read whole: base path in the base URL or in the API path", () => {
|
||||||
|
const e = feed(1, "x", "http://ace.internal:9117/jackett", "rutracker", "k");
|
||||||
|
assert.deepEqual(jackettFeed(e), { host: "ace.internal", id: "rutracker" });
|
||||||
|
assert.equal(jackettFeed({ ...e, implementation: "Newznab" }), undefined);
|
||||||
|
assert.equal(jackettFeed({ ...e, fields: [f("baseUrl", "https://api.nzbgeek.info"), f("apiPath", "/api")] }), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("settings: names default to the provider's, adoption and registration read from the merged file", () => {
|
||||||
|
assert.deepEqual(stepSettings({ node: "ace" }), { node: "ace", names: { "nzbget-api": "nzbget", "qbittorrent-api": "qbittorrent" }, indexers: { adoptHosts: [], indexers: [] } });
|
||||||
|
const s = stepSettings({ node: "ace", downloads: { "nzbget-api": { name: "NZBGet" }, "jackett-api": { "adopt-hosts": ["jackett"], indexers: ["torrent9", 3] } } });
|
||||||
|
assert.equal(s.names["nzbget-api"], "NZBGet");
|
||||||
|
assert.deepEqual(s.indexers, { adoptHosts: ["jackett"], indexers: ["torrent9"] });
|
||||||
|
});
|
||||||
|
|
||||||
|
// The four copies are one step. Where the siblings are checked out beside this module, they must
|
||||||
|
// be byte-identical — a fix made in one and not the others is a bug in three apps.
|
||||||
|
test("the step is the same in sonarr, radarr, lidarr and bookshelf", () => {
|
||||||
|
const here = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||||
|
const modules = dirname(here);
|
||||||
|
for (const file of ["downloads/settings.ts", "downloads/index.ts", "test/downloads.test.ts"]) {
|
||||||
|
const mine = readFileSync(join(here, file), "utf8");
|
||||||
|
for (const sibling of ["sonarr", "radarr", "lidarr", "bookshelf"]) {
|
||||||
|
const theirs = join(modules, sibling, file);
|
||||||
|
if (existsSync(theirs)) assert.equal(readFileSync(theirs, "utf8"), mine, `${sibling}/${file} differs`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
// bookshelf's tools — ported from the shared hal `arr` sdk (novox/hq ADR 0039), importing
|
||||||
|
// bookshelf's own client. They return structured data (not the pre-formatted text hal returned); the
|
||||||
|
// mesh serves them through the sdk's tool harness. Bookshelf has no calendar endpoint, so there is
|
||||||
|
// no calendar tool — matching hal, which excluded it from its calendar-capable apps.
|
||||||
|
|
||||||
|
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||||
|
import { BookshelfClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getBookshelfTools(bookshelf: BookshelfClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "bookshelf_status",
|
||||||
|
description: "Bookshelf status overview: version, book count, monitored count, queue size.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const [status, content, queue] = await Promise.all([
|
||||||
|
bookshelf.getStatus(),
|
||||||
|
bookshelf.getContent(),
|
||||||
|
bookshelf.getQueue(),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
app: status.appName,
|
||||||
|
version: status.version,
|
||||||
|
books: content.length,
|
||||||
|
monitored: content.filter((c) => c.monitored).length,
|
||||||
|
queue: queue.totalRecords,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bookshelf_library",
|
||||||
|
description: "List books from the Bookshelf library.",
|
||||||
|
input: { limit: { type: "number", description: "max items to return (default 50)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const items = await bookshelf.getContent(args.limit ? Number(args.limit) : 50);
|
||||||
|
return { count: items.length, books: items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bookshelf_search",
|
||||||
|
description:
|
||||||
|
"Search the Bookshelf library for books by title or author (filters existing content, not indexers).",
|
||||||
|
input: { query: { type: "string", description: "the search term" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const query = String(args.query);
|
||||||
|
return { query, results: await bookshelf.searchContent(query) };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bookshelf_queue",
|
||||||
|
description: "Show the Bookshelf download queue — what is downloading and how far along.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const queue = await bookshelf.getQueue();
|
||||||
|
return { count: queue.totalRecords, items: queue.items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tools exist only when Bookshelf is configured; without a URL and key, bookshelf contributes
|
||||||
|
// none rather than failing the whole runtime.
|
||||||
|
registerModuleTools("bookshelf", (env) => {
|
||||||
|
try {
|
||||||
|
return getBookshelfTools(BookshelfClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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", "downloads/settings.ts", "downloads/index.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# jackett's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/jackett
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/jackett/dist /app/modules/jackett/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/jackett/dist/tools/index.js
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
// The Jackett API client — jackett's own code, living in the module (novox/hq ADR 0039). Jackett is
|
||||||
|
// an indexer proxy: it normalises many torrent trackers behind one Torznab surface. This client
|
||||||
|
// talks its /api/v2.0 REST API, and only jackett's tools import it.
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
export interface JackettIndexer {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: string; // "public" | "private" | "semi-public"
|
||||||
|
configured: boolean;
|
||||||
|
siteLink?: string;
|
||||||
|
lastError?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface JackettResult {
|
||||||
|
title: string;
|
||||||
|
tracker: string;
|
||||||
|
category?: string;
|
||||||
|
size: number;
|
||||||
|
seeders?: number;
|
||||||
|
peers?: number;
|
||||||
|
publishDate?: string;
|
||||||
|
link?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
|
||||||
|
function meshConfig(file?: string): Record<string, string> {
|
||||||
|
if (!file) return {};
|
||||||
|
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
|
||||||
|
catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class JackettClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly apiKey: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the module's resolved environment. Jackett's REST API is keyed, so both the URL and
|
||||||
|
* the key must be present. The key is read from the settings-merged config or MESH_JACKETT_API_KEY,
|
||||||
|
* or, failing those, discovered from Jackett's own ServerConfig.json under MESH_JACKETT_CONFIG_DIR
|
||||||
|
* — the file Jackett writes it to, as sonarr/radarr read theirs from config.xml — so a running
|
||||||
|
* server needs no key configured by hand and no secret has to be put in an assignment. Without a
|
||||||
|
* URL or key there is nothing to talk to, so this throws and the module contributes no tools
|
||||||
|
* rather than failing half-configured.
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): JackettClient {
|
||||||
|
const cfg = meshConfig(env.MESH_JACKETT_CONFIG_FILE);
|
||||||
|
const url = cfg.url ?? env.MESH_JACKETT_URL;
|
||||||
|
const apiKey = cfg.apiKey ?? env.MESH_JACKETT_API_KEY
|
||||||
|
?? JackettClient.detectApiKey(env.MESH_JACKETT_CONFIG_DIR ?? "/config");
|
||||||
|
if (!url) throw new Error("no Jackett URL — set MESH_JACKETT_URL");
|
||||||
|
if (!apiKey) throw new Error("no Jackett API key — set MESH_JACKETT_API_KEY or make the config dir readable");
|
||||||
|
return new JackettClient(url, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Discover the API key from Jackett's ServerConfig.json (the linuxserver image keeps it at
|
||||||
|
* <config>/Jackett/ServerConfig.json), falling back to null. */
|
||||||
|
static detectApiKey(configDir: string): string | null {
|
||||||
|
for (const file of [join(configDir, "Jackett", "ServerConfig.json"), join(configDir, "ServerConfig.json")]) {
|
||||||
|
if (!existsSync(file)) continue;
|
||||||
|
try {
|
||||||
|
const key = (JSON.parse(readFileSync(file, "utf8")) as { APIKey?: unknown }).APIKey;
|
||||||
|
if (typeof key === "string" && key) return key;
|
||||||
|
} catch { /* unreadable or mid-write: try the next, then give up */ }
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async get(path: string, params: Record<string, string> = {}): Promise<any> {
|
||||||
|
const url = new URL(`${this.baseUrl}${path}`);
|
||||||
|
url.searchParams.set("apikey", this.apiKey);
|
||||||
|
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||||
|
const res = await fetch(url.toString(), { headers: { Accept: "application/json" } });
|
||||||
|
if (!res.ok) throw new Error(`Jackett API ${path}: ${res.status} ${await res.text()}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The configured indexers Jackett proxies. `configured=false` also lists the ones not set up.
|
||||||
|
* Read from the Torznab `t=indexers` feed, not /api/v2.0/indexers: that one is the web UI's and
|
||||||
|
* wants a login cookie (it answers an API-key request with a redirect), while the Torznab feed is
|
||||||
|
* what the key is for. The feed carries no last error, so `lastError` stays unset.
|
||||||
|
*/
|
||||||
|
async getIndexers(configuredOnly = true): Promise<JackettIndexer[]> {
|
||||||
|
const url = new URL(`${this.baseUrl}/api/v2.0/indexers/all/results/torznab/api`);
|
||||||
|
url.searchParams.set("apikey", this.apiKey);
|
||||||
|
url.searchParams.set("t", "indexers");
|
||||||
|
url.searchParams.set("configured", configuredOnly ? "true" : "false");
|
||||||
|
const res = await fetch(url.toString(), { headers: { Accept: "application/xml" } });
|
||||||
|
if (!res.ok) throw new Error(`Jackett API torznab t=indexers: ${res.status} ${await res.text()}`);
|
||||||
|
const xml = await res.text();
|
||||||
|
// Torznab reports failures (a wrong key among them) as 200 with an <error> body.
|
||||||
|
const err = xml.match(/<error code="(\d+)" description="([^"]*)"/);
|
||||||
|
if (err) throw new Error(`Jackett API torznab t=indexers: error ${err[1]} ${err[2]}`);
|
||||||
|
const text = (block: string, tag: string) =>
|
||||||
|
block.match(new RegExp(`<${tag}>([^<]*)</${tag}>`))?.[1];
|
||||||
|
const out: JackettIndexer[] = [];
|
||||||
|
for (const m of xml.matchAll(/<indexer id="([^"]+)" configured="([^"]+)">([\s\S]*?)<\/indexer>/g)) {
|
||||||
|
out.push({
|
||||||
|
id: m[1],
|
||||||
|
name: text(m[3], "title") ?? m[1],
|
||||||
|
type: text(m[3], "type") ?? "unknown",
|
||||||
|
configured: m[2] === "true",
|
||||||
|
siteLink: text(m[3], "link"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A Torznab search across one indexer, or the "all" aggregate. Jackett returns a normalised JSON
|
||||||
|
* result set regardless of the underlying tracker, which is the whole point of the proxy.
|
||||||
|
*/
|
||||||
|
async search(query: string, indexer = "all", limit = 25): Promise<JackettResult[]> {
|
||||||
|
const raw = await this.get(`/api/v2.0/indexers/${encodeURIComponent(indexer)}/results`, { Query: query });
|
||||||
|
const results = Array.isArray(raw?.Results) ? raw.Results : [];
|
||||||
|
return results.slice(0, limit).map((r: any) => ({
|
||||||
|
title: r.Title,
|
||||||
|
tracker: r.Tracker ?? r.TrackerId ?? "unknown",
|
||||||
|
category: Array.isArray(r.CategoryDesc) ? r.CategoryDesc.join(", ") : r.CategoryDesc,
|
||||||
|
size: r.Size ?? 0,
|
||||||
|
seeders: r.Seeders,
|
||||||
|
peers: r.Peers,
|
||||||
|
publishDate: r.PublishDate,
|
||||||
|
link: r.Link ?? r.Details,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
{
|
||||||
|
"module": "jackett",
|
||||||
|
"version": "1",
|
||||||
|
"provides": [
|
||||||
|
{
|
||||||
|
"name": "jackett-api",
|
||||||
|
"scope": "mesh"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"serves": {
|
||||||
|
"jackett-api": {
|
||||||
|
"scheme": "http",
|
||||||
|
"port": 9117,
|
||||||
|
"url-base": ""
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 9117,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "the indexer proxy: its web UI, and the Torznab feeds the *arr apps search through, which other modules reach as jackett-api"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/jackett",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "jackett",
|
||||||
|
"image": "lscr.io/linuxserver/jackett@sha256:7b19f4f6ac33d855ca9226600ecbd096ee678f66da28b13a7c09980b035ff583",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC"
|
||||||
|
},
|
||||||
|
"ports": [
|
||||||
|
"9117"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/config.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-jackett",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/jackett/broker:/run/secrets/broker:ro",
|
||||||
|
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||||
|
"${dir:config}:/var/lib/jackett/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_JACKETT_URL": "http://127.0.0.1:${port:9117}",
|
||||||
|
"MESH_JACKETT_CONFIG_FILE": "/run/config/config.json",
|
||||||
|
"MESH_JACKETT_CONFIG_DIR": "/var/lib/jackett/config"
|
||||||
|
},
|
||||||
|
"restart-on": [
|
||||||
|
"runtime-config"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/jackett/broker"
|
||||||
|
},
|
||||||
|
"requires": [
|
||||||
|
"route"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "indexers",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-jackett",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "jackett — indexer proxy. Its API client and tools live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// jackett's tools — its own code (novox/hq ADR 0039), importing jackett's client. Jackett has
|
||||||
|
// nothing worth watching (an indexer proxy answers queries; it has no timeline of its own), so it
|
||||||
|
// is a tools-only module: no events entrypoint, no broker. What is useful is asking it things.
|
||||||
|
|
||||||
|
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||||
|
import { JackettClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getJackettTools(jackett: JackettClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "jackett_indexers",
|
||||||
|
description: "List the indexers Jackett proxies, with their type and site.",
|
||||||
|
input: { all: { type: "boolean", description: "include indexers not yet configured (default false)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const indexers = await jackett.getIndexers(!args.all);
|
||||||
|
return { count: indexers.length, indexers };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "jackett_search",
|
||||||
|
description: "Torznab search across Jackett's indexers, returning normalised torrent results.",
|
||||||
|
input: {
|
||||||
|
query: { type: "string", description: "the search query" },
|
||||||
|
indexer: { type: "string", description: 'an indexer id, or "all" to aggregate (default "all")' },
|
||||||
|
limit: { type: "number", description: "max results (default 25)" },
|
||||||
|
},
|
||||||
|
run: async (args) => {
|
||||||
|
const query = String(args.query);
|
||||||
|
const results = await jackett.search(
|
||||||
|
query,
|
||||||
|
args.indexer ? String(args.indexer) : "all",
|
||||||
|
args.limit ? Number(args.limit) : 25,
|
||||||
|
);
|
||||||
|
return { query, count: results.length, results };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only exposed when Jackett is configured; otherwise jackett contributes no tools rather than
|
||||||
|
// failing the whole runtime.
|
||||||
|
registerModuleTools("jackett", (env) => {
|
||||||
|
try {
|
||||||
|
return getJackettTools(JackettClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"noEmit": true
|
||||||
|
},
|
||||||
|
"include": ["client.ts", "tools/index.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# kometa's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# Built from this module's own directory and nothing else; the sdk and the tool runtime are in the
|
||||||
|
# base images, declared in module.json's `build.on` (novox/hq ADR 0069, issue 044).
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/kometa
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/kometa/dist /app/modules/kometa/dist
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/kometa/dist/tools/index.js
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// Kometa's "client" — kometa's own code (novox/hq ADR 0039). Kometa is a scheduled job, not a
|
||||||
|
// server: it has no API to call. What can be asked is what it left behind: the rendered config it
|
||||||
|
// runs with and the logs of its last runs. Only kometa's tools import this.
|
||||||
|
|
||||||
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
export interface KometaRun {
|
||||||
|
log: string;
|
||||||
|
finishedAt: string;
|
||||||
|
lines: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class KometaClient {
|
||||||
|
constructor(
|
||||||
|
private readonly configDir: string,
|
||||||
|
private readonly configFile: string,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the runtime's environment: the placed config dir (assets, logs, cache) and the
|
||||||
|
* config.yml the mesh renders. Both are mounted read-only into the runtime; nothing here writes.
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): KometaClient {
|
||||||
|
const dir = env.MESH_KOMETA_CONFIG_DIR ?? "/var/lib/kometa/config";
|
||||||
|
const file = env.MESH_KOMETA_CONFIG_FILE ?? "/var/lib/kometa/config.yml";
|
||||||
|
if (!existsSync(dir)) throw new Error(`no kometa config dir at ${dir}`);
|
||||||
|
return new KometaClient(dir, file);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The config kometa runs with, its credentials blanked: tokens and API keys are never returned. */
|
||||||
|
config(): string {
|
||||||
|
if (!existsSync(this.configFile)) return "";
|
||||||
|
return readFileSync(this.configFile, "utf8").replace(
|
||||||
|
/^(\s*(token|apikey|api_key|password|secret|client_secret)\s*:\s*).*$/gim,
|
||||||
|
"$1<redacted>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The newest logs kometa wrote under logs/, newest first, with their last lines. */
|
||||||
|
runs(limit = 3, tail = 20): KometaRun[] {
|
||||||
|
const logs = join(this.configDir, "logs");
|
||||||
|
if (!existsSync(logs)) return [];
|
||||||
|
return readdirSync(logs)
|
||||||
|
.filter((f) => f.endsWith(".log"))
|
||||||
|
.map((f) => ({ f, at: statSync(join(logs, f)).mtime }))
|
||||||
|
.sort((a, b) => b.at.getTime() - a.at.getTime())
|
||||||
|
.slice(0, limit)
|
||||||
|
.map(({ f, at }) => {
|
||||||
|
const lines = readFileSync(join(logs, f), "utf8").trimEnd().split("\n");
|
||||||
|
return { log: f, finishedAt: at.toISOString(), lines: lines.slice(-tail) };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
{
|
||||||
|
"module": "kometa",
|
||||||
|
"version": "1",
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"requires": [
|
||||||
|
"plex-api"
|
||||||
|
],
|
||||||
|
"own-secrets": {
|
||||||
|
"tmdb": "${dir:state}/tmdb.secret",
|
||||||
|
"broker": "/var/lib/mesh/kometa/broker"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"plex-api": "${dir:state}/plex-api.json"
|
||||||
|
},
|
||||||
|
"secrets": {
|
||||||
|
"plex-api": "${dir:state}/plex-api.secret"
|
||||||
|
},
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "settings",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/config.yml",
|
||||||
|
"mode": "0600",
|
||||||
|
"merge": "json",
|
||||||
|
"content": "{\n \"plex\": {\n \"url\": \"${bound:plex-api:scheme}://${bound:plex-api:at}:${bound:plex-api:port}\",\n \"token\": \"${secret:plex-api}\",\n \"timeout\": 60,\n \"clean_bundles\": false,\n \"empty_trash\": false,\n \"optimize\": false,\n \"verify_ssl\": null,\n \"db_cache\": null\n },\n \"tmdb\": {\n \"apikey\": \"${secret:tmdb}\",\n \"language\": \"en\",\n \"cache_expiration\": 60,\n \"region\": null\n },\n \"settings\": {\n \"cache\": true,\n \"cache_expiration\": 60,\n \"asset_directory\": \"config/assets\",\n \"sync_mode\": \"append\",\n \"minimum_items\": 1,\n \"delete_below_minimum\": false,\n \"run_again_delay\": 2,\n \"show_missing\": false,\n \"save_report\": false,\n \"run_order\": [\n \"operations\",\n \"metadata\",\n \"collections\",\n \"overlays\"\n ],\n \"asset_folders\": true,\n \"asset_depth\": 0,\n \"create_asset_folders\": false,\n \"prioritize_assets\": false,\n \"dimensional_asset_rename\": false,\n \"download_url_assets\": false,\n \"show_missing_assets\": true,\n \"show_missing_season_assets\": false,\n \"show_missing_episode_assets\": false,\n \"show_asset_not_needed\": true,\n \"default_collection_order\": null,\n \"item_refresh_delay\": 0,\n \"delete_not_scheduled\": false,\n \"missing_only_released\": false,\n \"only_filter_missing\": false,\n \"show_unmanaged\": true,\n \"show_unconfigured\": true,\n \"show_filtered\": false,\n \"show_unfiltered\": false,\n \"show_options\": false,\n \"tvdb_language\": \"default\",\n \"ignore_ids\": null,\n \"ignore_imdb_ids\": null,\n \"playlist_sync_to_users\": null,\n \"playlist_exclude_users\": null,\n \"playlist_report\": true,\n \"custom_repo\": null,\n \"overlay_artwork_filetype\": \"webp_lossy\",\n \"overlay_artwork_quality\": 90,\n \"auto_sort_hubs\": null,\n \"verify_ssl\": true\n },\n \"libraries\": {}\n}\n"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "net",
|
||||||
|
"type": "network",
|
||||||
|
"name": "kometa"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "run",
|
||||||
|
"type": "container",
|
||||||
|
"name": "kometa",
|
||||||
|
"image": "kometateam/kometa@sha256:6c3971a4aaa928b045e5f22514196b6db7f9b2b186158ebfe3239f4b328dfb0a",
|
||||||
|
"network": "kometa",
|
||||||
|
"schedule": "0 3 * * *",
|
||||||
|
"args": [
|
||||||
|
"--run"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"TZ": "Etc/UTC",
|
||||||
|
"KOMETA_NO_MISSING": "true",
|
||||||
|
"KOMETA_READ_ONLY_CONFIG": "true"
|
||||||
|
},
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"${dir:state}/config.yml:/config/config.yml:ro"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/config.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-kometa",
|
||||||
|
"artifact": "runtime",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/kometa/broker:/run/secrets/broker:ro",
|
||||||
|
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||||
|
"${dir:state}/config.yml:/var/lib/kometa/config.yml:ro",
|
||||||
|
"${dir:config}:/var/lib/kometa/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_KOMETA_CONFIG_FILE": "/var/lib/kometa/config.yml",
|
||||||
|
"MESH_KOMETA_CONFIG_DIR": "/var/lib/kometa/config"
|
||||||
|
},
|
||||||
|
"restart-on": [
|
||||||
|
"runtime-config",
|
||||||
|
"settings"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-kometa",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "kometa — Plex metadata and collections on a schedule. Its tools live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// kometa's tools — its own code (novox/hq ADR 0039), importing kometa's client. Kometa runs on a
|
||||||
|
// schedule and has no API, so the tools read what it leaves behind. Two tools, the example to
|
||||||
|
// extend: what it ran with, and how its last runs went.
|
||||||
|
|
||||||
|
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||||
|
import { KometaClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getKometaTools(kometa: KometaClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "kometa_status",
|
||||||
|
description: "Kometa's last runs: the newest logs it wrote and their last lines.",
|
||||||
|
input: {
|
||||||
|
runs: { type: "number", description: "how many runs, newest first (default 3)" },
|
||||||
|
tail: { type: "number", description: "lines per run (default 20)" },
|
||||||
|
},
|
||||||
|
run: async (args) => {
|
||||||
|
const runs = kometa.runs(args.runs ? Number(args.runs) : 3, args.tail ? Number(args.tail) : 20);
|
||||||
|
return { count: runs.length, runs };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "kometa_config",
|
||||||
|
description: "The config.yml kometa runs with, credentials redacted.",
|
||||||
|
input: {},
|
||||||
|
run: async () => ({ config: kometa.config() }),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only exposed when the config dir is there; otherwise kometa contributes no tools rather than
|
||||||
|
// failing the whole runtime.
|
||||||
|
registerModuleTools("kometa", (env) => {
|
||||||
|
try {
|
||||||
|
return getKometaTools(KometaClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"noEmit": true
|
||||||
|
},
|
||||||
|
"include": ["client.ts", "tools/index.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# lidarr's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/lidarr
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts downloads/settings.ts downloads/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/lidarr/dist /app/modules/lidarr/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/lidarr/dist/index.js,/app/modules/lidarr/dist/tools/index.js
|
||||||
|
# NOT dist/downloads/index.js: that is a step the host runs to completion, named by the `downloads`
|
||||||
|
# container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run inside the
|
||||||
|
# serving sidecar too, and exit it.
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
// The Lidarr API client — lidarr's own code, living in the module (novox/hq ADR 0039). Ported from
|
||||||
|
// the shared hal `arr` client, but self-contained: in nox each Servarr app owns its own copy, so a
|
||||||
|
// change to Lidarr's API rebuilds only lidarr and nothing else. Both this module's tools and its
|
||||||
|
// events entrypoint import it, and nothing outside lidarr does.
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
// Lidarr speaks the v1 API (Radarr/Sonarr are v3); its content is the "artist".
|
||||||
|
const API_VERSION = "v1";
|
||||||
|
const CONTENT_ENDPOINT = "artist";
|
||||||
|
const APP_NAME = "Lidarr";
|
||||||
|
|
||||||
|
export interface LidarrQueueItem {
|
||||||
|
/** The queue record id — stable while the item is in the queue, so events can diff on it. */
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
status: string;
|
||||||
|
size: string;
|
||||||
|
sizeleft: string;
|
||||||
|
timeleft?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LidarrCalendarItem {
|
||||||
|
title: string;
|
||||||
|
date: string;
|
||||||
|
overview?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LidarrContentItem {
|
||||||
|
title: string;
|
||||||
|
status?: string;
|
||||||
|
monitored: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LidarrClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly apiKey: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the module's resolved environment. The URL defaults to the server on this node (the
|
||||||
|
* runtime shares its network), and the API key is read from MESH_LIDARR_API_KEY or, failing that,
|
||||||
|
* discovered from the server's own config.xml under MESH_LIDARR_CONFIG_DIR — the same file Lidarr
|
||||||
|
* writes it to, so a running server needs nothing configured by hand. Throws when no key can be
|
||||||
|
* found, so the tools/events simply do not load (the harness treats the throw as "exposes
|
||||||
|
* nothing").
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): LidarrClient {
|
||||||
|
const url = env.MESH_LIDARR_URL ?? `http://127.0.0.1:${env.MESH_LIDARR_PORT ?? "8686"}`;
|
||||||
|
const configDir = env.MESH_LIDARR_CONFIG_DIR ?? "/config";
|
||||||
|
const apiKey = env.MESH_LIDARR_API_KEY ?? LidarrClient.detectApiKey(configDir);
|
||||||
|
if (!apiKey) {
|
||||||
|
throw new Error("Lidarr not configured — set MESH_LIDARR_API_KEY or make the config dir readable");
|
||||||
|
}
|
||||||
|
return new LidarrClient(url, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Discover the API key from the server's config.xml, falling back to null. Every Servarr app
|
||||||
|
* writes <ApiKey> into config.xml at the root of its config directory. */
|
||||||
|
static detectApiKey(configDir: string): string | null {
|
||||||
|
const config = join(configDir, "config.xml");
|
||||||
|
if (existsSync(config)) {
|
||||||
|
const match = readFileSync(config, "utf8").match(/<ApiKey>([^<]+)<\/ApiKey>/);
|
||||||
|
if (match) return match[1];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async get(endpoint: string, params?: Record<string, string>): Promise<unknown> {
|
||||||
|
const url = new URL(`${this.baseUrl}/api/${API_VERSION}/${endpoint}`);
|
||||||
|
if (params) {
|
||||||
|
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||||
|
}
|
||||||
|
const res = await fetch(url.toString(), { headers: { "X-Api-Key": this.apiKey } });
|
||||||
|
if (!res.ok) throw new Error(`${APP_NAME} API /${endpoint}: ${res.status} ${await res.text()}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getStatus(): Promise<{ appName: string; version: string }> {
|
||||||
|
const data = (await this.get("system/status")) as { appName?: string; version?: string };
|
||||||
|
return { appName: data.appName || APP_NAME, version: data.version ?? "unknown" };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getContent(limit?: number): Promise<LidarrContentItem[]> {
|
||||||
|
const data = await this.get(CONTENT_ENDPOINT);
|
||||||
|
const items: any[] = Array.isArray(data) ? data : ((data as any)?.records ?? []);
|
||||||
|
const mapped = items.map((item) => ({
|
||||||
|
// Lidarr's content is an artist; its display name is artistName, not title.
|
||||||
|
title: item.artistName ?? item.title ?? "Unknown",
|
||||||
|
status: item.status,
|
||||||
|
monitored: item.monitored ?? true,
|
||||||
|
}));
|
||||||
|
return limit ? mapped.slice(0, limit) : mapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Library search is a filter over existing content, not an indexer lookup — same as hal's. */
|
||||||
|
async searchContent(term: string): Promise<LidarrContentItem[]> {
|
||||||
|
const all = await this.getContent();
|
||||||
|
const lower = term.toLowerCase();
|
||||||
|
return all.filter((item) => item.title.toLowerCase().includes(lower));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getQueue(): Promise<{ totalRecords: number; items: LidarrQueueItem[] }> {
|
||||||
|
const data = (await this.get("queue", { pageSize: "50" })) as { totalRecords?: number; records?: any[] };
|
||||||
|
const records = data.records ?? [];
|
||||||
|
return {
|
||||||
|
totalRecords: data.totalRecords ?? records.length,
|
||||||
|
items: records.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
title: r.title ?? r.artist?.artistName ?? r.album?.title ?? "Unknown",
|
||||||
|
status: r.status ?? "unknown",
|
||||||
|
size: formatBytes(r.size ?? 0),
|
||||||
|
sizeleft: formatBytes(r.sizeleft ?? 0),
|
||||||
|
timeleft: r.timeleft,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCalendar(days = 7): Promise<LidarrCalendarItem[]> {
|
||||||
|
const start = new Date().toISOString().split("T")[0];
|
||||||
|
const end = new Date(Date.now() + days * 86400000).toISOString().split("T")[0];
|
||||||
|
const data = await this.get("calendar", { start, end });
|
||||||
|
const items: any[] = Array.isArray(data) ? data : [];
|
||||||
|
return items.map((item) => ({
|
||||||
|
// A Lidarr calendar entry is an album release.
|
||||||
|
title: item.title ?? item.artist?.artistName ?? "Unknown",
|
||||||
|
date: item.releaseDate ?? "",
|
||||||
|
overview: item.overview?.slice(0, 150),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes === 0) return "0 B";
|
||||||
|
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||||
|
return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
// The downloads step — run once by the host after the app's server starts, and again whenever a
|
||||||
|
// binding, a pair credential or the step's settings change (the container's `restart-on`,
|
||||||
|
// novox/hq ADR 0099). Byte-identical in sonarr, radarr, lidarr and bookshelf; see settings.ts.
|
||||||
|
//
|
||||||
|
// **A step, not a loop**: everything it does is a function of files the mesh writes, and the host
|
||||||
|
// already knows when they change. It connects to no broker.
|
||||||
|
//
|
||||||
|
// Exits non-zero when anything could not be put right — a refused credential, an unreachable
|
||||||
|
// provider, an entry the app would not save — so the node reports the step failed and the host
|
||||||
|
// runs it again on the next apply. Declared last in the manifest, so its failing gates nothing
|
||||||
|
// else of the module's (novox/hq ADR 0136).
|
||||||
|
//
|
||||||
|
// Reads, in MESH_DOWNLOADS_DIR, `<provision>.json` (the binding), `<provision>.secret` (the pair
|
||||||
|
// credential) and the settings file; remembers in MESH_DOWNLOADS_MEMORY the jackett hosts it has
|
||||||
|
// pointed feeds at, so a jackett that moves takes its feeds with it. Never prints a credential.
|
||||||
|
|
||||||
|
import { mkdir, rename, writeFile } from "node:fs/promises";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CLIENTS,
|
||||||
|
JACKETT,
|
||||||
|
acceptRemedy,
|
||||||
|
appConfig,
|
||||||
|
appReady,
|
||||||
|
listEntries,
|
||||||
|
providerTakes,
|
||||||
|
readIfThere,
|
||||||
|
readJson,
|
||||||
|
reconcileClient,
|
||||||
|
reconcileIndexers,
|
||||||
|
scrub,
|
||||||
|
stepSettings,
|
||||||
|
wanted,
|
||||||
|
type App,
|
||||||
|
type Binding,
|
||||||
|
type Http,
|
||||||
|
type Entry,
|
||||||
|
type Outcome,
|
||||||
|
type Took,
|
||||||
|
} from "./settings.js";
|
||||||
|
|
||||||
|
const module = process.env.MESH_DOWNLOADS_APP ?? "app";
|
||||||
|
const dir = process.env.MESH_DOWNLOADS_DIR ?? "/run/downloads";
|
||||||
|
const settingsFile = process.env.MESH_DOWNLOADS_SETTINGS ?? join(dir, "downloads.json");
|
||||||
|
const memoryFile = process.env.MESH_DOWNLOADS_MEMORY ?? "/var/lib/downloads/memory.json";
|
||||||
|
const waitSeconds = Number(process.env.MESH_DOWNLOADS_WAIT_SECONDS ?? "180");
|
||||||
|
const tag = `[${module}-downloads]`;
|
||||||
|
|
||||||
|
const http: Http = { fetch: (u, init) => fetch(u, init) };
|
||||||
|
const secrets: string[] = [];
|
||||||
|
const say = (line: string) => console.log(scrub(`${tag} ${line}`, secrets));
|
||||||
|
const fail = (line: string) => console.error(scrub(`${tag} ${line}`, secrets));
|
||||||
|
|
||||||
|
const config = appConfig((await readIfThere(process.env.MESH_DOWNLOADS_APP_CONFIG)) ?? "");
|
||||||
|
if (!config.apiKey) {
|
||||||
|
fail(`no API key in ${module}'s config.xml yet — ${module} writes it on its first start; the step runs again on the next apply`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
secrets.push(config.apiKey);
|
||||||
|
const app: App = {
|
||||||
|
module,
|
||||||
|
url: `${(process.env.MESH_DOWNLOADS_APP_URL ?? "http://127.0.0.1").replace(/\/$/, "")}${config.urlBase}`,
|
||||||
|
apiKey: config.apiKey,
|
||||||
|
api: process.env.MESH_DOWNLOADS_API ?? "v3",
|
||||||
|
};
|
||||||
|
const settings = stepSettings(await readJson(settingsFile));
|
||||||
|
|
||||||
|
if (!(await appReady(http, app, waitSeconds * 1000))) {
|
||||||
|
fail(`${module} did not answer at ${app.url} within ${waitSeconds}s`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
|
||||||
|
// The download clients.
|
||||||
|
let clients: Entry[];
|
||||||
|
try {
|
||||||
|
clients = await listEntries(http, app, "downloadclient");
|
||||||
|
} catch (err) {
|
||||||
|
fail(err instanceof Error ? err.message : String(err));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
for (const kind of CLIENTS) {
|
||||||
|
const credential = await readIfThere(join(dir, `${kind.provision}.secret`));
|
||||||
|
if (credential) secrets.push(credential.trim());
|
||||||
|
const w = wanted(kind.provision, (await readJson(join(dir, `${kind.provision}.json`))) as Binding | undefined, credential, true);
|
||||||
|
// `in`, not `!w.ok`: the Dockerfile compiles without strict, where a boolean discriminant does not
|
||||||
|
// narrow.
|
||||||
|
if ("problem" in w) {
|
||||||
|
outcomes.push({ what: kind.provision, result: "refused", problem: w.problem });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const ep = w.endpoint;
|
||||||
|
try {
|
||||||
|
if (!(await providerTakes(http, kind.provision, ep)).took) {
|
||||||
|
outcomes.push({
|
||||||
|
what: kind.provision,
|
||||||
|
result: "refused",
|
||||||
|
problem: acceptRemedy(app, settings.node, kind.provision, kind.provider, kind.secretName, ep.from),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: kind.provision,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${kind.provider} could not be asked whether it takes the credential at ${ep.host}:${ep.port}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
outcomes.push(...(await reconcileClient(http, app, kind, settings.names[kind.provision], ep, clients)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The indexers, through jackett.
|
||||||
|
{
|
||||||
|
const credential = await readIfThere(join(dir, `${JACKETT}.secret`));
|
||||||
|
if (credential) secrets.push(credential.trim());
|
||||||
|
const w = wanted(JACKETT, (await readJson(join(dir, `${JACKETT}.json`))) as Binding | undefined, credential, false);
|
||||||
|
if ("problem" in w) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: w.problem });
|
||||||
|
} else {
|
||||||
|
const ep = w.endpoint;
|
||||||
|
let took: Took | undefined;
|
||||||
|
try {
|
||||||
|
took = await providerTakes(http, JACKETT, ep);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: JACKETT,
|
||||||
|
result: "refused",
|
||||||
|
problem: `jackett could not be asked whether it takes the key at ${ep.host}:${ep.port}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (took && !took.took) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: acceptRemedy(app, settings.node, JACKETT, "jackett", "API key", ep.from) });
|
||||||
|
} else if (took) {
|
||||||
|
const memory = ((await readJson(memoryFile)) ?? {}) as Record<string, { hosts?: string[] } | undefined>;
|
||||||
|
const remembered = Array.isArray(memory[JACKETT]?.hosts) ? (memory[JACKETT]?.hosts as string[]) : [];
|
||||||
|
try {
|
||||||
|
const indexers = await listEntries(http, app, "indexer");
|
||||||
|
outcomes.push(
|
||||||
|
...(await reconcileIndexers(http, app, ep, took.configured ?? new Map(), settings.indexers, remembered, indexers)),
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: err instanceof Error ? err.message : String(err) });
|
||||||
|
}
|
||||||
|
// Remember where the feeds now point, so they are still recognised as the mesh's if jackett
|
||||||
|
// moves. Written whole and renamed, so a crash leaves the old memory, never half of one.
|
||||||
|
const hosts = [...new Set([...remembered, ep.host.toLowerCase()])].sort();
|
||||||
|
if (hosts.join() !== [...remembered].sort().join()) {
|
||||||
|
try {
|
||||||
|
await mkdir(dirname(memoryFile), { recursive: true });
|
||||||
|
await writeFile(`${memoryFile}.tmp`, JSON.stringify({ ...memory, [JACKETT]: { hosts } }, null, 2) + "\n", { mode: 0o600 });
|
||||||
|
await rename(`${memoryFile}.tmp`, memoryFile);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: JACKETT,
|
||||||
|
result: "notice",
|
||||||
|
note: `could not remember ${ep.host} as a jackett host (${err instanceof Error ? err.message : String(err)}); if jackett moves, list it in downloads.jackett-api.adopt-hosts`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let failed = 0;
|
||||||
|
for (const o of outcomes) {
|
||||||
|
switch (o.result) {
|
||||||
|
case "unchanged":
|
||||||
|
say(`${o.what}: already as the mesh says${o.untested ? "" : "; connection tested"}`);
|
||||||
|
break;
|
||||||
|
case "written":
|
||||||
|
say(`${o.what}: wrote ${o.fields.join(", ")}${o.untested ? "" : "; connection tested"}`);
|
||||||
|
break;
|
||||||
|
case "created":
|
||||||
|
say(`${o.what}: registered; connection tested`);
|
||||||
|
break;
|
||||||
|
case "notice":
|
||||||
|
say(`${o.what}: ${o.note}`);
|
||||||
|
break;
|
||||||
|
case "refused":
|
||||||
|
failed++;
|
||||||
|
fail(`${o.what}: ${o.problem}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.exitCode = failed > 0 ? 1 : 0;
|
||||||
@@ -0,0 +1,778 @@
|
|||||||
|
// Where a Servarr app reaches its download clients and its indexer proxy — decided by the mesh,
|
||||||
|
// written into the app by the app's own API.
|
||||||
|
//
|
||||||
|
// **One file, four copies.** sonarr, radarr, lidarr and bookshelf (a Readarr fork) keep their
|
||||||
|
// download clients and indexers behind the same API — `/api/v3/…` for the first two, `/api/v1/…`
|
||||||
|
// for the others — so this step is the same code in each. Each module builds from its own
|
||||||
|
// directory (novox/hq ADR 0069), so each carries a byte-identical copy under `downloads/`;
|
||||||
|
// `test/downloads.test.ts` checks the copies agree wherever the siblings are checked out beside
|
||||||
|
// it. Change all four together.
|
||||||
|
//
|
||||||
|
// **Why this exists.** The app keeps its connection to nzbget, qBittorrent and jackett in its own
|
||||||
|
// database, not in a file, so the mesh has nowhere to write `${bound:nzbget-api:at}` for it. The
|
||||||
|
// module requires `nzbget-api`, `qbittorrent-api` and `jackett-api`; the mesh delivers, for each,
|
||||||
|
// a binding (where the provider is — `at` — and what it serves: `port`, `scheme`, `url-base`, and
|
||||||
|
// for a download client the `username`) and a pair credential (nzbget's ControlPassword,
|
||||||
|
// qBittorrent's WebUI password, jackett's API key — each the provider's one and only, accepted by
|
||||||
|
// the operator per pair; the mesh cannot mint them). This step reads those files and makes the
|
||||||
|
// app's entries say the same thing.
|
||||||
|
//
|
||||||
|
// **Which entries are the mesh's.** Never a guess from what an entry looks like:
|
||||||
|
// - a download client is the mesh's when its name is the one the module's settings give for
|
||||||
|
// that provision (`downloads.<provision>.name`) and its kind is that provider's. On a fresh
|
||||||
|
// machine the step registers it under that name; on a migrated one the assignment names the
|
||||||
|
// entry the migration adopts ("NZBGet" on ace).
|
||||||
|
// - a Torznab indexer is the mesh's when it reads a jackett feed
|
||||||
|
// (`…/api/v2.0/indexers/<id>/results/torznab`) on a host the mesh put there — the bound `at`,
|
||||||
|
// one it bound before (remembered by the step), or one the settings adopt
|
||||||
|
// (`downloads.jackett-api.adopt-hosts`, which is how a migration names the entries that pointed
|
||||||
|
// at the old container). `downloads.jackett-api.indexers` lists the jackett indexers the app
|
||||||
|
// should have; one missing is registered.
|
||||||
|
// Everything else — every entry a person made, an nzbget elsewhere, a seedbox's jackett, a Newznab
|
||||||
|
// indexer — is left exactly as it is. **Nothing is ever deleted.**
|
||||||
|
//
|
||||||
|
// **Only the connection, and only when it differs.** Host, port, TLS, base path, user name and
|
||||||
|
// the credential. Categories, priorities, "enabled", seed criteria and every other choice made in
|
||||||
|
// the app are left alone. The stored credential cannot be read back (the app masks it), so the
|
||||||
|
// step asks the app to test the entry with the mesh's host and port and the credential it already
|
||||||
|
// holds: passing, the credential is already the provider's one and only; failing, the delivered
|
||||||
|
// credential is written.
|
||||||
|
//
|
||||||
|
// **A credential the provider refuses is never written.** Until the operator accepts the
|
||||||
|
// provider's secret for this pair, the mesh delivers a value it minted itself, which no provider
|
||||||
|
// will ever accept (novox/hq ADR 0092). Writing it would replace a working password with a dead
|
||||||
|
// one. So it is tried against the provider first; refused, nothing of that provision is written
|
||||||
|
// and the step fails naming the `secret accept` that fixes it.
|
||||||
|
//
|
||||||
|
// Pure logic and a small HTTP seam, so it is tested against fake servers (test/downloads.test.ts).
|
||||||
|
// Never prints a credential, an API key, or a URL carrying one.
|
||||||
|
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
|
||||||
|
/** A download-client provision and the shape of its entry in the app. */
|
||||||
|
export interface ClientKind {
|
||||||
|
provision: "nzbget-api" | "qbittorrent-api";
|
||||||
|
/** The app's `implementation` for it. */
|
||||||
|
implementation: "Nzbget" | "QBittorrent";
|
||||||
|
/** The provider, as a person calls it. */
|
||||||
|
provider: string;
|
||||||
|
/** What the pair credential is, in the provider's words. */
|
||||||
|
secretName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CLIENTS: readonly ClientKind[] = [
|
||||||
|
{ provision: "nzbget-api", implementation: "Nzbget", provider: "nzbget", secretName: "ControlPassword" },
|
||||||
|
{ provision: "qbittorrent-api", implementation: "QBittorrent", provider: "qBittorrent", secretName: "WebUI password" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const JACKETT = "jackett-api";
|
||||||
|
|
||||||
|
/** What the mesh wrote at `binds.<provision>`: the binding document. */
|
||||||
|
export interface Binding {
|
||||||
|
provision?: string;
|
||||||
|
from?: string;
|
||||||
|
at?: string;
|
||||||
|
as?: string;
|
||||||
|
serves?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a provider is, as the mesh bound it, and the credential for it. */
|
||||||
|
export interface Endpoint {
|
||||||
|
scheme: "http" | "https";
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
/** "" at the root, otherwise "/base" — one leading slash, none trailing. */
|
||||||
|
urlBase: string;
|
||||||
|
/** The user a download client logs in as; "" for jackett, which takes a key. */
|
||||||
|
username: string;
|
||||||
|
credential: string;
|
||||||
|
/** The provider's node, for the `secret accept` remedy. */
|
||||||
|
from: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Wanted = { ok: true; endpoint: Endpoint } | { ok: false; problem: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The endpoint the mesh says to use, from a binding and its pair credential.
|
||||||
|
*
|
||||||
|
* Refused rather than guessed when the binding cannot be dialled from the app's own container: a
|
||||||
|
* loopback `at` — what the mesh hands a machine that is not on the private network — is the app's
|
||||||
|
* container itself.
|
||||||
|
*/
|
||||||
|
export function wanted(
|
||||||
|
provision: string,
|
||||||
|
binding: Binding | undefined,
|
||||||
|
credential: string | undefined,
|
||||||
|
needsUser: boolean,
|
||||||
|
): Wanted {
|
||||||
|
if (!binding) {
|
||||||
|
return { ok: false, problem: `no binding for ${provision} was delivered — the mesh writes it before this step runs` };
|
||||||
|
}
|
||||||
|
const host = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||||
|
const serves = binding.serves ?? {};
|
||||||
|
const port = Number(serves.port);
|
||||||
|
if (!host) return { ok: false, problem: `the ${provision} binding names no host (at)` };
|
||||||
|
if (isLoopback(host)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
problem:
|
||||||
|
`the ${provision} binding says the provider is at ${host}, which from the app's own container is the ` +
|
||||||
|
`app itself. The mesh hands loopback to a machine that is not on the private network; put it on the ` +
|
||||||
|
`private network so the provider has an address the app can dial`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves no usable port (${String(serves.port)})` };
|
||||||
|
}
|
||||||
|
const scheme = typeof serves.scheme === "string" && serves.scheme ? serves.scheme : "http";
|
||||||
|
if (scheme !== "http" && scheme !== "https") {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves scheme ${scheme}, which the app cannot dial` };
|
||||||
|
}
|
||||||
|
const username = typeof serves.username === "string" ? serves.username.trim() : "";
|
||||||
|
if (needsUser && !username) {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves no username for the app to log in as` };
|
||||||
|
}
|
||||||
|
const key = (credential ?? "").trim();
|
||||||
|
if (!key) return { ok: false, problem: `the ${provision} credential is empty or was not delivered` };
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
endpoint: {
|
||||||
|
scheme,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
urlBase: normBase(serves["url-base"]),
|
||||||
|
username,
|
||||||
|
credential: key,
|
||||||
|
from: typeof binding.from === "string" ? binding.from : "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A URL base as "" or "/x/y": slashes trimmed, one put back in front. */
|
||||||
|
export function normBase(v: unknown): string {
|
||||||
|
const s = typeof v === "string" ? v.trim().replace(/^\/+|\/+$/g, "") : "";
|
||||||
|
return s === "" ? "" : `/${s}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLoopback(host: string): boolean {
|
||||||
|
const h = host.toLowerCase();
|
||||||
|
return h === "localhost" || h === "::1" || h === "[::1]" || /^127\./.test(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hostForUrl(host: string): string {
|
||||||
|
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The provider's base URL, as the step dials it and as the app is given it. */
|
||||||
|
export function baseUrl(ep: Endpoint): string {
|
||||||
|
return `${ep.scheme}://${hostForUrl(ep.host)}:${ep.port}${ep.urlBase}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// HTTP
|
||||||
|
|
||||||
|
/** The HTTP the step needs, so a test can stand fakes in for the app and the providers. */
|
||||||
|
export interface Http {
|
||||||
|
fetch(
|
||||||
|
url: string,
|
||||||
|
init?: { method?: string; headers?: Record<string, string>; body?: string },
|
||||||
|
): Promise<{ status: number; text(): Promise<string> }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app, as the step reaches it from the host. */
|
||||||
|
export interface App {
|
||||||
|
/** The module, for messages and the remedy: sonarr, radarr, lidarr, bookshelf. */
|
||||||
|
module: string;
|
||||||
|
/** Its own URL, base path included. */
|
||||||
|
url: string;
|
||||||
|
apiKey: string;
|
||||||
|
/** v3 (sonarr, radarr) or v1 (lidarr, bookshelf). */
|
||||||
|
api: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Answer {
|
||||||
|
status: number;
|
||||||
|
body: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function appCall(http: Http, app: App, method: string, path: string, body?: unknown): Promise<Answer> {
|
||||||
|
const res = await http.fetch(`${app.url.replace(/\/$/, "")}/api/${app.api}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
"X-Api-Key": app.apiKey,
|
||||||
|
Accept: "application/json",
|
||||||
|
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||||
|
},
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
let parsed: unknown = undefined;
|
||||||
|
if (text) {
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(text) as unknown;
|
||||||
|
} catch {
|
||||||
|
parsed = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { status: res.status, body: parsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function appGet(http: Http, app: App, path: string): Promise<unknown> {
|
||||||
|
const a = await appCall(http, app, "GET", path);
|
||||||
|
if (a.status < 200 || a.status >= 300) throw new Error(`${app.module} GET ${path} answered ${a.status}`);
|
||||||
|
return a.body;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One of the app's validation failures: the only parts of an answer the step ever prints. */
|
||||||
|
interface Failure {
|
||||||
|
property: string;
|
||||||
|
message: string;
|
||||||
|
warning: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function failuresOf(body: unknown): Failure[] {
|
||||||
|
const list = Array.isArray(body) ? body : [];
|
||||||
|
return list.map((f) => {
|
||||||
|
const o = (f ?? {}) as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
property: String(o.propertyName ?? ""),
|
||||||
|
message: String(o.errorMessage ?? ""),
|
||||||
|
warning: o.isWarning === true,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One shape rather than a union on `ok`: the Dockerfile compiles without strict, where a boolean
|
||||||
|
* discriminant does not narrow.
|
||||||
|
*/
|
||||||
|
interface Verdict {
|
||||||
|
ok: boolean;
|
||||||
|
/** Warnings the app raised on a pass; errors (and any warnings) on a failure. */
|
||||||
|
failures: Failure[];
|
||||||
|
status: number;
|
||||||
|
saved?: Entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function verdict(a: Answer): Verdict {
|
||||||
|
if (a.status >= 200 && a.status < 300) return { ok: true, failures: [], status: a.status };
|
||||||
|
const failures = failuresOf(a.body);
|
||||||
|
if (a.status === 400 && failures.length > 0 && failures.every((f) => f.warning)) return { ok: true, failures, status: a.status };
|
||||||
|
return { ok: false, failures, status: a.status };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's own test of an entry, from the app's own container. */
|
||||||
|
async function appTest(http: Http, app: App, resource: string, entry: Entry): Promise<Verdict> {
|
||||||
|
return verdict(await appCall(http, app, "POST", `/${resource}/test`, entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save an entry. The app tests an enabled entry before saving it; a test that passes with only
|
||||||
|
* warnings ("a category is recommended") is saved with `forceSave`, the same as pressing "save
|
||||||
|
* anyway" in its screen. An error is never forced.
|
||||||
|
*/
|
||||||
|
async function appSave(http: Http, app: App, resource: string, entry: Entry, create: boolean): Promise<Verdict> {
|
||||||
|
const path = create ? `/${resource}` : `/${resource}/${entry.id}`;
|
||||||
|
const method = create ? "POST" : "PUT";
|
||||||
|
let a = await appCall(http, app, method, path, entry);
|
||||||
|
let v = verdict(a);
|
||||||
|
if (v.ok && (a.status < 200 || a.status >= 300)) {
|
||||||
|
a = await appCall(http, app, method, `${path}?forceSave=true`, entry);
|
||||||
|
v = verdict(a);
|
||||||
|
if (v.ok && (a.status < 200 || a.status >= 300)) {
|
||||||
|
return { ok: false, failures: failuresOf(a.body), status: a.status };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!v.ok) return v;
|
||||||
|
return { ...v, saved: (a.body ?? undefined) as Entry | undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Entries
|
||||||
|
|
||||||
|
/** An entry as the app's API gives it: a download client or an indexer. */
|
||||||
|
export interface Entry {
|
||||||
|
id?: number;
|
||||||
|
name?: string;
|
||||||
|
implementation?: string;
|
||||||
|
enable?: boolean;
|
||||||
|
enableRss?: boolean;
|
||||||
|
enableAutomaticSearch?: boolean;
|
||||||
|
enableInteractiveSearch?: boolean;
|
||||||
|
supportsRss?: boolean;
|
||||||
|
supportsSearch?: boolean;
|
||||||
|
fields?: { name: string; value?: unknown; [k: string]: unknown }[];
|
||||||
|
[k: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function field(e: Entry, name: string): unknown {
|
||||||
|
return e.fields?.find((f) => f.name === name)?.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The entry with these fields' values replaced — added when the app's shape lacks one. */
|
||||||
|
export function withFields(e: Entry, values: Record<string, unknown>): Entry {
|
||||||
|
const fields = (e.fields ?? []).map((f) => (f.name in values ? { ...f, value: values[f.name] } : { ...f }));
|
||||||
|
for (const [name, value] of Object.entries(values)) {
|
||||||
|
if (!fields.some((f) => f.name === name)) fields.push({ name, value });
|
||||||
|
}
|
||||||
|
return { ...e, fields };
|
||||||
|
}
|
||||||
|
|
||||||
|
function enabled(e: Entry): boolean {
|
||||||
|
return e.enable === true || e.enableRss === true || e.enableAutomaticSearch === true || e.enableInteractiveSearch === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What one provision, or one entry of it, came to. */
|
||||||
|
export type Outcome =
|
||||||
|
| { what: string; result: "unchanged"; untested?: boolean }
|
||||||
|
| { what: string; result: "written"; fields: string[]; untested?: boolean }
|
||||||
|
| { what: string; result: "created"; fields: string[] }
|
||||||
|
| { what: string; result: "notice"; note: string }
|
||||||
|
| { what: string; result: "refused"; problem: string };
|
||||||
|
|
||||||
|
function said(fs: Failure[]): string {
|
||||||
|
return fs.length === 0 ? "no reason given" : fs.map((f) => (f.property ? `${f.property}: ${f.message}` : f.message)).join("; ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring one of the mesh's entries in line: `connection` is the non-secret fields as the mesh says
|
||||||
|
* them, `differs` which of them the entry does not already say, `secretField` where the credential
|
||||||
|
* goes. Never throws: every failure is an outcome with a reason.
|
||||||
|
*/
|
||||||
|
export async function reconcileEntry(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
resource: "downloadclient" | "indexer",
|
||||||
|
what: string,
|
||||||
|
current: Entry,
|
||||||
|
connection: Record<string, unknown>,
|
||||||
|
differs: string[],
|
||||||
|
secretField: string,
|
||||||
|
credential: string,
|
||||||
|
testable = true,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
try {
|
||||||
|
const base = withFields(current, connection); // the credential as the app holds it — masked
|
||||||
|
if (!testable) {
|
||||||
|
// Nothing to test against (jackett no longer has the indexer it names): the connection is
|
||||||
|
// still the mesh's to state, and the key goes with it when the address changes.
|
||||||
|
if (differs.length === 0) return { what, result: "unchanged", untested: true };
|
||||||
|
const s = await appSave(http, app, resource, withFields(base, { [secretField]: credential }), false);
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not save it: ${said(s.failures)}` };
|
||||||
|
return { what, result: "written", fields: [...differs, secretField], untested: true };
|
||||||
|
}
|
||||||
|
const first = await appTest(http, app, resource, base);
|
||||||
|
if (first.ok) {
|
||||||
|
// The credential the app holds already works against the provider at the mesh's address —
|
||||||
|
// and the provider has exactly one, so it is the delivered one.
|
||||||
|
if (differs.length === 0) return { what, result: "unchanged" };
|
||||||
|
const s = await appSave(http, app, resource, base, false);
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not save it: ${said(s.failures)}` };
|
||||||
|
return { what, result: "written", fields: differs };
|
||||||
|
}
|
||||||
|
// The app's test failed with what it holds. The delivered credential was already checked
|
||||||
|
// against the provider, so writing it is safe; the app tests an enabled entry again on save.
|
||||||
|
const s = await appSave(http, app, resource, withFields(base, { [secretField]: credential }), false);
|
||||||
|
if (!s.ok) {
|
||||||
|
return {
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${app.module} tested it at the mesh's address and would not save it (nothing was written): ${said(s.failures)}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const stored = (await appGet(http, app, `/${resource}/${current.id}`)) as Entry;
|
||||||
|
const second = await appTest(http, app, resource, stored);
|
||||||
|
const fields = [...differs, secretField];
|
||||||
|
if (second.ok) return { what, result: "written", fields };
|
||||||
|
const why = `written (${fields.join(", ")}), and ${app.module}'s own test still fails: ${said(second.failures)}`;
|
||||||
|
return enabled(stored) ? { what, result: "refused", problem: why } : { what, result: "notice", note: `${why} — it is disabled, so nothing uses it` };
|
||||||
|
} catch (err) {
|
||||||
|
return { what, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a new entry from the app's own template for that kind: its defaults, the name, the
|
||||||
|
* connection and the credential. A category the provider does not have (nzbget refuses one it was
|
||||||
|
* not told about) is left empty rather than failing the registration, and said.
|
||||||
|
*/
|
||||||
|
export async function createEntry(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
resource: "downloadclient" | "indexer",
|
||||||
|
what: string,
|
||||||
|
implementation: string,
|
||||||
|
name: string,
|
||||||
|
values: Record<string, unknown>,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
try {
|
||||||
|
const schema = (await appGet(http, app, `/${resource}/schema`)) as Entry[];
|
||||||
|
const template = (schema ?? []).find((s) => s.implementation === implementation);
|
||||||
|
if (!template) return { what, result: "refused", problem: `${app.module} has no ${implementation} to register` };
|
||||||
|
let entry: Entry = withFields({ ...template, id: undefined, name }, values);
|
||||||
|
if (resource === "downloadclient") entry.enable = true;
|
||||||
|
else {
|
||||||
|
entry.enableRss = template.supportsRss !== false;
|
||||||
|
entry.enableAutomaticSearch = template.supportsSearch !== false;
|
||||||
|
entry.enableInteractiveSearch = template.supportsSearch !== false;
|
||||||
|
}
|
||||||
|
let s = await appSave(http, app, resource, entry, true);
|
||||||
|
let note = "";
|
||||||
|
if (!s.ok && s.failures.length > 0 && s.failures.every((f) => /category/i.test(f.property))) {
|
||||||
|
const emptied: Record<string, unknown> = {};
|
||||||
|
for (const f of entry.fields ?? []) if (/category$/i.test(f.name) && !/imported/i.test(f.name)) emptied[f.name] = "";
|
||||||
|
entry = withFields(entry, emptied);
|
||||||
|
s = await appSave(http, app, resource, entry, true);
|
||||||
|
note = " with its category left empty — the provider has none by the app's default name; set one in both";
|
||||||
|
}
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not register it: ${said(s.failures)}` };
|
||||||
|
const created = s.saved;
|
||||||
|
if (created?.id !== undefined) {
|
||||||
|
const t = await appTest(http, app, resource, (await appGet(http, app, `/${resource}/${created.id}`)) as Entry);
|
||||||
|
if (!t.ok) {
|
||||||
|
return { what, result: "refused", problem: `registered as "${name}"${note}, and ${app.module}'s own test fails: ${said(t.failures)}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return note
|
||||||
|
? { what, result: "notice", note: `registered as "${name}"${note}` }
|
||||||
|
: { what, result: "created", fields: Object.keys(values) };
|
||||||
|
} catch (err) {
|
||||||
|
return { what, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Providers: does it take the credential?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does the provider take this credential? `took` it does (for jackett, with the ids of the indexers
|
||||||
|
* it has configured); `refused` it said no; a thrown error when it could not be asked.
|
||||||
|
*/
|
||||||
|
export interface Took {
|
||||||
|
took: boolean;
|
||||||
|
configured?: Map<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function providerTakes(http: Http, provision: string, ep: Endpoint): Promise<Took> {
|
||||||
|
const base = baseUrl(ep);
|
||||||
|
if (provision === "nzbget-api") {
|
||||||
|
const auth = Buffer.from(`${ep.username}:${ep.credential}`).toString("base64");
|
||||||
|
const res = await http.fetch(`${base}/jsonrpc/version`, { method: "GET", headers: { Authorization: `Basic ${auth}` } });
|
||||||
|
await res.text();
|
||||||
|
if (res.status === 401 || res.status === 403) return { took: false };
|
||||||
|
if (res.status >= 200 && res.status < 300) return { took: true };
|
||||||
|
throw new Error(`nzbget answered ${res.status}`);
|
||||||
|
}
|
||||||
|
if (provision === "qbittorrent-api") {
|
||||||
|
const form = `username=${encodeURIComponent(ep.username)}&password=${encodeURIComponent(ep.credential)}`;
|
||||||
|
const res = await http.fetch(`${base}/api/v2/auth/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: form,
|
||||||
|
});
|
||||||
|
const text = (await res.text()).trim();
|
||||||
|
if (res.status === 401 || /^fails\.?$/i.test(text)) return { took: false };
|
||||||
|
if (res.status === 403) {
|
||||||
|
throw new Error(
|
||||||
|
"qBittorrent answered 403: it has banned this address after failed logins (WebUI\\BanDuration); it lifts by itself",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (res.status >= 200 && res.status < 300) return { took: true };
|
||||||
|
throw new Error(`qBittorrent answered ${res.status}`);
|
||||||
|
}
|
||||||
|
if (provision === JACKETT) {
|
||||||
|
const url = `${base}/api/v2.0/indexers/all/results/torznab/api?t=indexers&configured=true&apikey=${encodeURIComponent(ep.credential)}`;
|
||||||
|
const res = await http.fetch(url, { method: "GET" });
|
||||||
|
const text = await res.text();
|
||||||
|
if (res.status === 401 || res.status === 403) return { took: false };
|
||||||
|
if (res.status < 200 || res.status >= 300) throw new Error(`jackett answered ${res.status}`);
|
||||||
|
// jackett answers a wrong key 200 with an error document: code 100, "Invalid API Key".
|
||||||
|
if (/<error\b[^>]*\bcode="100"/i.test(text)) return { took: false };
|
||||||
|
if (/<error\b/i.test(text)) throw new Error("jackett answered with an error document");
|
||||||
|
return { took: true, configured: configuredIndexers(text) };
|
||||||
|
}
|
||||||
|
throw new Error(`no check for ${provision}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** jackett's configured indexers, id → title, from its `t=indexers` feed. */
|
||||||
|
export function configuredIndexers(xml: string): Map<string, string> {
|
||||||
|
const out = new Map<string, string>();
|
||||||
|
const re = /<indexer\b[^>]*\bid="([^"]+)"[^>]*>([\s\S]*?)<\/indexer>/g;
|
||||||
|
for (let m = re.exec(xml); m; m = re.exec(xml)) {
|
||||||
|
const title = /<title>([\s\S]*?)<\/title>/.exec(m[2])?.[1]?.trim() ?? m[1];
|
||||||
|
out.set(m[1], decodeXml(title));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeXml(s: string): string {
|
||||||
|
return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The remedy for a refused credential, in the controller's own words (ADR 0092). */
|
||||||
|
export function acceptRemedy(app: App, node: string, provision: string, provider: string, secretName: string, from: string): string {
|
||||||
|
return (
|
||||||
|
`${provider} refuses the ${provision} credential the mesh delivered, so nothing of ${provision} was written ` +
|
||||||
|
`into ${app.module}. ${provider} has one ${secretName} and the mesh cannot make it: accept it for this pair — ` +
|
||||||
|
`\`secret accept ${node || "<this node>"} ${app.module} ${provision} --provider ${from || "<its node>"} ` +
|
||||||
|
`--from <file holding ${provider}'s ${secretName}>\``
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Download clients
|
||||||
|
|
||||||
|
/** The non-secret fields of a download client as the mesh says them. */
|
||||||
|
export function clientConnection(ep: Endpoint): Record<string, unknown> {
|
||||||
|
return { host: ep.host, port: ep.port, useSsl: ep.scheme === "https", urlBase: ep.urlBase === "" ? null : ep.urlBase, username: ep.username };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which of them the entry does not already say. Names only. */
|
||||||
|
export function clientDiffers(e: Entry, ep: Endpoint): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
if (String(field(e, "host") ?? "").toLowerCase() !== ep.host.toLowerCase()) out.push("host");
|
||||||
|
if (Number(field(e, "port") ?? 0) !== ep.port) out.push("port");
|
||||||
|
if (Boolean(field(e, "useSsl")) !== (ep.scheme === "https")) out.push("useSsl");
|
||||||
|
if (normBase(field(e, "urlBase")) !== ep.urlBase) out.push("urlBase");
|
||||||
|
if (String(field(e, "username") ?? "") !== ep.username) out.push("username");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the app's download client for one provision in line: the entry by that name and kind is
|
||||||
|
* the mesh's and is updated; none, it is registered. An entry by that name of another kind, or by
|
||||||
|
* that name in another case, is somebody else's and is refused rather than touched.
|
||||||
|
*/
|
||||||
|
export async function reconcileClient(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
kind: ClientKind,
|
||||||
|
name: string,
|
||||||
|
ep: Endpoint,
|
||||||
|
entries: Entry[],
|
||||||
|
): Promise<Outcome[]> {
|
||||||
|
const what = `${kind.provision} ("${name}")`;
|
||||||
|
const exact = entries.filter((e) => e.name === name);
|
||||||
|
const alike = entries.filter((e) => e.name !== name && String(e.name ?? "").toLowerCase() === name.toLowerCase());
|
||||||
|
if (exact.length > 0 && exact[0].implementation !== kind.implementation) {
|
||||||
|
return [{
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `the download client named "${name}" is a ${exact[0].implementation}, not ${kind.implementation}; it is not the mesh's and was left alone. Name the mesh's entry otherwise in downloads.${kind.provision}.name`,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
if (exact.length === 0 && alike.length > 0) {
|
||||||
|
return [{
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${app.module} already has "${alike[0].name}", which is not the mesh's name ("${name}") and was left alone. To have the mesh manage it, set downloads.${kind.provision}.name to "${alike[0].name}"`,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
const others = entries.filter((e) => e.implementation === kind.implementation && e.name !== name);
|
||||||
|
if (others.length > 0) {
|
||||||
|
outcomes.push({
|
||||||
|
what,
|
||||||
|
result: "notice",
|
||||||
|
note: `also present and not the mesh's, left alone: ${others.map((o) => `"${o.name}"`).join(", ")}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (exact.length === 0) {
|
||||||
|
outcomes.push(
|
||||||
|
await createEntry(http, app, "downloadclient", what, kind.implementation, name, {
|
||||||
|
...clientConnection(ep),
|
||||||
|
password: ep.credential,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
outcomes.push(
|
||||||
|
await reconcileEntry(http, app, "downloadclient", what, exact[0], clientConnection(ep), clientDiffers(exact[0], ep), "password", ep.credential),
|
||||||
|
);
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Indexers
|
||||||
|
|
||||||
|
const FEED = /\/api\/v2\.0\/indexers\/([^/]+)\/results\/torznab\/?$/;
|
||||||
|
|
||||||
|
/** A Torznab entry reading a jackett feed: the host it points at and the jackett indexer's id. */
|
||||||
|
export function jackettFeed(e: Entry): { host: string; id: string } | undefined {
|
||||||
|
if (e.implementation !== "Torznab") return undefined;
|
||||||
|
const raw = String(field(e, "baseUrl") ?? "").trim();
|
||||||
|
if (!raw) return undefined;
|
||||||
|
let u: URL;
|
||||||
|
try {
|
||||||
|
u = new URL(raw);
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const path = `${u.pathname.replace(/\/+$/, "")}/${String(field(e, "apiPath") ?? "").replace(/^\/+/, "")}`;
|
||||||
|
const m = FEED.exec(path);
|
||||||
|
if (!m) return undefined;
|
||||||
|
return { host: u.hostname.replace(/^\[|\]$/g, "").toLowerCase(), id: decodeURIComponent(m[1]) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The feed's two fields as the mesh says them. */
|
||||||
|
export function feedConnection(ep: Endpoint, id: string): Record<string, unknown> {
|
||||||
|
return { baseUrl: baseUrl(ep), apiPath: `/api/v2.0/indexers/${id}/results/torznab/` };
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameUrl(a: string, b: string): boolean {
|
||||||
|
try {
|
||||||
|
const x = new URL(a);
|
||||||
|
const y = new URL(b);
|
||||||
|
const port = (u: URL) => u.port || (u.protocol === "https:" ? "443" : "80");
|
||||||
|
return (
|
||||||
|
x.protocol === y.protocol &&
|
||||||
|
x.hostname.toLowerCase() === y.hostname.toLowerCase() &&
|
||||||
|
port(x) === port(y) &&
|
||||||
|
x.pathname.replace(/\/+$/, "") === y.pathname.replace(/\/+$/, "")
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedDiffers(e: Entry, ep: Endpoint, id: string): string[] {
|
||||||
|
const want = feedConnection(ep, id);
|
||||||
|
const out: string[] = [];
|
||||||
|
if (!sameUrl(String(field(e, "baseUrl") ?? ""), String(want.baseUrl))) out.push("baseUrl");
|
||||||
|
const path = (v: unknown) => `/${String(v ?? "").replace(/^\/+|\/+$/g, "")}`;
|
||||||
|
if (path(field(e, "apiPath")) !== path(want.apiPath)) out.push("apiPath");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IndexerSettings {
|
||||||
|
/** Hosts whose jackett feeds the mesh takes over — a migration's old names. */
|
||||||
|
adoptHosts: string[];
|
||||||
|
/** jackett indexer ids the app should have. */
|
||||||
|
indexers: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the app's jackett feeds in line: every one the mesh manages is pointed at the bound jackett
|
||||||
|
* with its key, and every listed jackett indexer the app lacks is registered.
|
||||||
|
*/
|
||||||
|
export async function reconcileIndexers(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
ep: Endpoint,
|
||||||
|
configured: Map<string, string>,
|
||||||
|
settings: IndexerSettings,
|
||||||
|
remembered: string[],
|
||||||
|
entries: Entry[],
|
||||||
|
): Promise<Outcome[]> {
|
||||||
|
const ours = new Set([ep.host, ...settings.adoptHosts, ...remembered].map((h) => h.trim().toLowerCase()).filter(Boolean));
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
const managed = new Set<string>();
|
||||||
|
for (const e of entries) {
|
||||||
|
const feed = jackettFeed(e);
|
||||||
|
if (!feed || !ours.has(feed.host)) continue;
|
||||||
|
managed.add(feed.id);
|
||||||
|
const what = `jackett-api ("${e.name}", jackett indexer ${feed.id})`;
|
||||||
|
const known = feed.id === "all" || configured.has(feed.id);
|
||||||
|
const outcome = await reconcileEntry(
|
||||||
|
http, app, "indexer", what, e, feedConnection(ep, feed.id), feedDiffers(e, ep, feed.id), "apiKey", ep.credential, known,
|
||||||
|
);
|
||||||
|
outcomes.push(outcome);
|
||||||
|
if (!known && outcome.result !== "refused") {
|
||||||
|
outcomes.push({ what, result: "notice", note: `jackett has no indexer "${feed.id}" configured, so it was not tested; configure it in jackett or remove the entry in ${app.module}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const id of settings.indexers) {
|
||||||
|
if (managed.has(id)) continue;
|
||||||
|
const what = `jackett-api (jackett indexer ${id})`;
|
||||||
|
if (id !== "all" && !configured.has(id)) {
|
||||||
|
outcomes.push({ what, result: "refused", problem: `downloads.jackett-api.indexers lists "${id}", and jackett has no indexer by that id configured` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const name = `Jackett - ${id === "all" ? "all" : configured.get(id)}`;
|
||||||
|
outcomes.push(await createEntry(http, app, "indexer", what, "Torznab", name, { ...feedConnection(ep, id), apiKey: ep.credential }));
|
||||||
|
}
|
||||||
|
if (outcomes.length === 0) {
|
||||||
|
outcomes.push({ what: "jackett-api", result: "notice", note: `${app.module} has no jackett feed the mesh manages, and downloads.jackett-api.indexers lists none to register` });
|
||||||
|
}
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Files
|
||||||
|
|
||||||
|
/** The module's settings for this step, from its merged `downloads.json`. */
|
||||||
|
export interface StepSettings {
|
||||||
|
node: string;
|
||||||
|
names: Record<string, string>;
|
||||||
|
indexers: IndexerSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stepSettings(raw: unknown): StepSettings {
|
||||||
|
const doc = (raw ?? {}) as Record<string, unknown>;
|
||||||
|
const d = (doc.downloads ?? {}) as Record<string, Record<string, unknown> | undefined>;
|
||||||
|
const names: Record<string, string> = {};
|
||||||
|
for (const k of CLIENTS) {
|
||||||
|
const n = d[k.provision]?.name;
|
||||||
|
names[k.provision] = typeof n === "string" && n.trim() ? n.trim() : k.provision.replace(/-api$/, "");
|
||||||
|
}
|
||||||
|
const j = d[JACKETT] ?? {};
|
||||||
|
const strings = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && x.trim() !== "").map((x) => x.trim()) : []);
|
||||||
|
return {
|
||||||
|
node: typeof doc.node === "string" ? doc.node : "",
|
||||||
|
names,
|
||||||
|
indexers: { adoptHosts: strings(j["adopt-hosts"]), indexers: strings(j.indexers) },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's own key and base path, from its config.xml. */
|
||||||
|
export function appConfig(xml: string): { apiKey: string; urlBase: string } {
|
||||||
|
const tag = (t: string) => new RegExp(`<${t}>([^<]*)</${t}>`).exec(xml)?.[1]?.trim() ?? "";
|
||||||
|
return { apiKey: tag("ApiKey"), urlBase: normBase(tag("UrlBase")) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A file the mesh wrote, or undefined when it is not there. */
|
||||||
|
export async function readIfThere(path: string | undefined): Promise<string | undefined> {
|
||||||
|
if (!path) return undefined;
|
||||||
|
return readFile(path, "utf8").catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A JSON file parsed, or undefined when absent or not JSON. */
|
||||||
|
export async function readJson(path: string | undefined): Promise<unknown> {
|
||||||
|
const raw = await readIfThere(path);
|
||||||
|
if (raw === undefined) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as unknown;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait for the app to answer, because the step runs right after its container starts. */
|
||||||
|
export async function appReady(http: Http, app: App, waitMs: number, pauseMs = 2000): Promise<boolean> {
|
||||||
|
const until = Date.now() + waitMs;
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
const a = await appCall(http, app, "GET", "/system/status");
|
||||||
|
if (a.status === 200) return true;
|
||||||
|
} catch {
|
||||||
|
// not listening yet
|
||||||
|
}
|
||||||
|
if (Date.now() >= until) return false;
|
||||||
|
await new Promise((r) => setTimeout(r, pauseMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listEntries(http: Http, app: App, resource: "downloadclient" | "indexer"): Promise<Entry[]> {
|
||||||
|
return ((await appGet(http, app, `/${resource}`)) as Entry[]) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Anything printed goes through this: the credentials the step holds never reach a log. */
|
||||||
|
export function scrub(text: string, secrets: string[]): string {
|
||||||
|
let out = text;
|
||||||
|
for (const s of secrets) if (s && s.length >= 4) out = out.split(s).join("<redacted>");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(err: unknown): string {
|
||||||
|
return err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
// lidarr's events. The tool runtime imports this once the broker is bound. It watches the download
|
||||||
|
// queue and turns its comings and goings into mesh events.
|
||||||
|
//
|
||||||
|
// Emits (novox/hq ADR 0041/0042):
|
||||||
|
// module.lidarr.album.grabbed — a release entered the queue (Lidarr grabbed it)
|
||||||
|
// module.lidarr.download.completed — a release left the queue, imported. The download.completed
|
||||||
|
// routing key matches what a media consumer subscribes to
|
||||||
|
// (module.*.download.completed) to rescan its library.
|
||||||
|
// Consumes: none.
|
||||||
|
//
|
||||||
|
// The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a
|
||||||
|
// restart mid-download does not re-announce everything already in flight as freshly grabbed.
|
||||||
|
|
||||||
|
import { emit } from "@novox/mesh-sdk/events";
|
||||||
|
import { LidarrClient, type LidarrQueueItem } from "./client.js";
|
||||||
|
|
||||||
|
// Building the client throws when Lidarr has no URL/key yet. Like the tools (see tools/index.ts),
|
||||||
|
// the events entrypoint must not crash the runtime for that — it stays idle until configured.
|
||||||
|
function buildClient(): LidarrClient | null {
|
||||||
|
try {
|
||||||
|
return LidarrClient.fromEnv();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const lidarr = buildClient();
|
||||||
|
|
||||||
|
// Lidarr removes an item from the queue once it has been imported; a "warning"/"failed" status is
|
||||||
|
// how a stuck or broken grab shows itself, so we do not call those a completion when they vanish.
|
||||||
|
const FAILED_STATUSES = new Set(["failed", "warning"]);
|
||||||
|
|
||||||
|
const inQueue = new Map<number, LidarrQueueItem>();
|
||||||
|
let primed = false;
|
||||||
|
|
||||||
|
async function pollQueue(lidarr: LidarrClient): Promise<void> {
|
||||||
|
const { items } = await lidarr.getQueue();
|
||||||
|
const now = new Map(items.map((i) => [i.id, i]));
|
||||||
|
|
||||||
|
if (primed) {
|
||||||
|
// Entered the queue since last look — Lidarr grabbed a release.
|
||||||
|
for (const [id, item] of now) {
|
||||||
|
if (!inQueue.has(id)) await emit("album.grabbed", { title: item.title, status: item.status });
|
||||||
|
}
|
||||||
|
// Left the queue — imported and done, unless it was last seen failing.
|
||||||
|
for (const [id, item] of inQueue) {
|
||||||
|
if (!now.has(id) && !FAILED_STATUSES.has(item.status)) {
|
||||||
|
await emit("download.completed", { title: item.title });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inQueue.clear();
|
||||||
|
for (const [id, item] of now) inQueue.set(id, item);
|
||||||
|
primed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||||
|
const run = (): void => void fn().catch((err) => console.error(`[lidarr] ${err}`));
|
||||||
|
setInterval(run, everyMs);
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (lidarr) {
|
||||||
|
tick(() => pollQueue(lidarr), 30_000);
|
||||||
|
console.log("[lidarr] watching the download queue, emitting grabs and completions");
|
||||||
|
} else {
|
||||||
|
console.log("[lidarr] not configured — events idle until an API key is available");
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
{
|
||||||
|
"module": "lidarr",
|
||||||
|
"version": "1",
|
||||||
|
"provides": [
|
||||||
|
{
|
||||||
|
"name": "lidarr-api",
|
||||||
|
"scope": "mesh"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"serves": {
|
||||||
|
"lidarr-api": {
|
||||||
|
"scheme": "http",
|
||||||
|
"port": 8686,
|
||||||
|
"url-base": ""
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"album.grabbed",
|
||||||
|
"download.completed"
|
||||||
|
],
|
||||||
|
"consumes": [],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/lidarr/broker"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 8686,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "managing music"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accesses": [
|
||||||
|
{
|
||||||
|
"path": "/services/media/music",
|
||||||
|
"mode": "read-write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/downloads",
|
||||||
|
"mode": "read-write"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/lidarr",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "custom-cont-init",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0755"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "custom-services",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0755"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "lidarr",
|
||||||
|
"image": "lscr.io/linuxserver/lidarr@sha256:8ab0fd370b604ae034d9a9c261a9d8d873bece33d9736852e7ce4f3566e4a35d",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC"
|
||||||
|
},
|
||||||
|
"ports": [
|
||||||
|
"8686"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"${dir:custom-cont-init}:/custom-cont-init.d",
|
||||||
|
"${dir:custom-services}:/custom-services.d",
|
||||||
|
"/services/media/music:/music",
|
||||||
|
"/services/media/downloads:/downloads"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-lidarr",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/lidarr/broker:/run/secrets/broker:ro",
|
||||||
|
"${dir:config}:/var/lib/lidarr/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_LIDARR_URL": "http://127.0.0.1:${port:8686}",
|
||||||
|
"MESH_LIDARR_CONFIG_DIR": "/var/lib/lidarr/config"
|
||||||
|
},
|
||||||
|
"artifact": "runtime"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/downloads.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{\n \"node\": \"${machine:name}\",\n \"downloads\": {\n \"nzbget-api\": {\n \"name\": \"nzbget\"\n },\n \"qbittorrent-api\": {\n \"name\": \"qbittorrent\"\n },\n \"jackett-api\": {\n \"adopt-hosts\": [],\n \"indexers\": []\n }\n }\n}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads-memory",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-lidarr-downloads",
|
||||||
|
"network": "host",
|
||||||
|
"run-once": true,
|
||||||
|
"volumes": [
|
||||||
|
"${dir:state}/downloads.json:/run/downloads/downloads.json:ro",
|
||||||
|
"${dir:state}/nzbget-api.json:/run/downloads/nzbget-api.json:ro",
|
||||||
|
"${dir:state}/nzbget-api.secret:/run/downloads/nzbget-api.secret:ro",
|
||||||
|
"${dir:state}/qbittorrent-api.json:/run/downloads/qbittorrent-api.json:ro",
|
||||||
|
"${dir:state}/qbittorrent-api.secret:/run/downloads/qbittorrent-api.secret:ro",
|
||||||
|
"${dir:state}/jackett-api.json:/run/downloads/jackett-api.json:ro",
|
||||||
|
"${dir:state}/jackett-api.secret:/run/downloads/jackett-api.secret:ro",
|
||||||
|
"${dir:config}:/var/lib/lidarr/config:ro",
|
||||||
|
"${dir:downloads-memory}:/var/lib/downloads"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_DOWNLOADS_APP": "lidarr",
|
||||||
|
"MESH_DOWNLOADS_API": "v1",
|
||||||
|
"MESH_DOWNLOADS_APP_URL": "http://127.0.0.1:${port:8686}",
|
||||||
|
"MESH_DOWNLOADS_APP_CONFIG": "/var/lib/lidarr/config/config.xml",
|
||||||
|
"MESH_DOWNLOADS_DIR": "/run/downloads",
|
||||||
|
"MESH_DOWNLOADS_SETTINGS": "/run/downloads/downloads.json",
|
||||||
|
"MESH_DOWNLOADS_MEMORY": "/var/lib/downloads/memory.json"
|
||||||
|
},
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"/app/modules/lidarr/dist/downloads/index.js"
|
||||||
|
],
|
||||||
|
"restart-on": [
|
||||||
|
"downloads-config",
|
||||||
|
"bound-nzbget-api",
|
||||||
|
"secret-nzbget-api",
|
||||||
|
"bound-qbittorrent-api",
|
||||||
|
"secret-qbittorrent-api",
|
||||||
|
"bound-jackett-api",
|
||||||
|
"secret-jackett-api"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requires": [
|
||||||
|
"jackett-api",
|
||||||
|
"nzbget-api",
|
||||||
|
"qbittorrent-api",
|
||||||
|
"route"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "lidarr",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json",
|
||||||
|
"nzbget-api": "${dir:state}/nzbget-api.json",
|
||||||
|
"qbittorrent-api": "${dir:state}/qbittorrent-api.json",
|
||||||
|
"jackett-api": "${dir:state}/jackett-api.json"
|
||||||
|
},
|
||||||
|
"secrets": {
|
||||||
|
"nzbget-api": "${dir:state}/nzbget-api.secret",
|
||||||
|
"qbittorrent-api": "${dir:state}/qbittorrent-api.secret",
|
||||||
|
"jackett-api": "${dir:state}/jackett-api.secret"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-lidarr",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "lidarr — music management. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc client.ts index.ts tools/index.ts downloads/settings.ts downloads/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist",
|
||||||
|
"typecheck": "tsc -p tsconfig.json",
|
||||||
|
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
// What holds the downloads step (downloads/settings.ts): the app's download clients and jackett
|
||||||
|
// feeds are made to say what the mesh bound — host, port, TLS, base path, user, credential — and
|
||||||
|
// nothing else they keep is touched; only the mesh's entries are touched, and nothing is ever
|
||||||
|
// deleted; nothing is written when nothing differs; a missing one is registered; and a credential
|
||||||
|
// the provider refuses (the mesh's own minted value, before the operator accepts the provider's)
|
||||||
|
// is never written, with the `secret accept` that fixes it named.
|
||||||
|
//
|
||||||
|
// The app and the providers are fakes: the routes the step touches, answering as the real ones do
|
||||||
|
// (checked against the catalogue's pinned sonarr, radarr, lidarr, bookshelf, nzbget, qBittorrent
|
||||||
|
// and jackett): the app masks a stored password as "********", tests an enabled entry before
|
||||||
|
// saving it, refuses a warning unless forceSave, and jackett answers a wrong key 200 with an error.
|
||||||
|
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CLIENTS,
|
||||||
|
acceptRemedy,
|
||||||
|
jackettFeed,
|
||||||
|
providerTakes,
|
||||||
|
reconcileClient,
|
||||||
|
reconcileIndexers,
|
||||||
|
stepSettings,
|
||||||
|
wanted,
|
||||||
|
type App,
|
||||||
|
type Binding,
|
||||||
|
type Endpoint,
|
||||||
|
type Entry,
|
||||||
|
type Http,
|
||||||
|
} from "../downloads/settings.ts";
|
||||||
|
|
||||||
|
const NZBGET = CLIENTS.find((c) => c.provision === "nzbget-api")!;
|
||||||
|
const QBIT = CLIENTS.find((c) => c.provision === "qbittorrent-api")!;
|
||||||
|
const APP: App = { module: "sonarr", url: "http://127.0.0.1:8989", apiKey: "app-key", api: "v3" };
|
||||||
|
const MASK = "********";
|
||||||
|
|
||||||
|
interface Provider {
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
user?: string;
|
||||||
|
secret: string;
|
||||||
|
configured?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nzbget: Provider = { host: "ace.internal", port: 20201, user: "luffy", secret: "nzb-real" };
|
||||||
|
const qbit: Provider = { host: "ace.internal", port: 8112, user: "luffy", secret: "qbt-real" };
|
||||||
|
const jackett: Provider = { host: "ace.internal", port: 20204, secret: "jackett-real", configured: { rutracker: "RuTracker", torrent9: "Torrent9" } };
|
||||||
|
|
||||||
|
function binding(p: Provider, provision: string, extra: Record<string, unknown> = {}): Binding {
|
||||||
|
return {
|
||||||
|
provision,
|
||||||
|
from: "ace",
|
||||||
|
at: p.host,
|
||||||
|
as: "mesh_ace_sonarr",
|
||||||
|
serves: { scheme: "http", port: p.port, "url-base": "", ...(p.user ? { username: p.user } : {}), ...extra },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function endpoint(p: Provider, provision: string, credential = p.secret): Endpoint {
|
||||||
|
const w = wanted(provision, binding(p, provision), credential, provision !== "jackett-api");
|
||||||
|
if (!w.ok) throw new Error(w.problem);
|
||||||
|
return w.endpoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
const f = (name: string, value: unknown) => ({ name, value });
|
||||||
|
|
||||||
|
function client(id: number, name: string, implementation: string, host: string, port: number, password: string, extra: Record<string, unknown> = {}): Entry {
|
||||||
|
return {
|
||||||
|
id, name, implementation, enable: true, priority: 1, tags: [],
|
||||||
|
fields: [f("host", host), f("port", port), f("useSsl", false), f("urlBase", null), f("username", "luffy"), f("password", password), f("tvCategory", "Series"), ...Object.entries(extra).map(([k, v]) => f(k, v))],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function feed(id: number, name: string, baseUrl: string, jid: string, key: string, on = true): Entry {
|
||||||
|
return {
|
||||||
|
id, name, implementation: "Torznab", enableRss: on, enableAutomaticSearch: on, enableInteractiveSearch: on, priority: 25,
|
||||||
|
fields: [f("baseUrl", baseUrl), f("apiPath", `/api/v2.0/indexers/${jid}/results/torznab/`), f("apiKey", key), f("categories", [5000])],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Call {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
body?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A Servarr app and the three providers behind one fetch. */
|
||||||
|
function fakes(start: { clients?: Entry[]; indexers?: Entry[] }) {
|
||||||
|
const calls: Call[] = [];
|
||||||
|
const store: Record<string, Entry[]> = {
|
||||||
|
downloadclient: structuredClone(start.clients ?? []),
|
||||||
|
indexer: structuredClone(start.indexers ?? []),
|
||||||
|
};
|
||||||
|
let next = 100;
|
||||||
|
const secretOf: Record<string, string> = { downloadclient: "password", indexer: "apiKey" };
|
||||||
|
const masked = (e: Entry): Entry => ({ ...e, fields: e.fields!.map((x) => (x.name === "password" || x.name === "apiKey") && x.value ? { ...x, value: MASK } : { ...x }) });
|
||||||
|
const val = (e: Entry, n: string) => e.fields?.find((x) => x.name === n)?.value;
|
||||||
|
|
||||||
|
/** What the app's own test says: dialled from its container, with its stored secret for a mask. */
|
||||||
|
const appTest = (kind: string, e: Entry): { propertyName: string; errorMessage: string; isWarning: boolean }[] => {
|
||||||
|
let secret = val(e, secretOf[kind]);
|
||||||
|
if (secret === MASK) secret = val(store[kind].find((s) => s.id === e.id) ?? {}, secretOf[kind]);
|
||||||
|
if (kind === "downloadclient") {
|
||||||
|
const p = e.implementation === "Nzbget" ? nzbget : qbit;
|
||||||
|
if (val(e, "host") !== p.host || val(e, "port") !== p.port) return [{ propertyName: "Host", errorMessage: "Unable to connect", isWarning: false }];
|
||||||
|
if (secret !== p.secret || val(e, "username") !== p.user) return [{ propertyName: "Username", errorMessage: "Authentication Failure", isWarning: false }];
|
||||||
|
if (val(e, "tvCategory") === "") return [{ propertyName: "TvCategory", errorMessage: "A category is recommended", isWarning: true }];
|
||||||
|
if (e.implementation === "Nzbget" && val(e, "tvCategory") === "tv") return [{ propertyName: "TvCategory", errorMessage: "Category does not exist", isWarning: false }];
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const u = new URL(String(val(e, "baseUrl")));
|
||||||
|
if (u.hostname !== jackett.host || Number(u.port) !== jackett.port) return [{ propertyName: "BaseUrl", errorMessage: "Unable to connect", isWarning: false }];
|
||||||
|
if (secret !== jackett.secret) return [{ propertyName: "ApiKey", errorMessage: "Invalid API Key", isWarning: false }];
|
||||||
|
const id = /indexers\/([^/]+)\//.exec(String(val(e, "apiPath")))?.[1] ?? "";
|
||||||
|
if (!(id in jackett.configured!)) return [{ propertyName: "", errorMessage: "Unknown indexer", isWarning: false }];
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const http: Http = {
|
||||||
|
async fetch(url, init) {
|
||||||
|
const method = init?.method ?? "GET";
|
||||||
|
const body = init?.body && init.headers?.["Content-Type"] === "application/json" ? (JSON.parse(init.body) as Entry) : init?.body;
|
||||||
|
calls.push({ method, url, body });
|
||||||
|
const reply = (status: number, value?: unknown) => ({ status, text: async () => (value === undefined ? "" : typeof value === "string" ? value : JSON.stringify(value)) });
|
||||||
|
const u = new URL(url);
|
||||||
|
// Providers.
|
||||||
|
if (u.pathname === "/jsonrpc/version") {
|
||||||
|
const want = "Basic " + Buffer.from(`${nzbget.user}:${nzbget.secret}`).toString("base64");
|
||||||
|
return init?.headers?.Authorization === want ? reply(200, { result: "26.0" }) : reply(401);
|
||||||
|
}
|
||||||
|
if (u.pathname === "/api/v2/auth/login") {
|
||||||
|
const form = new URLSearchParams(String(init?.body ?? ""));
|
||||||
|
return form.get("username") === qbit.user && form.get("password") === qbit.secret ? reply(204) : reply(401, "Unauthorized");
|
||||||
|
}
|
||||||
|
if (u.pathname.endsWith("/torznab/api")) {
|
||||||
|
if (u.searchParams.get("apikey") !== jackett.secret) return reply(200, '<?xml version="1.0"?><error code="100" description="Invalid API Key" />');
|
||||||
|
const items = Object.entries(jackett.configured!).map(([id, t]) => `<indexer id="${id}" configured="true"><title>${t}</title></indexer>`).join("");
|
||||||
|
return reply(200, `<?xml version="1.0"?><indexers>${items}</indexers>`);
|
||||||
|
}
|
||||||
|
// The app.
|
||||||
|
if (init?.headers?.["X-Api-Key"] !== APP.apiKey) return reply(401);
|
||||||
|
const m = /^\/api\/v3\/(downloadclient|indexer)(?:\/(schema|test|\d+))?$/.exec(u.pathname);
|
||||||
|
if (!m) return reply(404);
|
||||||
|
const [, kind, sub] = m;
|
||||||
|
const force = u.searchParams.get("forceSave") === "true";
|
||||||
|
if (method === "GET" && !sub) return reply(200, store[kind].map(masked));
|
||||||
|
if (method === "GET" && sub === "schema") {
|
||||||
|
return reply(200, kind === "downloadclient"
|
||||||
|
? [client(0, "", "Nzbget", "localhost", 6789, MASK, {}), client(0, "", "QBittorrent", "localhost", 8080, "", {})].map((e) => ({ ...e, fields: e.fields!.map((x) => x.name === "tvCategory" ? { ...x, value: e.implementation === "Nzbget" ? "tv" : "tv-sonarr" } : x.name === "username" ? { ...x, value: null } : x) }))
|
||||||
|
: [{ ...feed(0, "", "", "x", "", false), supportsRss: true, supportsSearch: true, fields: [f("baseUrl", null), f("apiPath", "/api"), f("apiKey", null), f("categories", [5030, 5040])] }]);
|
||||||
|
}
|
||||||
|
if (method === "GET") {
|
||||||
|
const e = store[kind].find((s) => s.id === Number(sub));
|
||||||
|
return e ? reply(200, masked(e)) : reply(404);
|
||||||
|
}
|
||||||
|
if (method === "POST" && sub === "test") {
|
||||||
|
const fails = appTest(kind, body as Entry);
|
||||||
|
return fails.length ? reply(400, fails) : reply(200);
|
||||||
|
}
|
||||||
|
// Save: tested when enabled; a mask keeps what is stored.
|
||||||
|
const e = body as Entry;
|
||||||
|
const on = e.enable === true || e.enableRss === true || e.enableAutomaticSearch === true;
|
||||||
|
if (on) {
|
||||||
|
const fails = appTest(kind, e);
|
||||||
|
if (fails.some((x) => !x.isWarning) || (fails.length && !force)) return reply(400, fails);
|
||||||
|
}
|
||||||
|
if (method === "POST" && !sub) {
|
||||||
|
if (store[kind].some((s) => String(s.name).toLowerCase() === String(e.name).toLowerCase())) {
|
||||||
|
return reply(400, [{ propertyName: "Name", errorMessage: "Should be unique", isWarning: false }]);
|
||||||
|
}
|
||||||
|
const created = { ...e, id: next++ };
|
||||||
|
store[kind].push(created);
|
||||||
|
return reply(201, masked(created));
|
||||||
|
}
|
||||||
|
if (method === "PUT") {
|
||||||
|
const i = store[kind].findIndex((s) => s.id === Number(sub));
|
||||||
|
if (i < 0) return reply(404);
|
||||||
|
const was = store[kind][i];
|
||||||
|
store[kind][i] = { ...e, fields: e.fields!.map((x) => x.value === MASK ? { ...x, value: val(was, x.name) } : x) };
|
||||||
|
return reply(202, masked(store[kind][i]));
|
||||||
|
}
|
||||||
|
return reply(405);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const saves = () => calls.filter((c) => (c.method === "PUT" || (c.method === "POST" && !c.url.endsWith("/test"))) && c.url.includes("/api/v3/"));
|
||||||
|
return { http, calls, store, saves };
|
||||||
|
}
|
||||||
|
|
||||||
|
const aceClients = () => [
|
||||||
|
client(1, "NZBGet", "Nzbget", "nzbget", 6789, "nzb-real"),
|
||||||
|
client(2, "qBitTorrent", "QBittorrent", "qbittorrent", 8112, "qbt-real"),
|
||||||
|
];
|
||||||
|
|
||||||
|
test("the migration's download client is repointed, its category and everything else kept", async () => {
|
||||||
|
const f = fakes({ clients: aceClients() });
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(nzbget, "nzbget-api"), f.store.downloadclient.map((e) => ({ ...e })));
|
||||||
|
assert.deepEqual(out, [{ what: 'nzbget-api ("NZBGet")', result: "written", fields: ["host", "port"] }]);
|
||||||
|
const saved = f.store.downloadclient.find((e) => e.id === 1)!;
|
||||||
|
const v = (n: string) => saved.fields!.find((x) => x.name === n)?.value;
|
||||||
|
assert.equal(v("host"), "ace.internal");
|
||||||
|
assert.equal(v("port"), 20201);
|
||||||
|
assert.equal(v("tvCategory"), "Series");
|
||||||
|
assert.equal(v("password"), "nzb-real", "the password it held works, so it was kept, not rewritten");
|
||||||
|
assert.equal(saved.priority, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rerun: already as the mesh says, nothing saved", async () => {
|
||||||
|
const f = fakes({ clients: [client(1, "NZBGet", "Nzbget", "ace.internal", 20201, "nzb-real")] });
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(nzbget, "nzbget-api"), f.store.downloadclient);
|
||||||
|
assert.deepEqual(out, [{ what: 'nzbget-api ("NZBGet")', result: "unchanged" }]);
|
||||||
|
assert.equal(f.saves().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a stale password is replaced by the delivered one, which the provider took first", async () => {
|
||||||
|
const f = fakes({ clients: [client(2, "qBitTorrent", "QBittorrent", "ace.internal", 8112, "old-pass")] });
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qBitTorrent", endpoint(qbit, "qbittorrent-api"), f.store.downloadclient);
|
||||||
|
assert.deepEqual(out, [{ what: 'qbittorrent-api ("qBitTorrent")', result: "written", fields: ["password"] }]);
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "password")?.value, "qbt-real");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a minted credential is refused by the provider: nothing written, the accept named", async () => {
|
||||||
|
const f = fakes({ clients: aceClients() });
|
||||||
|
const ep = endpoint(nzbget, "nzbget-api", "a-value-the-mesh-minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "nzbget-api", ep), { took: false });
|
||||||
|
const remedy = acceptRemedy(APP, "ace", "nzbget-api", "nzbget", "ControlPassword", ep.from);
|
||||||
|
assert.match(remedy, /`secret accept ace sonarr nzbget-api --provider ace --from <file holding nzbget's ControlPassword>`/);
|
||||||
|
assert.doesNotMatch(remedy, /minted/);
|
||||||
|
assert.equal(f.calls.some((c) => c.url.includes("/api/v3/")), false, "the app was not even asked");
|
||||||
|
const q = endpoint(qbit, "qbittorrent-api", "minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "qbittorrent-api", q), { took: false });
|
||||||
|
const j = endpoint(jackett, "jackett-api", "minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "jackett-api", j), { took: false });
|
||||||
|
assert.equal(f.calls.find((c) => c.url.includes("apikey="))?.url.includes("jackett-real"), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a fresh app gets the mesh's client registered, under the mesh's name", async () => {
|
||||||
|
const f = fakes({});
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qbittorrent", endpoint(qbit, "qbittorrent-api"), []);
|
||||||
|
assert.equal(out[0].result, "created");
|
||||||
|
const e = f.store.downloadclient[0];
|
||||||
|
assert.equal(e.name, "qbittorrent");
|
||||||
|
assert.equal(e.enable, true);
|
||||||
|
assert.equal(e.fields!.find((x) => x.name === "tvCategory")?.value, "tv-sonarr", "the app's own default category");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("nzbget without the app's default category: registered with none, and said", async () => {
|
||||||
|
const f = fakes({});
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "nzbget", endpoint(nzbget, "nzbget-api"), []);
|
||||||
|
assert.equal(out[0].result, "notice");
|
||||||
|
assert.match((out[0] as { note: string }).note, /category left empty/);
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "tvCategory")?.value, "");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("somebody else's entries are never touched: another name of the same kind, and a clash of names", async () => {
|
||||||
|
const mine = client(7, "My seedbox", "QBittorrent", "seedbox.example", 443, "theirs");
|
||||||
|
const f = fakes({ clients: [mine] });
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qbittorrent", endpoint(qbit, "qbittorrent-api"), f.store.downloadclient);
|
||||||
|
assert.equal(out[0].result, "notice");
|
||||||
|
assert.deepEqual(f.store.downloadclient.find((e) => e.id === 7), mine);
|
||||||
|
// Same name in another case: refused, and the setting that adopts it named.
|
||||||
|
const g = fakes({ clients: aceClients() });
|
||||||
|
const clash = await reconcileClient(g.http, APP, NZBGET, "nzbget", endpoint(nzbget, "nzbget-api"), g.store.downloadclient);
|
||||||
|
assert.equal(clash[0].result, "refused");
|
||||||
|
assert.match((clash[0] as { problem: string }).problem, /downloads\.nzbget-api\.name to "NZBGet"/);
|
||||||
|
assert.equal(g.saves().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("jackett feeds: the migration's are repointed, a person's is left, a listed one is registered", async () => {
|
||||||
|
const personal = feed(9, "Seedbox jackett", "https://jackett.seedbox.example", "rutracker", "their-key");
|
||||||
|
const f = fakes({
|
||||||
|
indexers: [
|
||||||
|
feed(5, "Torznab - RuTracker", "https://indexers.zurag.be", "rutracker-ru", "jackett-real", false),
|
||||||
|
feed(6, "Torznab - Torrent9", "https://indexers.zurag.be", "torrent9", "jackett-real", false),
|
||||||
|
feed(4, "Jackett - RARBG", "http://jackett:9117", "therarbg", "old", false),
|
||||||
|
personal,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const configured = new Map(Object.entries(jackett.configured!));
|
||||||
|
const out = await reconcileIndexers(
|
||||||
|
f.http, APP, endpoint(jackett, "jackett-api"), configured,
|
||||||
|
{ adoptHosts: ["indexers.zurag.be", "jackett"], indexers: ["rutracker"] }, [], f.store.indexer,
|
||||||
|
);
|
||||||
|
const byWhat = Object.fromEntries(out.map((o) => [o.what + ":" + o.result, o]));
|
||||||
|
// torrent9: jackett has it; repointed, key already right, tested.
|
||||||
|
assert.ok(byWhat['jackett-api ("Torznab - Torrent9", jackett indexer torrent9):written']);
|
||||||
|
// rutracker-ru and therarbg: jackett has neither — repointed with the key, untested, and said.
|
||||||
|
assert.ok(byWhat['jackett-api ("Jackett - RARBG", jackett indexer therarbg):written']);
|
||||||
|
assert.ok(byWhat['jackett-api ("Jackett - RARBG", jackett indexer therarbg):notice']);
|
||||||
|
// rutracker is listed and nothing of the mesh's reads it: registered.
|
||||||
|
assert.ok(byWhat["jackett-api (jackett indexer rutracker):created"]);
|
||||||
|
assert.deepEqual(f.store.indexer.find((e) => e.id === 9), personal, "a person's jackett is not the mesh's");
|
||||||
|
const t9 = f.store.indexer.find((e) => e.id === 6)!;
|
||||||
|
assert.equal(t9.fields!.find((x) => x.name === "baseUrl")?.value, "http://ace.internal:20204");
|
||||||
|
assert.equal(t9.enableRss, false, "disabled stays disabled");
|
||||||
|
const created = f.store.indexer.find((e) => e.name === "Jackett - RuTracker")!;
|
||||||
|
assert.equal(created.enableRss, true);
|
||||||
|
assert.equal(f.calls.some((c) => c.method === "DELETE"), false, "nothing is ever deleted");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("jackett feeds rerun: nothing saved, and a remembered host keeps a moved jackett's feeds", async () => {
|
||||||
|
const f = fakes({ indexers: [feed(6, "Torznab - Torrent9", "http://ace.internal:20204", "torrent9", "jackett-real")] });
|
||||||
|
const configured = new Map(Object.entries(jackett.configured!));
|
||||||
|
const out = await reconcileIndexers(f.http, APP, endpoint(jackett, "jackett-api"), configured, { adoptHosts: [], indexers: ["torrent9"] }, [], f.store.indexer);
|
||||||
|
assert.deepEqual(out.map((o) => o.result), ["unchanged"]);
|
||||||
|
assert.equal(f.saves().length, 0);
|
||||||
|
// jackett moved to novox: the feed on ace.internal is still the mesh's because it was remembered.
|
||||||
|
const moved = { ...jackett, host: "novox.internal" };
|
||||||
|
const g = fakes({ indexers: [feed(6, "Torznab - Torrent9", "http://ace.internal:20204", "torrent9", "jackett-real")] });
|
||||||
|
const saved = jackett.host;
|
||||||
|
jackett.host = moved.host;
|
||||||
|
try {
|
||||||
|
const again = await reconcileIndexers(g.http, APP, endpoint(moved, "jackett-api"), configured, { adoptHosts: [], indexers: [] }, ["ace.internal"], g.store.indexer);
|
||||||
|
assert.equal(again[0].result, "written");
|
||||||
|
assert.equal(g.store.indexer[0].fields!.find((x) => x.name === "baseUrl")?.value, "http://novox.internal:20204");
|
||||||
|
} finally {
|
||||||
|
jackett.host = saved;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an enabled entry the app cannot test at the mesh's address is not saved", async () => {
|
||||||
|
const f = fakes({ clients: [client(1, "NZBGet", "Nzbget", "nzbget", 6789, "nzb-real")] });
|
||||||
|
const elsewhere = { ...nzbget, port: 1 };
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(elsewhere, "nzbget-api"), f.store.downloadclient);
|
||||||
|
assert.equal(out[0].result, "refused");
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "host")?.value, "nzbget", "left as it was");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("bindings: loopback, no user, no credential are refused; the base path is normalised", () => {
|
||||||
|
assert.equal(wanted("nzbget-api", { ...binding(nzbget, "nzbget-api"), at: "127.0.0.1" }, "x", true).ok, false);
|
||||||
|
assert.equal(wanted("nzbget-api", binding({ ...nzbget, user: undefined }, "nzbget-api"), "x", true).ok, false);
|
||||||
|
assert.equal(wanted("nzbget-api", binding(nzbget, "nzbget-api"), " \n", true).ok, false);
|
||||||
|
const w = wanted("jackett-api", binding(jackett, "jackett-api", { "url-base": "jackett/" }), "k", false);
|
||||||
|
assert.equal(w.ok && w.endpoint.urlBase, "/jackett");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a feed is read whole: base path in the base URL or in the API path", () => {
|
||||||
|
const e = feed(1, "x", "http://ace.internal:9117/jackett", "rutracker", "k");
|
||||||
|
assert.deepEqual(jackettFeed(e), { host: "ace.internal", id: "rutracker" });
|
||||||
|
assert.equal(jackettFeed({ ...e, implementation: "Newznab" }), undefined);
|
||||||
|
assert.equal(jackettFeed({ ...e, fields: [f("baseUrl", "https://api.nzbgeek.info"), f("apiPath", "/api")] }), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("settings: names default to the provider's, adoption and registration read from the merged file", () => {
|
||||||
|
assert.deepEqual(stepSettings({ node: "ace" }), { node: "ace", names: { "nzbget-api": "nzbget", "qbittorrent-api": "qbittorrent" }, indexers: { adoptHosts: [], indexers: [] } });
|
||||||
|
const s = stepSettings({ node: "ace", downloads: { "nzbget-api": { name: "NZBGet" }, "jackett-api": { "adopt-hosts": ["jackett"], indexers: ["torrent9", 3] } } });
|
||||||
|
assert.equal(s.names["nzbget-api"], "NZBGet");
|
||||||
|
assert.deepEqual(s.indexers, { adoptHosts: ["jackett"], indexers: ["torrent9"] });
|
||||||
|
});
|
||||||
|
|
||||||
|
// The four copies are one step. Where the siblings are checked out beside this module, they must
|
||||||
|
// be byte-identical — a fix made in one and not the others is a bug in three apps.
|
||||||
|
test("the step is the same in sonarr, radarr, lidarr and bookshelf", () => {
|
||||||
|
const here = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||||
|
const modules = dirname(here);
|
||||||
|
for (const file of ["downloads/settings.ts", "downloads/index.ts", "test/downloads.test.ts"]) {
|
||||||
|
const mine = readFileSync(join(here, file), "utf8");
|
||||||
|
for (const sibling of ["sonarr", "radarr", "lidarr", "bookshelf"]) {
|
||||||
|
const theirs = join(modules, sibling, file);
|
||||||
|
if (existsSync(theirs)) assert.equal(readFileSync(theirs, "utf8"), mine, `${sibling}/${file} differs`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// lidarr's tools — ported from the shared hal sdk (novox/hq ADR 0039), importing lidarr's own
|
||||||
|
// client. They return structured data (not pre-formatted text as hal did); the mesh serves them
|
||||||
|
// through the sdk's tool harness.
|
||||||
|
|
||||||
|
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||||
|
import { LidarrClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getLidarrTools(lidarr: LidarrClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "lidarr_status",
|
||||||
|
description: "Lidarr status overview: version, artist count, monitored count, queue size.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const [status, content, queue] = await Promise.all([
|
||||||
|
lidarr.getStatus(),
|
||||||
|
lidarr.getContent(),
|
||||||
|
lidarr.getQueue(),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
app: status.appName,
|
||||||
|
version: status.version,
|
||||||
|
artists: content.length,
|
||||||
|
monitored: content.filter((c) => c.monitored).length,
|
||||||
|
queue: queue.totalRecords,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "lidarr_library",
|
||||||
|
description: "List artists from the Lidarr library.",
|
||||||
|
input: { limit: { type: "number", description: "max items to return (default 50)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const items = await lidarr.getContent(args.limit ? Number(args.limit) : 50);
|
||||||
|
return { count: items.length, artists: items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "lidarr_search",
|
||||||
|
description: "Search the Lidarr library for artists by name (filters existing content, not indexers).",
|
||||||
|
input: { query: { type: "string", description: "the search term" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const query = String(args.query);
|
||||||
|
return { query, results: await lidarr.searchContent(query) };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "lidarr_queue",
|
||||||
|
description: "Show the Lidarr download queue — what is downloading and how far along.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const queue = await lidarr.getQueue();
|
||||||
|
return { count: queue.totalRecords, items: queue.items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "lidarr_calendar",
|
||||||
|
description: "Upcoming album releases from the Lidarr calendar.",
|
||||||
|
input: { days: { type: "number", description: "how many days to look ahead (default 7)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const days = args.days ? Number(args.days) : 7;
|
||||||
|
const items = await lidarr.getCalendar(days);
|
||||||
|
items.sort((a, b) => a.date.localeCompare(b.date));
|
||||||
|
return { days, count: items.length, items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tools exist only when Lidarr is configured; without a URL and key, lidarr contributes none
|
||||||
|
// rather than failing the whole runtime.
|
||||||
|
registerModuleTools("lidarr", (env) => {
|
||||||
|
try {
|
||||||
|
return getLidarrTools(LidarrClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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", "downloads/settings.ts", "downloads/index.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# nzbget's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/nzbget
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/nzbget/dist /app/modules/nzbget/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/nzbget/dist/index.js,/app/modules/nzbget/dist/tools/index.js
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
// The NZBGet API client — nzbget's own code, living in the module (novox/hq ADR 0039). Ported from
|
||||||
|
// hal's shared nzbget tools, but self-contained: a change to NZBGet's JSON-RPC now rebuilds only
|
||||||
|
// nzbget and nothing else. Both this module's tools and its events entrypoint import it, and
|
||||||
|
// nothing outside nzbget does. NZBGet speaks JSON-RPC at /jsonrpc, behind HTTP Basic auth.
|
||||||
|
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
export interface NzbgetStatus {
|
||||||
|
/** Bytes/sec — NZBGet reports it split across two 32-bit halves, rejoined here. */
|
||||||
|
speedBytesPerSec: number;
|
||||||
|
remainingMB: number;
|
||||||
|
downloadedTodayMB: number;
|
||||||
|
downloadedMonthMB: number;
|
||||||
|
freeDiskMB: number;
|
||||||
|
paused: boolean;
|
||||||
|
postJobs: number;
|
||||||
|
uptimeSec: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NzbgetQueueItem {
|
||||||
|
/** The NZBID — stable while the item is queued, so events can diff on it. */
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
status: string;
|
||||||
|
category: string;
|
||||||
|
sizeMB: number;
|
||||||
|
remainingMB: number;
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NzbgetHistoryItem {
|
||||||
|
/** The NZBID — the same id the item carried in the queue. */
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
/** NZBGet's own status string, e.g. "SUCCESS/ALL", "FAILURE/PAR", "DELETED/MANUAL". */
|
||||||
|
status: string;
|
||||||
|
category: string;
|
||||||
|
sizeMB: number;
|
||||||
|
/** A genuine completion (status starts "SUCCESS") vs a failed or deleted entry — the difference
|
||||||
|
* between something to announce as done and something that merely left the queue. */
|
||||||
|
success: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
|
||||||
|
function meshConfig(file?: string): Record<string, string> {
|
||||||
|
if (!file) return {};
|
||||||
|
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
|
||||||
|
catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One key of nzbget's own nzbget.conf, from the config directory the mesh mounts read-only
|
||||||
|
* (MESH_NZBGET_CONFIG_DIR). The software's file is the truth about who may log in, so the tools
|
||||||
|
* ask it rather than a setting that could disagree. Absent, unreadable or unset yields undefined. */
|
||||||
|
function confValue(dir: string | undefined, key: string): string | undefined {
|
||||||
|
if (!dir) return undefined;
|
||||||
|
try {
|
||||||
|
const line = readFileSync(`${dir.replace(/\/$/, "")}/nzbget.conf`, "utf8")
|
||||||
|
.split("\n")
|
||||||
|
.find((l) => l.startsWith(`${key}=`));
|
||||||
|
const value = line?.slice(key.length + 1).trim();
|
||||||
|
return value ? value : undefined;
|
||||||
|
} catch { return undefined; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read a secret the mesh mounted at a file path (an own-secret delivered by `secret accept`);
|
||||||
|
* absent or unreadable yields undefined so callers fall back rather than crash. */
|
||||||
|
function readSecret(file?: string): string | undefined {
|
||||||
|
if (!file) return undefined;
|
||||||
|
try { return readFileSync(file, "utf8").trim(); }
|
||||||
|
catch { return undefined; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NzbgetClient {
|
||||||
|
readonly rpcUrl: string;
|
||||||
|
private readonly auth: string;
|
||||||
|
|
||||||
|
constructor(url: string, user: string, password: string) {
|
||||||
|
this.rpcUrl = `${url.replace(/\/$/, "")}/jsonrpc`;
|
||||||
|
this.auth = Buffer.from(`${user}:${password}`).toString("base64");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the module's resolved environment. URL and password are read from MESH_NZBGET_URL
|
||||||
|
* and MESH_NZBGET_PASSWORD; both must be present — an unconfigured NZBGet throws rather than
|
||||||
|
* pretend to be reachable, so the tools/events simply do not load (the harness treats the throw
|
||||||
|
* as "exposes nothing"). The password file is the same own-secret the server container is started
|
||||||
|
* with (FILE__NZBGET_PASS), so the two cannot disagree. The control username is read from
|
||||||
|
* nzbget.conf, falling back to "nzbget", NZBGet's own default.
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): NzbgetClient {
|
||||||
|
const cfg = meshConfig(env.MESH_NZBGET_CONFIG_FILE);
|
||||||
|
const url = cfg.url ?? env.MESH_NZBGET_URL;
|
||||||
|
const password = cfg.password ?? readSecret(env.MESH_NZBGET_PASSWORD_FILE) ?? env.MESH_NZBGET_PASSWORD;
|
||||||
|
if (!url || !password) {
|
||||||
|
throw new Error("NZBGet not configured — set MESH_NZBGET_URL and MESH_NZBGET_PASSWORD");
|
||||||
|
}
|
||||||
|
// The control username: a setting or the environment if one says so, else whatever
|
||||||
|
// nzbget.conf holds (an adopted machine keeps its own, e.g. not "nzbget"), else NZBGet's default.
|
||||||
|
const user = cfg.user ?? env.MESH_NZBGET_USER ?? confValue(env.MESH_NZBGET_CONFIG_DIR, "ControlUsername") ?? "nzbget";
|
||||||
|
return new NzbgetClient(url, user, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async rpc<T>(method: string, params: unknown[] = []): Promise<T> {
|
||||||
|
const res = await fetch(this.rpcUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", Authorization: `Basic ${this.auth}` },
|
||||||
|
body: JSON.stringify({ method, params, id: 1 }),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(`NZBGet API ${method}: ${res.status} ${await res.text()}`);
|
||||||
|
const data = (await res.json()) as { result?: T; error?: unknown };
|
||||||
|
if (data.error) throw new Error(`NZBGet RPC ${method}: ${JSON.stringify(data.error)}`);
|
||||||
|
return data.result as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getVersion(): Promise<string> {
|
||||||
|
return this.rpc<string>("version");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getStatus(): Promise<NzbgetStatus> {
|
||||||
|
const s = await this.rpc<Record<string, number | boolean>>("status");
|
||||||
|
const lo = Number(s.DownloadRateLo ?? 0);
|
||||||
|
const hi = Number(s.DownloadRateHi ?? 0);
|
||||||
|
return {
|
||||||
|
speedBytesPerSec: lo + hi * 4294967296,
|
||||||
|
remainingMB: Number(s.RemainingSizeMB ?? 0),
|
||||||
|
downloadedTodayMB: Number(s.DaySizeMB ?? 0),
|
||||||
|
downloadedMonthMB: Number(s.MonthSizeMB ?? 0),
|
||||||
|
freeDiskMB: Number(s.FreeDiskSpaceMB ?? 0),
|
||||||
|
paused: Boolean(s.DownloadPaused),
|
||||||
|
postJobs: Number(s.PostJobCount ?? 0),
|
||||||
|
uptimeSec: Number(s.UpTimeSec ?? 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getQueue(): Promise<NzbgetQueueItem[]> {
|
||||||
|
const groups = await this.rpc<Record<string, any>[]>("listgroups", [0]);
|
||||||
|
return groups.map((g) => {
|
||||||
|
const size = Number(g.FileSizeMB ?? 0);
|
||||||
|
const remaining = Number(g.RemainingSizeMB ?? 0);
|
||||||
|
return {
|
||||||
|
id: Number(g.NZBID),
|
||||||
|
name: String(g.NZBName ?? "Unknown"),
|
||||||
|
status: String(g.Status ?? "unknown"),
|
||||||
|
category: String(g.Category ?? ""),
|
||||||
|
sizeMB: size,
|
||||||
|
remainingMB: remaining,
|
||||||
|
percent: size > 0 ? Math.round(((size - remaining) / size) * 100) : 0,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getHistory(limit = 20): Promise<NzbgetHistoryItem[]> {
|
||||||
|
const history = await this.rpc<Record<string, any>[]>("history", [false]);
|
||||||
|
return history.slice(0, limit).map((h) => {
|
||||||
|
const status = String(h.Status ?? "");
|
||||||
|
return {
|
||||||
|
id: Number(h.NZBID),
|
||||||
|
name: String(h.Name ?? "Unknown"),
|
||||||
|
status,
|
||||||
|
category: String(h.Category ?? ""),
|
||||||
|
sizeMB: Number(h.FileSizeMB ?? 0),
|
||||||
|
success: status.startsWith("SUCCESS"),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Queue an NZB by URL. Returns the new NZBID; a non-positive id means NZBGet refused it. */
|
||||||
|
async add(url: string, category = "", priority = 0, paused = false): Promise<number> {
|
||||||
|
const id = await this.rpc<number>("append", [
|
||||||
|
"", url, category, priority, false, paused, "", 0, "SCORE", false, [],
|
||||||
|
]);
|
||||||
|
if (!id || id <= 0) throw new Error("NZBGet refused the NZB (append returned 0)");
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
async pauseAll(): Promise<void> {
|
||||||
|
await this.rpc("pausedownload");
|
||||||
|
}
|
||||||
|
|
||||||
|
async resumeAll(): Promise<void> {
|
||||||
|
await this.rpc("resumedownload");
|
||||||
|
}
|
||||||
|
|
||||||
|
async pauseItem(id: number): Promise<void> {
|
||||||
|
await this.rpc("editqueue", ["GroupPause", "", [id]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async resumeItem(id: number): Promise<void> {
|
||||||
|
await this.rpc("editqueue", ["GroupResume", "", [id]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Delete an item from the queue or from history. */
|
||||||
|
async delete(id: number, from: "queue" | "history" = "queue"): Promise<void> {
|
||||||
|
await this.rpc("editqueue", [from === "history" ? "HistoryDelete" : "GroupDelete", "", [id]]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// nzbget's events. The tool runtime imports this once the broker is bound. It watches the download
|
||||||
|
// queue and the history and turns their comings and goings into mesh events.
|
||||||
|
//
|
||||||
|
// Emits (novox/hq ADR 0041/0042):
|
||||||
|
// module.nzbget.download.added — an NZB entered the queue
|
||||||
|
// module.nzbget.download.completed — an NZB finished successfully (left the queue, landed in
|
||||||
|
// history as SUCCESS). 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.
|
||||||
|
//
|
||||||
|
// Two diffs, each primed silently on the first look (like plex's and sonarr's index.ts) so a
|
||||||
|
// restart mid-download does not re-announce everything already in flight or already finished. The
|
||||||
|
// queue tells us what was grabbed; history — not the queue's disappearance — tells us what actually
|
||||||
|
// succeeded, since a failed or deleted download also leaves the queue.
|
||||||
|
|
||||||
|
import { emit } from "@novox/mesh-sdk/events";
|
||||||
|
import { NzbgetClient } from "./client.js";
|
||||||
|
|
||||||
|
const nzbget = NzbgetClient.fromEnv();
|
||||||
|
|
||||||
|
const inQueue = new Set<number>();
|
||||||
|
let queuePrimed = false;
|
||||||
|
async function pollQueue(): Promise<void> {
|
||||||
|
const items = await nzbget.getQueue();
|
||||||
|
const now = new Set(items.map((i) => i.id));
|
||||||
|
if (queuePrimed) {
|
||||||
|
for (const item of items) {
|
||||||
|
if (!inQueue.has(item.id)) {
|
||||||
|
await emit("download.added", { name: item.name, category: item.category, sizeMB: item.sizeMB });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inQueue.clear();
|
||||||
|
for (const id of now) inQueue.add(id);
|
||||||
|
queuePrimed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const seenHistory = new Set<number>();
|
||||||
|
let historyPrimed = false;
|
||||||
|
async function pollHistory(): Promise<void> {
|
||||||
|
const items = await nzbget.getHistory(50);
|
||||||
|
for (const item of items) {
|
||||||
|
if (!seenHistory.has(item.id)) {
|
||||||
|
// A newly-appeared history entry is a completion only if it actually succeeded; a failure or
|
||||||
|
// a manual delete lands in history too, and neither is a "download.completed".
|
||||||
|
if (historyPrimed && item.success) {
|
||||||
|
await emit("download.completed", { name: item.name, category: item.category, sizeMB: item.sizeMB });
|
||||||
|
}
|
||||||
|
seenHistory.add(item.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
historyPrimed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||||
|
const run = (): void => void fn().catch((err) => console.error(`[nzbget] ${err}`));
|
||||||
|
setInterval(run, everyMs);
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
tick(pollQueue, 20_000);
|
||||||
|
tick(pollHistory, 30_000);
|
||||||
|
|
||||||
|
console.log("[nzbget] watching the queue and history, emitting adds and completions");
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
{
|
||||||
|
"module": "nzbget",
|
||||||
|
"version": "1",
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"download.added",
|
||||||
|
"download.completed"
|
||||||
|
],
|
||||||
|
"consumes": [],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/nzbget/broker",
|
||||||
|
"password": "/var/lib/mesh/nzbget/password"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 6789,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "the download client's pages, and the JSON-RPC API its consumers and its own tools call"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accesses": [
|
||||||
|
{
|
||||||
|
"path": "/services/media/downloads",
|
||||||
|
"mode": "read-write"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/nzbget",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "nzbget",
|
||||||
|
"image": "lscr.io/linuxserver/nzbget@sha256:ec3ef0ae7dc410084086a7fdd447deda4747531154aa1cc5c7c48ac60794e277",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC",
|
||||||
|
"FILE__NZBGET_PASS": "/run/secrets/password"
|
||||||
|
},
|
||||||
|
"ports": [
|
||||||
|
"6789"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"/services/media/downloads:/downloads",
|
||||||
|
"/var/lib/mesh/nzbget/password:/run/secrets/password:ro"
|
||||||
|
],
|
||||||
|
"restart-on": [
|
||||||
|
"needs-password"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/config.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-nzbget",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/nzbget/broker:/run/secrets/broker:ro",
|
||||||
|
"/var/lib/mesh/nzbget/password:/run/secrets/password:ro",
|
||||||
|
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||||
|
"${dir:config}:/var/lib/nzbget/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_NZBGET_URL": "http://127.0.0.1:${port:6789}",
|
||||||
|
"MESH_NZBGET_PASSWORD_FILE": "/run/secrets/password",
|
||||||
|
"MESH_NZBGET_CONFIG_FILE": "/run/config/config.json",
|
||||||
|
"MESH_NZBGET_CONFIG_DIR": "/var/lib/nzbget/config"
|
||||||
|
},
|
||||||
|
"restart-on": [
|
||||||
|
"runtime-config",
|
||||||
|
"needs-password"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"provides": [
|
||||||
|
"nzbget-api"
|
||||||
|
],
|
||||||
|
"serves": {
|
||||||
|
"nzbget-api": {
|
||||||
|
"scheme": "http",
|
||||||
|
"port": 6789,
|
||||||
|
"url-base": "",
|
||||||
|
"username": "nzbget"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"requires": [
|
||||||
|
"route"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "nzbget",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-nzbget",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "nzbget — Usenet download client. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// nzbget's tools — ported from the shared hal sdk (novox/hq ADR 0039), importing nzbget's own
|
||||||
|
// client. They return structured data (not the pre-formatted text hal returned); the mesh serves
|
||||||
|
// them through the sdk's tool harness.
|
||||||
|
|
||||||
|
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||||
|
import { NzbgetClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getNzbgetTools(nzbget: NzbgetClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "nzbget_status",
|
||||||
|
description: "NZBGet server status: download speed, queue remaining, disk free, paused state.",
|
||||||
|
input: {},
|
||||||
|
run: async () => nzbget.getStatus(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nzbget_queue",
|
||||||
|
description: "List the current NZBGet download queue — what is downloading and how far along.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const items = await nzbget.getQueue();
|
||||||
|
return { count: items.length, items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nzbget_history",
|
||||||
|
description: "Recent NZBGet download history, newest first — completed, failed and deleted items.",
|
||||||
|
input: { limit: { type: "number", description: "how many entries (default 20)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const items = await nzbget.getHistory(args.limit ? Number(args.limit) : 20);
|
||||||
|
return { count: items.length, items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nzbget_add",
|
||||||
|
description: "Queue an NZB download by URL, optionally into a category.",
|
||||||
|
input: {
|
||||||
|
url: { type: "string", description: "URL to the NZB file" },
|
||||||
|
category: { type: "string", description: "category name (determines download directory)" },
|
||||||
|
priority: { type: "number", description: "-100 very low … 0 normal … 100 very high (default 0)" },
|
||||||
|
paused: { type: "boolean", description: "add in paused state (default false)" },
|
||||||
|
},
|
||||||
|
run: async (args) => {
|
||||||
|
const id = await nzbget.add(
|
||||||
|
String(args.url),
|
||||||
|
args.category ? String(args.category) : "",
|
||||||
|
args.priority ? Number(args.priority) : 0,
|
||||||
|
args.paused === true || args.paused === "true",
|
||||||
|
);
|
||||||
|
return { added: id, category: args.category ? String(args.category) : null };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nzbget_pause",
|
||||||
|
description: "Pause or resume all NZBGet downloads.",
|
||||||
|
input: { resume: { type: "boolean", description: "true to resume, false to pause (default false)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const resume = args.resume === true || args.resume === "true";
|
||||||
|
if (resume) await nzbget.resumeAll();
|
||||||
|
else await nzbget.pauseAll();
|
||||||
|
return { paused: !resume };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nzbget_delete",
|
||||||
|
description: "Delete an NZB from the queue or from history by its NZBID.",
|
||||||
|
input: {
|
||||||
|
id: { type: "number", description: "the NZBID to delete" },
|
||||||
|
from: { type: "string", description: "'queue' (default) or 'history'" },
|
||||||
|
},
|
||||||
|
run: async (args) => {
|
||||||
|
const from = args.from === "history" ? "history" : "queue";
|
||||||
|
await nzbget.delete(Number(args.id), from);
|
||||||
|
return { deleted: Number(args.id), from };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tools exist only when NZBGet is configured; without a URL and password, nzbget contributes
|
||||||
|
// none rather than failing the whole runtime.
|
||||||
|
registerModuleTools("nzbget", (env) => {
|
||||||
|
try {
|
||||||
|
return getNzbgetTools(NzbgetClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# ombi's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/ombi
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts servarr/settings.ts plex/settings.ts connections/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/ombi/dist /app/modules/ombi/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/ombi/dist/index.js,/app/modules/ombi/dist/tools/index.js
|
||||||
|
# NOT dist/connections/index.js: that is a step the host runs to completion, named by the `connections`
|
||||||
|
# container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run inside the
|
||||||
|
# serving sidecar too, and exit it.
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
// The Ombi API client — ombi's own code, living in the module (novox/hq ADR 0039). Ombi is the
|
||||||
|
// request front-end: viewers ask for movies and shows, and an operator approves them. This client
|
||||||
|
// talks its /api/v1 REST API (keyed by an ApiKey header); ombi's tools and events import it.
|
||||||
|
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
export interface OmbiRequest {
|
||||||
|
kind: "movie" | "tv";
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
requestedBy?: string;
|
||||||
|
requestedDate?: string;
|
||||||
|
approved: boolean;
|
||||||
|
available: boolean;
|
||||||
|
denied: boolean;
|
||||||
|
tmdbId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RequestCounts {
|
||||||
|
pending: number;
|
||||||
|
approved: number;
|
||||||
|
available: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
|
||||||
|
function meshConfig(file?: string): Record<string, string> {
|
||||||
|
if (!file) return {};
|
||||||
|
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
|
||||||
|
catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read a secret the mesh mounted at a file path (an own-secret delivered by `secret accept`);
|
||||||
|
* absent or unreadable yields undefined so callers fall back rather than crash. */
|
||||||
|
function readSecret(file?: string): string | undefined {
|
||||||
|
if (!file) return undefined;
|
||||||
|
try { return readFileSync(file, "utf8").trim(); }
|
||||||
|
catch { return undefined; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class OmbiClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly apiKey: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build from the module's resolved environment. Ombi's API is keyed; without URL and key there
|
||||||
|
* is nothing to talk to, so this throws rather than run half-configured. */
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): OmbiClient {
|
||||||
|
const cfg = meshConfig(env.MESH_OMBI_CONFIG_FILE);
|
||||||
|
const url = cfg.url ?? env.MESH_OMBI_URL;
|
||||||
|
const apiKey = cfg.apiKey ?? readSecret(env.MESH_OMBI_API_KEY_FILE) ?? env.MESH_OMBI_API_KEY;
|
||||||
|
if (!url) throw new Error("no Ombi URL — set MESH_OMBI_URL");
|
||||||
|
if (!apiKey) throw new Error("no Ombi API key — set MESH_OMBI_API_KEY");
|
||||||
|
return new OmbiClient(url, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async request(method: string, path: string, body?: unknown): Promise<any> {
|
||||||
|
const res = await fetch(`${this.baseUrl}/api/v1${path}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
ApiKey: this.apiKey,
|
||||||
|
Accept: "application/json",
|
||||||
|
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||||
|
},
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(`Ombi API ${method} ${path}: ${res.status} ${await res.text()}`);
|
||||||
|
const text = await res.text();
|
||||||
|
return text ? JSON.parse(text) : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** All requests, movies and TV together — who asked for what, and where each stands. */
|
||||||
|
async getRequests(): Promise<OmbiRequest[]> {
|
||||||
|
const [movies, tv] = await Promise.all([
|
||||||
|
this.request("GET", "/Request/movie"),
|
||||||
|
this.request("GET", "/Request/tv"),
|
||||||
|
]);
|
||||||
|
const films: OmbiRequest[] = (Array.isArray(movies) ? movies : []).map((r: any) => ({
|
||||||
|
kind: "movie" as const,
|
||||||
|
id: r.id,
|
||||||
|
title: r.title ?? "Unknown",
|
||||||
|
requestedBy: r.requestedUser?.userName ?? r.requestedUser?.userAlias,
|
||||||
|
requestedDate: r.requestedDate,
|
||||||
|
approved: Boolean(r.approved),
|
||||||
|
available: Boolean(r.available),
|
||||||
|
denied: Boolean(r.denied),
|
||||||
|
tmdbId: r.theMovieDbId,
|
||||||
|
}));
|
||||||
|
// TV requests carry per-season child requests; the top-level record is approved when all its
|
||||||
|
// children are, which is the grain an operator acts on.
|
||||||
|
const shows: OmbiRequest[] = (Array.isArray(tv) ? tv : []).map((r: any) => {
|
||||||
|
const children: any[] = r.childRequests ?? [];
|
||||||
|
return {
|
||||||
|
kind: "tv" as const,
|
||||||
|
id: r.id,
|
||||||
|
title: r.title ?? "Unknown",
|
||||||
|
requestedBy: children[0]?.requestedUser?.userName,
|
||||||
|
requestedDate: children[0]?.requestedDate,
|
||||||
|
approved: children.length > 0 && children.every((c) => c.approved),
|
||||||
|
available: children.length > 0 && children.every((c) => c.available),
|
||||||
|
denied: children.some((c) => c.denied),
|
||||||
|
tmdbId: r.theMovieDbId,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return [...films, ...shows];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Live pending/approved/available counts — a one-line health read without listing everything. */
|
||||||
|
async getCounts(): Promise<RequestCounts> {
|
||||||
|
const c = await this.request("GET", "/Request/count");
|
||||||
|
return { pending: c.pending ?? 0, approved: c.approved ?? 0, available: c.available ?? 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Approve a request. TV approval fans out to the request's child (per-season) requests. */
|
||||||
|
async approve(kind: "movie" | "tv", id: number): Promise<void> {
|
||||||
|
await this.request("POST", `/Request/${kind}/approve`, { id });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// ombi's connections step — run once by the host after ombi's server starts, and run again whenever
|
||||||
|
// a binding or pair credential it reads changes (the container's `restart-on`, novox/hq ADR 0099).
|
||||||
|
// It brings ombi's connections to Sonarr, Radarr, Lidarr (servarr/settings.ts) and Plex
|
||||||
|
// (plex/settings.ts) in line with what the mesh bound.
|
||||||
|
//
|
||||||
|
// **A step, not a loop**, for the reason route-adapter gives: everything it does is a function of
|
||||||
|
// files the mesh writes, and the host already knows when they change. It connects to no broker.
|
||||||
|
//
|
||||||
|
// Exits non-zero when any app could not be put right — a refused credential, an unreachable app, an
|
||||||
|
// ombi that cannot reach it — so the node reports the step failed and the host runs it again on the
|
||||||
|
// next apply. It is declared last in the manifest, so its failing gates nothing else of ombi's
|
||||||
|
// (novox/hq ADR 0136). One app failing does not stop the others being put right.
|
||||||
|
//
|
||||||
|
// Reads, per provision, `<dir>/<provision>.json` (the binding) and `<dir>/<provision>.secret` (the
|
||||||
|
// pair credential), where <dir> is MESH_CONNECTIONS_DIR. Never prints a key or a token.
|
||||||
|
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import { PLEX_PROVISION, reconcilePlex } from "../plex/settings.js";
|
||||||
|
import { APPS, ombiReady, readBinding, readIfThere, reconcileApp, type Http, type Outcome } from "../servarr/settings.js";
|
||||||
|
|
||||||
|
const dir = process.env.MESH_CONNECTIONS_DIR ?? "/run/connections";
|
||||||
|
const url = process.env.MESH_OMBI_URL ?? "http://127.0.0.1:3579";
|
||||||
|
const apiKey = (await readIfThere(process.env.MESH_OMBI_API_KEY_FILE))?.trim() ?? process.env.MESH_OMBI_API_KEY ?? "";
|
||||||
|
const waitSeconds = Number(process.env.MESH_OMBI_WAIT_SECONDS ?? "180");
|
||||||
|
|
||||||
|
// Every call bounded: an entry ombi keeps may name a host that no longer answers, and a step that
|
||||||
|
// hangs on it holds the apply.
|
||||||
|
const http: Http = { fetch: (u, init) => fetch(u, { ...init, signal: AbortSignal.timeout(20_000) }) };
|
||||||
|
|
||||||
|
if (!apiKey) {
|
||||||
|
console.error("[ombi-connections] no ombi API key — ombi's own `api-key` secret has not been accepted");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const ombi = { url, apiKey };
|
||||||
|
|
||||||
|
if (!(await ombiReady(http, ombi, waitSeconds * 1000))) {
|
||||||
|
console.error(`[ombi-connections] ombi did not answer at ${url} within ${waitSeconds}s`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputs = async (provision: string) =>
|
||||||
|
[await readBinding(join(dir, `${provision}.json`)), await readIfThere(join(dir, `${provision}.secret`))] as const;
|
||||||
|
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
for (const spec of APPS) {
|
||||||
|
outcomes.push(await reconcileApp(http, ombi, spec, ...(await inputs(spec.provision))));
|
||||||
|
}
|
||||||
|
outcomes.push(await reconcilePlex(http, ombi, ...(await inputs(PLEX_PROVISION))));
|
||||||
|
|
||||||
|
let failed = 0;
|
||||||
|
for (const outcome of outcomes) {
|
||||||
|
switch (outcome.result) {
|
||||||
|
case "unchanged":
|
||||||
|
console.log(`[ombi-connections] ${outcome.app}: already as the mesh says; connection tested`);
|
||||||
|
break;
|
||||||
|
case "written":
|
||||||
|
console.log(`[ombi-connections] ${outcome.app}: wrote ${outcome.fields.join(", ")}; connection tested`);
|
||||||
|
break;
|
||||||
|
case "refused":
|
||||||
|
failed++;
|
||||||
|
console.error(`[ombi-connections] ${outcome.app}: ${outcome.problem}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.exitCode = failed > 0 ? 1 : 0;
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
// ombi's events. The tool runtime imports this once the broker is bound. Ombi's timeline is the
|
||||||
|
// request lifecycle: a viewer files a request, and later an operator approves it. Both transitions
|
||||||
|
// are worth announcing — the mesh can notify on a new request, and act on an approval (that is when
|
||||||
|
// a downloader should start looking).
|
||||||
|
//
|
||||||
|
// Emits (novox/hq ADR 0041/0042):
|
||||||
|
// module.ombi.request.created — a viewer filed a new request
|
||||||
|
// module.ombi.request.approved — a request was approved
|
||||||
|
//
|
||||||
|
// Ombi is the origin of these decisions, not a reactor to the mesh, so it consumes nothing.
|
||||||
|
//
|
||||||
|
// Both events are observation-based: poll the request list and diff. Creation is diffed on the set
|
||||||
|
// of request ids; approval on each request's approved flag flipping true. Primed silently on the
|
||||||
|
// first look, or a restart would re-announce every existing request and approval.
|
||||||
|
|
||||||
|
import { emit } from "@novox/mesh-sdk/events";
|
||||||
|
import { OmbiClient, type OmbiRequest } from "./client.js";
|
||||||
|
|
||||||
|
const ombi = OmbiClient.fromEnv();
|
||||||
|
|
||||||
|
// Remember each seen request and whether it was approved last time, keyed by kind+id (ids are only
|
||||||
|
// unique within a kind).
|
||||||
|
const approvedState = new Map<string, boolean>();
|
||||||
|
let primed = false;
|
||||||
|
|
||||||
|
const keyOf = (r: OmbiRequest): string => `${r.kind}:${r.id}`;
|
||||||
|
|
||||||
|
async function pollRequests(): Promise<void> {
|
||||||
|
const requests = await ombi.getRequests();
|
||||||
|
for (const r of requests) {
|
||||||
|
const key = keyOf(r);
|
||||||
|
const known = approvedState.has(key);
|
||||||
|
if (primed && !known) {
|
||||||
|
await emit("request.created", {
|
||||||
|
kind: r.kind,
|
||||||
|
id: r.id,
|
||||||
|
title: r.title,
|
||||||
|
requestedBy: r.requestedBy,
|
||||||
|
tmdbId: r.tmdbId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Approval: the flag went from false to true for a request we already knew about.
|
||||||
|
if (primed && known && r.approved && approvedState.get(key) === false) {
|
||||||
|
await emit("request.approved", { kind: r.kind, id: r.id, title: r.title, tmdbId: r.tmdbId });
|
||||||
|
}
|
||||||
|
approvedState.set(key, r.approved);
|
||||||
|
}
|
||||||
|
primed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||||
|
const run = (): void => void fn().catch((err) => console.error(`[ombi] ${err}`));
|
||||||
|
setInterval(run, everyMs);
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
tick(pollRequests, 30_000);
|
||||||
|
|
||||||
|
console.log("[ombi] watching requests for new filings and approvals");
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
{
|
||||||
|
"module": "ombi",
|
||||||
|
"version": "1",
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"request.created",
|
||||||
|
"request.approved"
|
||||||
|
],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/ombi/broker",
|
||||||
|
"api-key": "/var/lib/mesh/ombi/api-key"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 3579,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "requests from viewers"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/ombi",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "ombi",
|
||||||
|
"image": "lscr.io/linuxserver/ombi@sha256:22d6ebadbaaa728571353e74dc2173719e0fb02d4eaec551a7e9d2ee99ef68ac",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC"
|
||||||
|
},
|
||||||
|
"ports": [
|
||||||
|
"3579"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "/var/lib/mesh/ombi/config.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-ombi",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/ombi/broker:/run/secrets/broker:ro",
|
||||||
|
"/var/lib/mesh/ombi/api-key:/run/secrets/api-key:ro",
|
||||||
|
"/var/lib/mesh/ombi/config.json:/run/config/config.json:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_OMBI_URL": "http://127.0.0.1:${port:3579}",
|
||||||
|
"MESH_OMBI_API_KEY_FILE": "/run/secrets/api-key",
|
||||||
|
"MESH_OMBI_CONFIG_FILE": "/run/config/config.json"
|
||||||
|
},
|
||||||
|
"restart-on": [
|
||||||
|
"runtime-config"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "connections",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-ombi-connections",
|
||||||
|
"network": "host",
|
||||||
|
"run-once": true,
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/ombi/api-key:/run/secrets/api-key:ro",
|
||||||
|
"${dir:state}/sonarr-api.json:/run/connections/sonarr-api.json:ro",
|
||||||
|
"${dir:state}/sonarr-api.secret:/run/connections/sonarr-api.secret:ro",
|
||||||
|
"${dir:state}/radarr-api.json:/run/connections/radarr-api.json:ro",
|
||||||
|
"${dir:state}/radarr-api.secret:/run/connections/radarr-api.secret:ro",
|
||||||
|
"${dir:state}/lidarr-api.json:/run/connections/lidarr-api.json:ro",
|
||||||
|
"${dir:state}/lidarr-api.secret:/run/connections/lidarr-api.secret:ro",
|
||||||
|
"${dir:state}/plex-api.json:/run/connections/plex-api.json:ro",
|
||||||
|
"${dir:state}/plex-api.secret:/run/connections/plex-api.secret:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_OMBI_URL": "http://127.0.0.1:${port:3579}",
|
||||||
|
"MESH_OMBI_API_KEY_FILE": "/run/secrets/api-key",
|
||||||
|
"MESH_CONNECTIONS_DIR": "/run/connections"
|
||||||
|
},
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"/app/modules/ombi/dist/connections/index.js"
|
||||||
|
],
|
||||||
|
"restart-on": [
|
||||||
|
"bound-sonarr-api",
|
||||||
|
"secret-sonarr-api",
|
||||||
|
"bound-radarr-api",
|
||||||
|
"secret-radarr-api",
|
||||||
|
"bound-lidarr-api",
|
||||||
|
"secret-lidarr-api",
|
||||||
|
"bound-plex-api",
|
||||||
|
"secret-plex-api"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requires": [
|
||||||
|
"lidarr-api",
|
||||||
|
"plex-api",
|
||||||
|
"radarr-api",
|
||||||
|
"route",
|
||||||
|
"sonarr-api"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "ombi",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json",
|
||||||
|
"sonarr-api": "${dir:state}/sonarr-api.json",
|
||||||
|
"radarr-api": "${dir:state}/radarr-api.json",
|
||||||
|
"lidarr-api": "${dir:state}/lidarr-api.json",
|
||||||
|
"plex-api": "${dir:state}/plex-api.json"
|
||||||
|
},
|
||||||
|
"secrets": {
|
||||||
|
"sonarr-api": "${dir:state}/sonarr-api.secret",
|
||||||
|
"radarr-api": "${dir:state}/radarr-api.secret",
|
||||||
|
"lidarr-api": "${dir:state}/lidarr-api.secret",
|
||||||
|
"plex-api": "${dir:state}/plex-api.secret"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-ombi",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "ombi — media requests. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc client.ts index.ts tools/index.ts servarr/settings.ts plex/settings.ts connections/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist",
|
||||||
|
"typecheck": "tsc -p tsconfig.json",
|
||||||
|
"test": "npm run build && node --test --experimental-strip-types 'test/*.test.ts'"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
// Where ombi reaches Plex — decided by the mesh, written into ombi by ombi's own API.
|
||||||
|
//
|
||||||
|
// **Why this exists.** ombi keeps its Plex servers in its own database (OmbiSettings.db), so the
|
||||||
|
// mesh has no file to write `${bound:plex-api:at}` into. ombi requires `plex-api`; the mesh delivers
|
||||||
|
// a binding (where plex is: `at`, and what it serves: `port`, `scheme`) and a pair credential (the
|
||||||
|
// server owner's X-Plex-Token, accepted by the operator — plex.tv issues it and the mesh cannot
|
||||||
|
// mint it). This step makes ombi's Plex settings say the same thing, beside its Servarr ones.
|
||||||
|
//
|
||||||
|
// **Which entry is plex's.** ombi may list several Plex servers. The one this provision names is
|
||||||
|
// found by the server's own machineIdentifier, which plex answers at /identity — the same value
|
||||||
|
// ombi stored when an operator loaded the server in its settings screen. That entry's connection is
|
||||||
|
// brought in line; an entry for any other server is never touched.
|
||||||
|
//
|
||||||
|
// When no entry carries that identifier, an entry may still be this server reached another way:
|
||||||
|
// ace's ombi holds one loaded from an older server and later retyped to plex's public name, so its
|
||||||
|
// stored identifier is stale while its address answers as this plex. Each entry's OWN address is
|
||||||
|
// asked for /identity, and an entry plex itself answers for is this server's — adopted: its
|
||||||
|
// connection laid over and its identifier corrected (ombi builds its "view in Plex" links from it).
|
||||||
|
// Nothing is guessed: an entry whose address is unreachable, or answers as another server, is left
|
||||||
|
// as it was. Only when no entry is this server's either way is one added, named as plex names
|
||||||
|
// itself — it is the mesh's, so later runs keep it true.
|
||||||
|
//
|
||||||
|
// **Only the connection, and only when it differs.** Host, port, TLS, base path and token — and the
|
||||||
|
// identifier of an adopted entry. Whether Plex is enabled in ombi, watchlist import, the selected
|
||||||
|
// libraries, the batch size and everything else an operator chose are left exactly as they are.
|
||||||
|
//
|
||||||
|
// **A token plex refuses is never written.** Until the operator accepts the server's token for this
|
||||||
|
// pair, the mesh delivers a value it minted itself, which plex answers with 401 (or 400 on its own
|
||||||
|
// network). Writing it would replace a working token in ombi with a dead one, so the token is tried
|
||||||
|
// against plex first; refused, nothing is written and the step fails naming the `secret accept`.
|
||||||
|
|
||||||
|
import { isLoopback, ombiCall, type Binding, type Http, type Ombi, type Outcome } from "../servarr/settings.js";
|
||||||
|
|
||||||
|
/** The provision ombi requires for Plex — the manifest's `requires`, `binds` and `secrets` key. */
|
||||||
|
export const PLEX_PROVISION = "plex-api";
|
||||||
|
|
||||||
|
/** The connection fields ombi keeps for a Plex server — the only ones this step ever writes. */
|
||||||
|
export interface PlexConnection {
|
||||||
|
ip: string;
|
||||||
|
port: number;
|
||||||
|
ssl: boolean;
|
||||||
|
subDir: string | null;
|
||||||
|
plexAuthToken: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PlexWanted = { ok: true; connection: PlexConnection; from: string } | { ok: false; problem: string };
|
||||||
|
|
||||||
|
/** The connection the mesh says ombi should use, from the binding and the pair credential. */
|
||||||
|
export function wantedPlex(binding: Binding | undefined, credential: string | undefined): PlexWanted {
|
||||||
|
if (!binding) {
|
||||||
|
return { ok: false, problem: `no binding for ${PLEX_PROVISION} was delivered — the mesh writes it before this step runs` };
|
||||||
|
}
|
||||||
|
const at = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||||
|
const serves = binding.serves ?? {};
|
||||||
|
const port = Number(serves.port);
|
||||||
|
if (!at) return { ok: false, problem: `the ${PLEX_PROVISION} binding names no host (at)` };
|
||||||
|
if (isLoopback(at)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
problem:
|
||||||
|
`the ${PLEX_PROVISION} binding says plex is at ${at}, which from ombi's own container is ombi itself. ` +
|
||||||
|
`The mesh hands loopback to a machine that is not on the private network; put it on the private ` +
|
||||||
|
`network so plex has an address ombi can dial`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||||
|
return { ok: false, problem: `the ${PLEX_PROVISION} binding serves no usable port (${String(serves.port)})` };
|
||||||
|
}
|
||||||
|
const scheme = typeof serves.scheme === "string" && serves.scheme ? serves.scheme : "http";
|
||||||
|
if (scheme !== "http" && scheme !== "https") {
|
||||||
|
return { ok: false, problem: `the ${PLEX_PROVISION} binding serves scheme ${scheme}, which ombi cannot dial` };
|
||||||
|
}
|
||||||
|
const token = (credential ?? "").trim();
|
||||||
|
if (!token) return { ok: false, problem: `the ${PLEX_PROVISION} credential is empty or was not delivered` };
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
from: typeof binding.from === "string" ? binding.from : "",
|
||||||
|
connection: { ip: at, port, ssl: scheme === "https", subDir: null, plexAuthToken: token },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** plex's base URL as the step dials it — the same host and port ombi will be given. */
|
||||||
|
export function plexUrl(want: PlexConnection): string {
|
||||||
|
const host = want.ip.includes(":") && !want.ip.startsWith("[") ? `[${want.ip}]` : want.ip;
|
||||||
|
return `${want.ssl ? "https" : "http"}://${host}:${want.port}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which connection fields differ between an entry ombi holds and what the mesh says. Names only. */
|
||||||
|
export function differingPlex(current: Record<string, unknown> | undefined, want: PlexConnection): (keyof PlexConnection)[] {
|
||||||
|
const now = current ?? {};
|
||||||
|
const out: (keyof PlexConnection)[] = [];
|
||||||
|
if (String(now.ip ?? "") !== want.ip) out.push("ip");
|
||||||
|
if (Number(now.port ?? 0) !== want.port) out.push("port");
|
||||||
|
if (Boolean(now.ssl) !== want.ssl) out.push("ssl");
|
||||||
|
const sub = typeof now.subDir === "string" && now.subDir.trim() !== "" ? now.subDir : null;
|
||||||
|
if (sub !== want.subDir) out.push("subDir");
|
||||||
|
if (String(now.plexAuthToken ?? "") !== want.plexAuthToken) out.push("plexAuthToken");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function plexGet(http: Http, want: PlexConnection, path: string, withToken: boolean) {
|
||||||
|
const headers: Record<string, string> = { Accept: "application/json" };
|
||||||
|
if (withToken) headers["X-Plex-Token"] = want.plexAuthToken;
|
||||||
|
return http.fetch(`${plexUrl(want)}${path}`, { method: "GET", headers });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does plex take this token? `true` it does; `false` it refused it — 401 or 403, or 400, which is
|
||||||
|
* what plex answers a token it never issued on a network it trusts. A thrown error when plex could
|
||||||
|
* not be asked.
|
||||||
|
*/
|
||||||
|
export async function plexTakes(http: Http, want: PlexConnection): Promise<{ takes: boolean; friendlyName?: string }> {
|
||||||
|
const res = await plexGet(http, want, "/", true);
|
||||||
|
if (res.status === 400 || res.status === 401 || res.status === 403) return { takes: false };
|
||||||
|
if (res.status < 200 || res.status >= 300) throw new Error(`plex answered ${res.status} at /`);
|
||||||
|
let friendlyName: string | undefined;
|
||||||
|
try {
|
||||||
|
const body = JSON.parse(await res.text()) as { MediaContainer?: { friendlyName?: unknown } };
|
||||||
|
if (typeof body.MediaContainer?.friendlyName === "string") friendlyName = body.MediaContainer.friendlyName;
|
||||||
|
} catch {
|
||||||
|
// a name is a nicety for a new entry, not a condition
|
||||||
|
}
|
||||||
|
return { takes: true, friendlyName };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server's own machineIdentifier, which plex answers without a token. */
|
||||||
|
export async function plexIdentity(http: Http, want: Pick<PlexConnection, "ip" | "port" | "ssl" | "subDir">): Promise<string> {
|
||||||
|
const host = want.ip.includes(":") && !want.ip.startsWith("[") ? `[${want.ip}]` : want.ip;
|
||||||
|
const base = `${want.ssl ? "https" : "http"}://${host}:${want.port}${want.subDir ? `/${want.subDir.replace(/^\/+|\/+$/g, "")}` : ""}`;
|
||||||
|
const res = await http.fetch(`${base}/identity`, { method: "GET", headers: { Accept: "application/json" } });
|
||||||
|
if (res.status !== 200) throw new Error(`plex answered ${res.status} at /identity`);
|
||||||
|
const body = JSON.parse(await res.text()) as { MediaContainer?: { machineIdentifier?: unknown } };
|
||||||
|
const id = body.MediaContainer?.machineIdentifier;
|
||||||
|
if (typeof id !== "string" || id === "") throw new Error("plex's /identity names no machineIdentifier");
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The remedy for a refused token, in the controller's own words (ADR 0092). */
|
||||||
|
export function plexAcceptRemedy(from: string): string {
|
||||||
|
return (
|
||||||
|
`plex refuses the ${PLEX_PROVISION} credential the mesh delivered, so it was not written into ombi. ` +
|
||||||
|
`plex's token is issued by plex.tv and the mesh cannot make it: accept the server's own token for ` +
|
||||||
|
`this pair — \`secret accept <this node> ombi ${PLEX_PROVISION} --provider ${from || "<its node>"} ` +
|
||||||
|
`--from <file holding the server's X-Plex-Token>\``
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The batch size ombi's settings screen fills in for a server it adds ("150 by default"). */
|
||||||
|
const EPISODE_BATCH_SIZE = 150;
|
||||||
|
|
||||||
|
/** ombi's server entries, as its settings document holds them (null on a fresh ombi). */
|
||||||
|
export function serversOf(document: Record<string, unknown> | undefined): Record<string, unknown>[] {
|
||||||
|
const servers = document?.servers;
|
||||||
|
return Array.isArray(servers) ? (servers as Record<string, unknown>[]) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which entries, holding another identifier, plex answers for at their own address — this server,
|
||||||
|
* reached another way. Asked only when no entry carries the identifier. An entry that cannot be
|
||||||
|
* asked is not this server's: nothing is guessed.
|
||||||
|
*/
|
||||||
|
export async function answeringAs(http: Http, servers: Record<string, unknown>[], machineIdentifier: string): Promise<Set<number>> {
|
||||||
|
const out = new Set<number>();
|
||||||
|
if (servers.some((s) => s?.machineIdentifier === machineIdentifier)) return out;
|
||||||
|
for (const [i, s] of servers.entries()) {
|
||||||
|
const ip = typeof s?.ip === "string" ? s.ip.trim() : "";
|
||||||
|
const port = Number(s?.port);
|
||||||
|
if (!ip || !Number.isInteger(port) || port <= 0 || port > 65535) continue;
|
||||||
|
const subDir = typeof s.subDir === "string" && s.subDir.trim() !== "" ? s.subDir : null;
|
||||||
|
try {
|
||||||
|
if ((await plexIdentity(http, { ip, port, ssl: Boolean(s.ssl), subDir })) === machineIdentifier) out.add(i);
|
||||||
|
} catch {
|
||||||
|
// unreachable, or not a plex: not this server's
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ombi's Plex settings with this server's connection laid over them: every entry naming the
|
||||||
|
* server's machineIdentifier — or adopted, its address answering as this server — gets the
|
||||||
|
* connection (an adopted one also the identifier), every other entry is left as it was, and when
|
||||||
|
* none is this server's one is added. Returns the document to save and the fields that changed.
|
||||||
|
*/
|
||||||
|
export function withPlexServer(
|
||||||
|
document: Record<string, unknown> | undefined,
|
||||||
|
machineIdentifier: string,
|
||||||
|
want: PlexConnection,
|
||||||
|
name: string,
|
||||||
|
adopted: ReadonlySet<number> = new Set(),
|
||||||
|
): { next: Record<string, unknown>; fields: string[]; added: boolean; entry: Record<string, unknown> } {
|
||||||
|
const doc = document ?? {};
|
||||||
|
const servers = serversOf(doc);
|
||||||
|
const fields = new Set<string>();
|
||||||
|
let entry: Record<string, unknown> | undefined;
|
||||||
|
const next = servers.map((s, i) => {
|
||||||
|
const adopt = adopted.has(i) && s?.machineIdentifier !== machineIdentifier;
|
||||||
|
if (s?.machineIdentifier !== machineIdentifier && !adopt) return s;
|
||||||
|
for (const f of differingPlex(s, want)) fields.add(f);
|
||||||
|
if (adopt) fields.add("machineIdentifier");
|
||||||
|
const laid = { ...s, machineIdentifier, ip: want.ip, port: want.port, ssl: want.ssl, subDir: want.subDir, plexAuthToken: want.plexAuthToken };
|
||||||
|
entry ??= laid;
|
||||||
|
return laid;
|
||||||
|
});
|
||||||
|
if (entry) return { next: { ...doc, servers: next }, fields: [...fields], added: false, entry };
|
||||||
|
const added: Record<string, unknown> = {
|
||||||
|
name,
|
||||||
|
machineIdentifier,
|
||||||
|
ip: want.ip,
|
||||||
|
port: want.port,
|
||||||
|
ssl: want.ssl,
|
||||||
|
subDir: want.subDir,
|
||||||
|
plexAuthToken: want.plexAuthToken,
|
||||||
|
episodeBatchSize: EPISODE_BATCH_SIZE,
|
||||||
|
plexSelectedLibraries: [],
|
||||||
|
};
|
||||||
|
return { next: { ...doc, servers: [...next, added] }, fields: ["server"], added: true, entry: added };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring ombi's connection to plex in line with the mesh: check the token against plex, find the
|
||||||
|
* server's entry by its machineIdentifier, write only the connection fields when they differ (or add
|
||||||
|
* the entry), then have ombi test the connection from its own container. Never throws.
|
||||||
|
*/
|
||||||
|
export async function reconcilePlex(http: Http, ombi: Ombi, binding: Binding | undefined, credential: string | undefined): Promise<Outcome> {
|
||||||
|
const app = "plex";
|
||||||
|
const w = wantedPlex(binding, credential);
|
||||||
|
// `in`, not `!w.ok`: the Dockerfile compiles without strict, where a boolean discriminant does not
|
||||||
|
// narrow.
|
||||||
|
if ("problem" in w) return { app, result: "refused", problem: w.problem };
|
||||||
|
const want = w.connection;
|
||||||
|
|
||||||
|
let name: string;
|
||||||
|
let machineIdentifier: string;
|
||||||
|
try {
|
||||||
|
const taken = await plexTakes(http, want);
|
||||||
|
if (!taken.takes) return { app, result: "refused", problem: plexAcceptRemedy(w.from) };
|
||||||
|
machineIdentifier = await plexIdentity(http, want);
|
||||||
|
name = taken.friendlyName || "Plex";
|
||||||
|
} catch (err) {
|
||||||
|
return { app, result: "refused", problem: `plex could not be asked whether it takes the token at ${want.ip}:${want.port}: ${message(err)}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const document = (await ombiCall(http, ombi, "GET", "/Settings/Plex")) as Record<string, unknown> | undefined;
|
||||||
|
const adopted = await answeringAs(http, serversOf(document), machineIdentifier);
|
||||||
|
const laid = withPlexServer(document, machineIdentifier, want, name, adopted);
|
||||||
|
if (laid.fields.length > 0) {
|
||||||
|
const saved = await ombiCall(http, ombi, "POST", "/Settings/Plex", laid.next);
|
||||||
|
if (saved === false) return { app, result: "refused", problem: "ombi declined to save its Plex settings" };
|
||||||
|
}
|
||||||
|
// ombi's own test, from ombi's own container — the path the step's check above did not take.
|
||||||
|
const tested = await ombiCall(http, ombi, "POST", "/Tester/plex", laid.entry);
|
||||||
|
if (tested !== true) {
|
||||||
|
return {
|
||||||
|
app,
|
||||||
|
result: "refused",
|
||||||
|
problem:
|
||||||
|
`ombi cannot reach plex at ${want.ip}:${want.port} from its own container` +
|
||||||
|
(laid.fields.length > 0 ? `; its settings were written (${laid.fields.join(", ")})` : ""),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return laid.fields.length > 0 ? { app, result: "written", fields: laid.fields } : { app, result: "unchanged" };
|
||||||
|
} catch (err) {
|
||||||
|
return { app, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(err: unknown): string {
|
||||||
|
return err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
// Where ombi reaches Sonarr, Radarr and Lidarr — decided by the mesh, written into ombi by ombi's
|
||||||
|
// own API.
|
||||||
|
//
|
||||||
|
// **Why this exists.** ombi keeps its connection to each Servarr app in its own database
|
||||||
|
// (OmbiSettings.db), not in a file, so the mesh has nowhere to write `${bound:sonarr-api:at}` for it.
|
||||||
|
// ombi requires `sonarr-api`, `radarr-api` and `lidarr-api`; the mesh delivers, for each, a binding
|
||||||
|
// (where the app is: `at`, and what it serves: `port`, `scheme`, `url-base`) and a pair credential
|
||||||
|
// (the app's API key, accepted by the operator — a Servarr app has exactly one key and the mesh
|
||||||
|
// cannot mint it). This step reads those files and makes ombi's settings say the same thing.
|
||||||
|
//
|
||||||
|
// **Only the connection, and only when it differs.** Host, port, TLS, base path and API key. The
|
||||||
|
// quality profile, root folder, language profile, tags, "enabled" and every other choice an operator
|
||||||
|
// made in ombi's settings screen are left exactly as they are: the mesh knows where the app is, not
|
||||||
|
// what ombi should do with it. Radarr's 4K instance is a different Radarr and is not touched.
|
||||||
|
//
|
||||||
|
// **A credential the app refuses is never written.** Until the operator accepts the app's API key
|
||||||
|
// for this pair, the mesh delivers a value it minted itself, which no Servarr app will ever accept
|
||||||
|
// (novox/hq ADR 0092). Writing it would replace a working key in ombi with a dead one. So the key is
|
||||||
|
// tried against the app first; refused, nothing for that app is written and the step fails naming
|
||||||
|
// the `secret accept` that fixes it.
|
||||||
|
//
|
||||||
|
// Pure logic and a small HTTP seam, so it is tested against fake servers (test/servarr.test.ts).
|
||||||
|
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
|
||||||
|
/** One Servarr app ombi connects to, and the shape of that connection in ombi's API. */
|
||||||
|
export interface ServarrApp {
|
||||||
|
/** The app, as ombi's API names it: /Settings/<app>, /Tester/<app>. */
|
||||||
|
app: "sonarr" | "radarr" | "lidarr";
|
||||||
|
/** The provision it is required as — the manifest's `requires`, `binds` and `secrets` key. */
|
||||||
|
provision: string;
|
||||||
|
/** The app's own status endpoint, which answers 401 to a wrong key. */
|
||||||
|
statusPath: string;
|
||||||
|
/**
|
||||||
|
* Where the one connection sits in ombi's settings document. Radarr's is `{radarr, radarr4K}`
|
||||||
|
* (two Radarr instances); only `radarr` is this provision's.
|
||||||
|
*/
|
||||||
|
within?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const APPS: readonly ServarrApp[] = [
|
||||||
|
{ app: "sonarr", provision: "sonarr-api", statusPath: "/api/v3/system/status" },
|
||||||
|
{ app: "radarr", provision: "radarr-api", statusPath: "/api/v3/system/status", within: "radarr" },
|
||||||
|
{ app: "lidarr", provision: "lidarr-api", statusPath: "/api/v1/system/status" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** The connection fields ombi keeps for an app — the only ones this step ever writes. */
|
||||||
|
export interface Connection {
|
||||||
|
ip: string;
|
||||||
|
port: number;
|
||||||
|
ssl: boolean;
|
||||||
|
/** ombi's name for the app's URL base; null when the app is served at the root. */
|
||||||
|
subDir: string | null;
|
||||||
|
apiKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the mesh wrote at `binds.<provision>`: the binding document (controller's boundFile). */
|
||||||
|
export interface Binding {
|
||||||
|
provision?: string;
|
||||||
|
from?: string;
|
||||||
|
at?: string;
|
||||||
|
as?: string;
|
||||||
|
serves?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Wanted = { ok: true; connection: Connection; from: string } | { ok: false; problem: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The connection the mesh says ombi should use, from the binding and the pair credential.
|
||||||
|
*
|
||||||
|
* Refused rather than guessed when the binding cannot be dialled from ombi's own container: a
|
||||||
|
* loopback `at` — what the mesh hands a machine that is not on the private network — is ombi's
|
||||||
|
* container itself, not the app.
|
||||||
|
*/
|
||||||
|
export function wanted(spec: ServarrApp, binding: Binding | undefined, credential: string | undefined): Wanted {
|
||||||
|
if (!binding) {
|
||||||
|
return { ok: false, problem: `no binding for ${spec.provision} was delivered — the mesh writes it before this step runs` };
|
||||||
|
}
|
||||||
|
const at = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||||
|
const serves = binding.serves ?? {};
|
||||||
|
const port = Number(serves.port);
|
||||||
|
if (!at) {
|
||||||
|
return { ok: false, problem: `the ${spec.provision} binding names no host (at)` };
|
||||||
|
}
|
||||||
|
if (isLoopback(at)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
problem:
|
||||||
|
`the ${spec.provision} binding says ${spec.app} is at ${at}, which from ombi's own container is ` +
|
||||||
|
`ombi itself. The mesh hands loopback to a machine that is not on the private network; put it ` +
|
||||||
|
`on the private network so ${spec.app} has an address ombi can dial`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||||
|
return { ok: false, problem: `the ${spec.provision} binding serves no usable port (${String(serves.port)})` };
|
||||||
|
}
|
||||||
|
const scheme = typeof serves.scheme === "string" && serves.scheme ? serves.scheme : "http";
|
||||||
|
if (scheme !== "http" && scheme !== "https") {
|
||||||
|
return { ok: false, problem: `the ${spec.provision} binding serves scheme ${scheme}, which ombi cannot dial` };
|
||||||
|
}
|
||||||
|
const key = (credential ?? "").trim();
|
||||||
|
if (!key) {
|
||||||
|
return { ok: false, problem: `the ${spec.provision} credential is empty or was not delivered` };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
from: typeof binding.from === "string" ? binding.from : "",
|
||||||
|
connection: { ip: at, port, ssl: scheme === "https", subDir: subDirOf(serves["url-base"]), apiKey: key },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ombi's `subDir`: the URL base with its slashes trimmed, null when there is none. */
|
||||||
|
export function subDirOf(urlBase: unknown): string | null {
|
||||||
|
const trimmed = typeof urlBase === "string" ? urlBase.trim().replace(/^\/+|\/+$/g, "") : "";
|
||||||
|
return trimmed === "" ? null : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isLoopback(host: string): boolean {
|
||||||
|
const h = host.toLowerCase();
|
||||||
|
return h === "localhost" || h === "::1" || h === "[::1]" || /^127\./.test(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which connection fields differ between what ombi holds and what the mesh says. Names only. */
|
||||||
|
export function differing(current: Record<string, unknown> | undefined, want: Connection): (keyof Connection)[] {
|
||||||
|
const now = current ?? {};
|
||||||
|
const out: (keyof Connection)[] = [];
|
||||||
|
if (String(now.ip ?? "") !== want.ip) out.push("ip");
|
||||||
|
if (Number(now.port ?? 0) !== want.port) out.push("port");
|
||||||
|
if (Boolean(now.ssl) !== want.ssl) out.push("ssl");
|
||||||
|
if (subDirOf(now.subDir) !== want.subDir) out.push("subDir");
|
||||||
|
if (String(now.apiKey ?? "") !== want.apiKey) out.push("apiKey");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ombi's settings for the app with the connection laid over them and nothing else changed. */
|
||||||
|
export function withConnection(current: Record<string, unknown> | undefined, want: Connection): Record<string, unknown> {
|
||||||
|
return { ...(current ?? {}), ip: want.ip, port: want.port, ssl: want.ssl, subDir: want.subDir, apiKey: want.apiKey };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's base URL as the step dials it — the same host and port ombi will be given. */
|
||||||
|
export function appUrl(want: Connection): string {
|
||||||
|
const scheme = want.ssl ? "https" : "http";
|
||||||
|
const host = want.ip.includes(":") && !want.ip.startsWith("[") ? `[${want.ip}]` : want.ip;
|
||||||
|
return `${scheme}://${host}:${want.port}${want.subDir ? `/${want.subDir}` : ""}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How one app came out. */
|
||||||
|
export type Outcome =
|
||||||
|
| { app: string; result: "unchanged" }
|
||||||
|
| { app: string; result: "written"; fields: string[] }
|
||||||
|
| { app: string; result: "refused"; problem: string };
|
||||||
|
|
||||||
|
/** The HTTP the step needs, so a test can stand fakes in for ombi and the apps. */
|
||||||
|
export interface Http {
|
||||||
|
fetch(url: string, init?: { method?: string; headers?: Record<string, string>; body?: string }): Promise<{
|
||||||
|
status: number;
|
||||||
|
text(): Promise<string>;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Ombi {
|
||||||
|
url: string;
|
||||||
|
apiKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ombiCall(http: Http, ombi: Ombi, method: string, path: string, body?: unknown): Promise<unknown> {
|
||||||
|
const res = await http.fetch(`${ombi.url.replace(/\/$/, "")}/api/v1${path}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
ApiKey: ombi.apiKey,
|
||||||
|
Accept: "application/json",
|
||||||
|
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||||
|
},
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
if (res.status < 200 || res.status >= 300) {
|
||||||
|
// The body is ombi's error, never a request echo, so it carries no key.
|
||||||
|
throw new Error(`ombi ${method} ${path} answered ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
||||||
|
}
|
||||||
|
return text ? (JSON.parse(text) as unknown) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does the app take this key? `true` it does, `false` it refused it (401/403), and a thrown error
|
||||||
|
* when it could not be asked — unreachable, or answering something that is neither.
|
||||||
|
*/
|
||||||
|
export async function appTakes(http: Http, spec: ServarrApp, want: Connection): Promise<boolean> {
|
||||||
|
const res = await http.fetch(`${appUrl(want)}${spec.statusPath}`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: { "X-Api-Key": want.apiKey, Accept: "application/json" },
|
||||||
|
});
|
||||||
|
if (res.status === 401 || res.status === 403) return false;
|
||||||
|
if (res.status >= 200 && res.status < 300) return true;
|
||||||
|
throw new Error(`${spec.app} answered ${res.status} at ${spec.statusPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The remedy for a refused key, in the controller's own words (ADR 0092). */
|
||||||
|
export function acceptRemedy(spec: ServarrApp, from: string): string {
|
||||||
|
return (
|
||||||
|
`${spec.app} refuses the ${spec.provision} credential the mesh delivered, so it was not written ` +
|
||||||
|
`into ombi. A Servarr app has one API key and the mesh cannot make it: accept ${spec.app}'s own ` +
|
||||||
|
`key for this pair — \`secret accept <this node> ombi ${spec.provision} --provider ${from || "<its node>"} ` +
|
||||||
|
`--from <file holding ${spec.app}'s ApiKey>\``
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring ombi's connection to one app in line with the mesh: check the key against the app, compare,
|
||||||
|
* write only the connection fields when they differ, then have ombi test the connection from its own
|
||||||
|
* container. Never throws: every failure is an outcome with a reason.
|
||||||
|
*/
|
||||||
|
export async function reconcileApp(
|
||||||
|
http: Http,
|
||||||
|
ombi: Ombi,
|
||||||
|
spec: ServarrApp,
|
||||||
|
binding: Binding | undefined,
|
||||||
|
credential: string | undefined,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
const w = wanted(spec, binding, credential);
|
||||||
|
// `in`, not `!w.ok`: the Dockerfile compiles without strict, where a boolean discriminant does not
|
||||||
|
// narrow.
|
||||||
|
if ("problem" in w) return { app: spec.app, result: "refused", problem: w.problem };
|
||||||
|
const want = w.connection;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!(await appTakes(http, spec, want))) {
|
||||||
|
return { app: spec.app, result: "refused", problem: acceptRemedy(spec, w.from) };
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return {
|
||||||
|
app: spec.app,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${spec.app} could not be asked whether it takes the key at ${want.ip}:${want.port}: ${message(err)}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const document = (await ombiCall(http, ombi, "GET", `/Settings/${spec.app}`)) as Record<string, unknown> | undefined;
|
||||||
|
const current = spec.within ? (document?.[spec.within] as Record<string, unknown> | undefined) : document;
|
||||||
|
const fields = differing(current, want);
|
||||||
|
if (fields.length > 0) {
|
||||||
|
const next = withConnection(current, want);
|
||||||
|
const body = spec.within ? { ...(document ?? {}), [spec.within]: next } : next;
|
||||||
|
const saved = await ombiCall(http, ombi, "POST", `/Settings/${spec.app}`, body);
|
||||||
|
if (saved === false) {
|
||||||
|
return { app: spec.app, result: "refused", problem: `ombi declined to save its ${spec.app} settings` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ombi's own test, from ombi's own container — the path the step's check above did not take.
|
||||||
|
const tested = (await ombiCall(http, ombi, "POST", `/Tester/${spec.app}`, withConnection(current, want))) as
|
||||||
|
| { isValid?: boolean; expectedSubDir?: string | null }
|
||||||
|
| undefined;
|
||||||
|
if (!tested?.isValid) {
|
||||||
|
const hint = tested?.expectedSubDir ? ` (ombi expected the base path ${tested.expectedSubDir})` : "";
|
||||||
|
return {
|
||||||
|
app: spec.app,
|
||||||
|
result: "refused",
|
||||||
|
problem:
|
||||||
|
`ombi cannot reach ${spec.app} at ${want.ip}:${want.port} from its own container${hint}` +
|
||||||
|
(fields.length > 0 ? `; its settings were written (${fields.join(", ")})` : ""),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return fields.length > 0 ? { app: spec.app, result: "written", fields } : { app: spec.app, result: "unchanged" };
|
||||||
|
} catch (err) {
|
||||||
|
return { app: spec.app, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait for ombi to answer, because the step runs right after its container starts. */
|
||||||
|
export async function ombiReady(http: Http, ombi: Ombi, waitMs: number, pauseMs = 2000): Promise<boolean> {
|
||||||
|
const until = Date.now() + waitMs;
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
const res = await http.fetch(`${ombi.url.replace(/\/$/, "")}/api/v1/Status`, { method: "GET" });
|
||||||
|
if (res.status === 200) return true;
|
||||||
|
} catch {
|
||||||
|
// not listening yet
|
||||||
|
}
|
||||||
|
if (Date.now() >= until) return false;
|
||||||
|
await new Promise((r) => setTimeout(r, pauseMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A file the mesh wrote, or undefined when it is not there. */
|
||||||
|
export async function readIfThere(path: string | undefined): Promise<string | undefined> {
|
||||||
|
if (!path) return undefined;
|
||||||
|
return readFile(path, "utf8").catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A binding file parsed, or undefined when absent or not JSON. */
|
||||||
|
export async function readBinding(path: string | undefined): Promise<Binding | undefined> {
|
||||||
|
const raw = await readIfThere(path);
|
||||||
|
if (raw === undefined) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as Binding;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(err: unknown): string {
|
||||||
|
return err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
// What holds ombi's Plex step (plex/settings.ts): the entry for the server plex says it is — found
|
||||||
|
// by machineIdentifier — is made to say what the mesh bound (host, port, TLS, token) and nothing
|
||||||
|
// else it keeps is touched; an entry for another server is left alone; an ombi with no entry for it
|
||||||
|
// gets one; nothing is written when nothing differs; and a token plex refuses (the mesh's own minted
|
||||||
|
// value, before the operator accepts the server's token) is never written, with the `secret accept`
|
||||||
|
// that fixes it named.
|
||||||
|
//
|
||||||
|
// ombi and plex are fakes answering the routes the step touches as the real ones do (checked against
|
||||||
|
// lscr.io/linuxserver/ombi 4.53.10 and plexinc/pms-docker 1.43.4: plex answers 401 to an unknown
|
||||||
|
// token from another network and 400 on one it trusts; ombi's /Tester/plex answers a bare boolean).
|
||||||
|
//
|
||||||
|
// Imports the compiled step, as keycloak's tests do: plex/settings.ts imports its sibling with the
|
||||||
|
// `.js` specifier the build needs, which Node's type stripping does not resolve to a `.ts` file.
|
||||||
|
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
|
||||||
|
import { differingPlex, reconcilePlex, wantedPlex, withPlexServer } from "../dist/plex/settings.js";
|
||||||
|
import type { Binding, Http } from "../servarr/settings.ts";
|
||||||
|
|
||||||
|
const TOKEN = "the-servers-own-token";
|
||||||
|
const MACHINE = "5c47d9a165d10b622995d55b3ae1f168242f33bd";
|
||||||
|
const OMBI = { url: "http://127.0.0.1:3579", apiKey: "ombi-key" };
|
||||||
|
|
||||||
|
function binding(port = 32400, at = "ace.internal", scheme = "http"): Binding {
|
||||||
|
return { binding: 1, provision: "plex-api", from: "ace", at, as: "mesh_ace_ombi", serves: { scheme, port } } as Binding;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Call {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
body?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fakes(plexSettings: Record<string, unknown>, opts: { reachable?: boolean; trusted?: boolean } = {}) {
|
||||||
|
const calls: Call[] = [];
|
||||||
|
const store = { plex: plexSettings };
|
||||||
|
const http: Http = {
|
||||||
|
async fetch(url, init) {
|
||||||
|
const method = init?.method ?? "GET";
|
||||||
|
const body = init?.body ? (JSON.parse(init.body) as unknown) : undefined;
|
||||||
|
calls.push({ method, url, body });
|
||||||
|
const reply = (status: number, value?: unknown) => ({
|
||||||
|
status,
|
||||||
|
text: async () => (value === undefined ? "" : JSON.stringify(value)),
|
||||||
|
});
|
||||||
|
const u = new URL(url);
|
||||||
|
// Other servers an entry may name: a friend's, and plex's own public name (the same server).
|
||||||
|
if (u.hostname === "10.0.0.9") return reply(200, { MediaContainer: { machineIdentifier: "another-server" } });
|
||||||
|
if (u.hostname === "gone.example") throw new Error("getaddrinfo ENOTFOUND");
|
||||||
|
if (u.hostname === "plex.zurag.be") {
|
||||||
|
if (u.pathname === "/identity") return reply(200, { MediaContainer: { machineIdentifier: MACHINE } });
|
||||||
|
return reply(401);
|
||||||
|
}
|
||||||
|
if (u.port === "32400" || u.hostname === "ace.internal") {
|
||||||
|
if (opts.reachable === false) throw new Error("connect ECONNREFUSED");
|
||||||
|
if (u.pathname === "/identity") return reply(200, { MediaContainer: { machineIdentifier: MACHINE } });
|
||||||
|
const token = init?.headers?.["X-Plex-Token"];
|
||||||
|
if (token !== TOKEN) return reply(opts.trusted ? 400 : 401);
|
||||||
|
return reply(200, { MediaContainer: { friendlyName: "ace", machineIdentifier: MACHINE } });
|
||||||
|
}
|
||||||
|
if (init?.headers?.ApiKey !== "ombi-key") return reply(401);
|
||||||
|
if (u.pathname === "/api/v1/Settings/Plex" && method === "GET") return reply(200, store.plex);
|
||||||
|
if (u.pathname === "/api/v1/Settings/Plex" && method === "POST") {
|
||||||
|
store.plex = body as Record<string, unknown>;
|
||||||
|
return reply(200, true);
|
||||||
|
}
|
||||||
|
if (u.pathname === "/api/v1/Tester/plex") {
|
||||||
|
const tried = body as { plexAuthToken?: string; ip?: string };
|
||||||
|
return reply(200, tried.plexAuthToken === TOKEN && tried.ip === "ace.internal");
|
||||||
|
}
|
||||||
|
return reply(404);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { http, calls, store };
|
||||||
|
}
|
||||||
|
|
||||||
|
// What an operator's ombi holds: plex loaded through its public name, plus a friend's server.
|
||||||
|
const operatorPlex = () => ({
|
||||||
|
enable: true,
|
||||||
|
enableWatchlistImport: true,
|
||||||
|
monitorAll: false,
|
||||||
|
installId: "b358a2a2-2ab0-4025-a3f3-450313c3c418",
|
||||||
|
servers: [
|
||||||
|
{
|
||||||
|
name: "ace", plexAuthToken: TOKEN, machineIdentifier: MACHINE, episodeBatchSize: 150,
|
||||||
|
serverHostname: "https://app.plex.tv", plexSelectedLibraries: [{ key: "1", title: "Films", enabled: true }],
|
||||||
|
ssl: true, subDir: null, ip: "plex.zurag.be", port: 443, id: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "a friend", plexAuthToken: "their-token", machineIdentifier: "another-server", episodeBatchSize: 150,
|
||||||
|
plexSelectedLibraries: [], ssl: false, subDir: null, ip: "10.0.0.9", port: 32400, id: 2,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
id: 4,
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the server's own entry gets the bound connection; its libraries and every other setting stay", async () => {
|
||||||
|
const f = fakes(operatorPlex());
|
||||||
|
const out = await reconcilePlex(f.http, OMBI, binding(), `${TOKEN}\n`);
|
||||||
|
assert.deepEqual(out, { app: "plex", result: "written", fields: ["ip", "port", "ssl"] });
|
||||||
|
const want = operatorPlex();
|
||||||
|
Object.assign(want.servers[0], { ip: "ace.internal", port: 32400, ssl: false });
|
||||||
|
assert.deepEqual(f.store.plex, want);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("another server's entry is never touched", async () => {
|
||||||
|
const f = fakes(operatorPlex());
|
||||||
|
await reconcilePlex(f.http, OMBI, binding(), TOKEN);
|
||||||
|
const servers = f.store.plex.servers as Record<string, unknown>[];
|
||||||
|
assert.deepEqual(servers[1], operatorPlex().servers[1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("nothing is written when ombi already says what the mesh says", async () => {
|
||||||
|
const doc = operatorPlex();
|
||||||
|
Object.assign(doc.servers[0], { ip: "ace.internal", port: 32400, ssl: false });
|
||||||
|
const f = fakes(doc);
|
||||||
|
const out = await reconcilePlex(f.http, OMBI, binding(), TOKEN);
|
||||||
|
assert.deepEqual(out, { app: "plex", result: "unchanged" });
|
||||||
|
assert.equal(f.calls.filter((c) => c.method === "POST" && c.url.includes("/Settings/")).length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an ombi with no entry for this server gets one, named as plex names itself", async () => {
|
||||||
|
const fresh = { enable: false, enableWatchlistImport: false, monitorAll: false, installId: "x", servers: null, id: 0 };
|
||||||
|
const f = fakes(fresh);
|
||||||
|
const out = await reconcilePlex(f.http, OMBI, binding(), TOKEN);
|
||||||
|
assert.deepEqual(out, { app: "plex", result: "written", fields: ["server"] });
|
||||||
|
assert.deepEqual(f.store.plex, {
|
||||||
|
...fresh,
|
||||||
|
servers: [{
|
||||||
|
name: "ace", machineIdentifier: MACHINE, ip: "ace.internal", port: 32400, ssl: false, subDir: null,
|
||||||
|
plexAuthToken: TOKEN, episodeBatchSize: 150, plexSelectedLibraries: [],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
assert.equal(f.store.plex.enable, false, "whether plex is enabled in ombi is the operator's choice");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a token plex refuses is never written, and the accept that fixes it is named", async () => {
|
||||||
|
for (const trusted of [false, true]) {
|
||||||
|
const f = fakes(operatorPlex(), { trusted });
|
||||||
|
const out = await reconcilePlex(f.http, OMBI, binding(), "a-value-the-mesh-minted");
|
||||||
|
assert.equal(out.result, "refused");
|
||||||
|
const problem = (out as { problem: string }).problem;
|
||||||
|
assert.match(problem, /secret accept <this node> ombi plex-api --provider ace/);
|
||||||
|
assert.doesNotMatch(problem, /a-value-the-mesh-minted/);
|
||||||
|
assert.deepEqual(f.store.plex, operatorPlex(), "ombi's working settings were left alone");
|
||||||
|
assert.equal(f.calls.some((c) => c.url.includes("/api/v1/")), false, "ombi was not even asked");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a plex it cannot reach is reported, and ombi is left alone", async () => {
|
||||||
|
const f = fakes(operatorPlex(), { reachable: false });
|
||||||
|
const out = await reconcilePlex(f.http, OMBI, binding(), TOKEN);
|
||||||
|
assert.equal(out.result, "refused");
|
||||||
|
assert.match((out as { problem: string }).problem, /could not be asked.*ECONNREFUSED/);
|
||||||
|
assert.deepEqual(f.store.plex, operatorPlex());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a loopback binding is refused: from ombi's container it is ombi itself", () => {
|
||||||
|
const w = wantedPlex(binding(32400, "127.0.0.1"), TOKEN);
|
||||||
|
assert.equal(w.ok, false);
|
||||||
|
assert.match((w as { problem: string }).problem, /private network/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an https binding sets ombi's ssl flag; an empty subDir is none", () => {
|
||||||
|
const w = wantedPlex(binding(32400, "ace.internal", "https"), TOKEN);
|
||||||
|
assert.equal(w.ok && w.connection.ssl, true);
|
||||||
|
assert.deepEqual(
|
||||||
|
differingPlex({ ip: "h", port: 1, ssl: false, subDir: "", plexAuthToken: "k" }, { ip: "h", port: 1, ssl: false, subDir: null, plexAuthToken: "k" }),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("every entry naming the server is laid over, not only the first", () => {
|
||||||
|
const doc = { servers: [{ machineIdentifier: MACHINE, ip: "a" }, { machineIdentifier: MACHINE, ip: "b" }] };
|
||||||
|
const want = { ip: "ace.internal", port: 32400, ssl: false, subDir: null, plexAuthToken: TOKEN };
|
||||||
|
const laid = withPlexServer(doc, MACHINE, want, "ace");
|
||||||
|
assert.equal(laid.added, false);
|
||||||
|
assert.deepEqual((laid.next.servers as { ip: string }[]).map((s) => s.ip), ["ace.internal", "ace.internal"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ace's own ombi: its one entry was loaded from an older server (a stale identifier) and retyped to
|
||||||
|
// plex's public name, so it IS this server, reached another way (read from ace, 2026-09-30).
|
||||||
|
const acesOmbi = () => ({
|
||||||
|
enable: true,
|
||||||
|
enableWatchlistImport: true,
|
||||||
|
servers: [{
|
||||||
|
name: "Nami", plexAuthToken: TOKEN, machineIdentifier: "76562198623e708eef85b46aedb72c8f2fe671aa", episodeBatchSize: 0,
|
||||||
|
plexSelectedLibraries: [1, 2, 3, 4, 5, 6].map((k) => ({ key: String(k), enabled: true })), ssl: true, subDir: null,
|
||||||
|
ip: "plex.zurag.be", port: 443, id: 1,
|
||||||
|
}],
|
||||||
|
id: 4,
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an entry whose own address answers as this server is adopted: connection and identifier, nothing else", async () => {
|
||||||
|
const f = fakes(acesOmbi());
|
||||||
|
const out = await reconcilePlex(f.http, OMBI, binding(), TOKEN);
|
||||||
|
assert.deepEqual(out, { app: "plex", result: "written", fields: ["ip", "port", "ssl", "machineIdentifier"] });
|
||||||
|
const want = acesOmbi();
|
||||||
|
Object.assign(want.servers[0], { ip: "ace.internal", port: 32400, ssl: false, machineIdentifier: MACHINE });
|
||||||
|
assert.deepEqual(f.store.plex, want, "one entry, still named Nami, its six libraries kept; none added");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an entry answering as another server, or not at all, is not adopted; this server gets its own", async () => {
|
||||||
|
const doc = {
|
||||||
|
servers: [
|
||||||
|
{ name: "a friend", machineIdentifier: "stale-1", ip: "10.0.0.9", port: 32400, ssl: false, plexAuthToken: "theirs" },
|
||||||
|
{ name: "gone", machineIdentifier: "stale-2", ip: "gone.example", port: 32400, ssl: false, plexAuthToken: "old" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const f = fakes(structuredClone(doc));
|
||||||
|
const out = await reconcilePlex(f.http, OMBI, binding(), TOKEN);
|
||||||
|
assert.deepEqual(out, { app: "plex", result: "written", fields: ["server"] });
|
||||||
|
const servers = f.store.plex.servers as Record<string, unknown>[];
|
||||||
|
assert.deepEqual(servers.slice(0, 2), doc.servers, "both left exactly as they were");
|
||||||
|
assert.equal(servers[2].machineIdentifier, MACHINE);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("no entry is probed once one carries the server's identifier", async () => {
|
||||||
|
const f = fakes(operatorPlex());
|
||||||
|
await reconcilePlex(f.http, OMBI, binding(), TOKEN);
|
||||||
|
assert.equal(f.calls.some((c) => c.url.startsWith("http://10.0.0.9")), false, "the friend's server was not asked");
|
||||||
|
});
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
// What holds ombi's Servarr step (servarr/settings.ts): the connection ombi keeps for each app is
|
||||||
|
// made to say what the mesh bound — host, port, TLS, base path, key — and nothing else it keeps is
|
||||||
|
// touched; nothing is written when nothing differs; Radarr's 4K instance is left alone; and a key the
|
||||||
|
// app refuses (the mesh's own minted value, before the operator accepts the app's key) is never
|
||||||
|
// written, with the `secret accept` that fixes it named.
|
||||||
|
//
|
||||||
|
// ombi and the apps are fakes: the routes the step touches, answering as the real ones do (checked
|
||||||
|
// against lscr.io/linuxserver/ombi 4.53.10 and the catalogue's pinned sonarr/radarr/lidarr).
|
||||||
|
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
|
||||||
|
import { APPS, differing, reconcileApp, subDirOf, wanted, type Binding, type Http, type ServarrApp } from "../servarr/settings.ts";
|
||||||
|
|
||||||
|
const SONARR = APPS.find((a) => a.app === "sonarr") as ServarrApp;
|
||||||
|
const RADARR = APPS.find((a) => a.app === "radarr") as ServarrApp;
|
||||||
|
const LIDARR = APPS.find((a) => a.app === "lidarr") as ServarrApp;
|
||||||
|
const THE_KEY = "the-apps-own-key";
|
||||||
|
|
||||||
|
function binding(provision: string, port: number, at = "ace.internal"): Binding {
|
||||||
|
return { binding: 1, provision, from: "ace", at, as: "mesh_ace_ombi", serves: { scheme: "http", port, "url-base": "" } } as Binding;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Call {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
body?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ombi's settings store and the apps' key check, behind one fetch. */
|
||||||
|
function fakes(settings: Record<string, unknown>, opts: { appKey?: string; reachable?: boolean } = {}) {
|
||||||
|
const calls: Call[] = [];
|
||||||
|
const appKey = opts.appKey ?? THE_KEY;
|
||||||
|
const http: Http = {
|
||||||
|
async fetch(url, init) {
|
||||||
|
const method = init?.method ?? "GET";
|
||||||
|
const body = init?.body ? (JSON.parse(init.body) as unknown) : undefined;
|
||||||
|
calls.push({ method, url, body });
|
||||||
|
const reply = (status: number, value?: unknown) => ({
|
||||||
|
status,
|
||||||
|
text: async () => (value === undefined ? "" : JSON.stringify(value)),
|
||||||
|
});
|
||||||
|
const u = new URL(url);
|
||||||
|
if (u.pathname.endsWith("/system/status")) {
|
||||||
|
if (opts.reachable === false) throw new Error("connect ECONNREFUSED");
|
||||||
|
return init?.headers?.["X-Api-Key"] === appKey ? reply(200, { version: "4" }) : reply(401);
|
||||||
|
}
|
||||||
|
if (init?.headers?.ApiKey !== "ombi-key") return reply(401);
|
||||||
|
const m = u.pathname.match(/^\/api\/v1\/(Settings|Tester)\/(\w+)$/);
|
||||||
|
if (!m) return reply(404);
|
||||||
|
const [, kind, app] = m;
|
||||||
|
if (kind === "Settings" && method === "GET") return reply(200, settings[app]);
|
||||||
|
if (kind === "Settings" && method === "POST") {
|
||||||
|
settings[app] = body;
|
||||||
|
return reply(200, true);
|
||||||
|
}
|
||||||
|
const tried = body as { apiKey?: string };
|
||||||
|
return reply(200, { isValid: tried.apiKey === appKey, expectedSubDir: null });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { http, calls, settings };
|
||||||
|
}
|
||||||
|
|
||||||
|
const OMBI = { url: "http://127.0.0.1:3579", apiKey: "ombi-key" };
|
||||||
|
|
||||||
|
const operatorSonarr = () => ({
|
||||||
|
enabled: true, apiKey: "old-key", qualityProfile: "3", seasonFolders: true, rootPath: "10",
|
||||||
|
qualityProfileAnime: "7", rootPathAnime: "9", languageProfile: 1, ssl: false, subDir: null,
|
||||||
|
ip: "sonarr", port: 8989, id: 5,
|
||||||
|
});
|
||||||
|
|
||||||
|
test("it writes the connection the mesh bound, and keeps every other setting ombi had", async () => {
|
||||||
|
const f = fakes({ sonarr: operatorSonarr() });
|
||||||
|
const out = await reconcileApp(f.http, OMBI, SONARR, binding("sonarr-api", 20101), `${THE_KEY}\n`);
|
||||||
|
assert.deepEqual(out, { app: "sonarr", result: "written", fields: ["ip", "port", "apiKey"] });
|
||||||
|
assert.deepEqual(f.settings.sonarr, {
|
||||||
|
...operatorSonarr(), ip: "ace.internal", port: 20101, apiKey: THE_KEY, ssl: false, subDir: null,
|
||||||
|
});
|
||||||
|
// Checked against the app itself, at the bound address, before anything was written.
|
||||||
|
assert.equal(f.calls[0].url, "http://ace.internal:20101/api/v3/system/status");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("nothing is written when ombi already says what the mesh says", async () => {
|
||||||
|
const f = fakes({ sonarr: { ...operatorSonarr(), ip: "ace.internal", port: 20101, apiKey: THE_KEY } });
|
||||||
|
const out = await reconcileApp(f.http, OMBI, SONARR, binding("sonarr-api", 20101), THE_KEY);
|
||||||
|
assert.deepEqual(out, { app: "sonarr", result: "unchanged" });
|
||||||
|
assert.equal(f.calls.filter((c) => c.method === "POST" && c.url.includes("/Settings/")).length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a key the app refuses is never written, and the accept that fixes it is named", async () => {
|
||||||
|
const f = fakes({ sonarr: operatorSonarr() });
|
||||||
|
const out = await reconcileApp(f.http, OMBI, SONARR, binding("sonarr-api", 20101), "a-value-the-mesh-minted");
|
||||||
|
assert.equal(out.result, "refused");
|
||||||
|
assert.match((out as { problem: string }).problem, /secret accept <this node> ombi sonarr-api --provider ace/);
|
||||||
|
assert.doesNotMatch((out as { problem: string }).problem, /a-value-the-mesh-minted/);
|
||||||
|
assert.deepEqual(f.settings.sonarr, operatorSonarr(), "ombi's working settings were left alone");
|
||||||
|
assert.equal(f.calls.some((c) => c.url.includes("/api/v1/")), false, "ombi was not even asked");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an app it cannot reach is reported, and ombi is left alone", async () => {
|
||||||
|
const f = fakes({ sonarr: operatorSonarr() }, { reachable: false });
|
||||||
|
const out = await reconcileApp(f.http, OMBI, SONARR, binding("sonarr-api", 20101), THE_KEY);
|
||||||
|
assert.equal(out.result, "refused");
|
||||||
|
assert.match((out as { problem: string }).problem, /could not be asked.*ECONNREFUSED/);
|
||||||
|
assert.deepEqual(f.settings.sonarr, operatorSonarr());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("radarr's connection is written inside its combined document, and the 4K instance is untouched", async () => {
|
||||||
|
const fourK = { enabled: true, apiKey: "4k-key", ip: "radarr4k", port: 7879, defaultQualityProfile: "9", id: 7 };
|
||||||
|
const f = fakes({ radarr: { radarr: { enabled: true, apiKey: "old", ip: "radarr", port: 7878, defaultRootPath: "/movies", id: 6 }, radarr4K: fourK } });
|
||||||
|
const out = await reconcileApp(f.http, OMBI, RADARR, binding("radarr-api", 20102), THE_KEY);
|
||||||
|
assert.equal(out.result, "written");
|
||||||
|
const doc = f.settings.radarr as { radarr: Record<string, unknown>; radarr4K: unknown };
|
||||||
|
assert.deepEqual(doc.radarr4K, fourK);
|
||||||
|
assert.equal(doc.radarr.ip, "ace.internal");
|
||||||
|
assert.equal(doc.radarr.port, 20102);
|
||||||
|
assert.equal(doc.radarr.defaultRootPath, "/movies");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("lidarr is checked on its own API version", async () => {
|
||||||
|
const f = fakes({ lidarr: { enabled: true, apiKey: null, ip: null, port: 0, id: 0 } });
|
||||||
|
const out = await reconcileApp(f.http, OMBI, LIDARR, binding("lidarr-api", 20103), THE_KEY);
|
||||||
|
assert.equal(out.result, "written");
|
||||||
|
assert.equal(f.calls[0].url, "http://ace.internal:20103/api/v1/system/status");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a loopback binding is refused: from ombi's container it is ombi itself", () => {
|
||||||
|
const w = wanted(SONARR, binding("sonarr-api", 20101, "127.0.0.1"), THE_KEY);
|
||||||
|
assert.equal(w.ok, false);
|
||||||
|
assert.match((w as { problem: string }).problem, /private network/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the base path is ombi's subDir, slashes trimmed; empty is none", () => {
|
||||||
|
assert.equal(subDirOf(""), null);
|
||||||
|
assert.equal(subDirOf("/sonarr/"), "sonarr");
|
||||||
|
assert.deepEqual(
|
||||||
|
differing({ ip: "h", port: 1, ssl: false, subDir: "", apiKey: "k" }, { ip: "h", port: 1, ssl: false, subDir: null, apiKey: "k" }),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an https binding sets ombi's ssl flag", () => {
|
||||||
|
const b = binding("sonarr-api", 443);
|
||||||
|
(b.serves as Record<string, unknown>).scheme = "https";
|
||||||
|
const w = wanted(SONARR, b, THE_KEY);
|
||||||
|
assert.equal(w.ok && w.connection.ssl, true);
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
// ombi's tools — its own code (novox/hq ADR 0039), importing ombi's 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 { OmbiClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getOmbiTools(ombi: OmbiClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "ombi_requests",
|
||||||
|
description: "List media requests — movies and shows — with who asked and whether each is approved or available.",
|
||||||
|
input: { pending: { type: "boolean", description: "only requests not yet approved (default false)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
let requests = await ombi.getRequests();
|
||||||
|
if (args.pending) requests = requests.filter((r) => !r.approved && !r.denied);
|
||||||
|
const counts = await ombi.getCounts();
|
||||||
|
return { counts, count: requests.length, requests };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "ombi_approve",
|
||||||
|
description: "Approve a media request by its kind and id (from ombi_requests).",
|
||||||
|
input: {
|
||||||
|
kind: { type: "string", description: '"movie" or "tv"' },
|
||||||
|
id: { type: "number", description: "the request id" },
|
||||||
|
},
|
||||||
|
run: async (args) => {
|
||||||
|
const kind = String(args.kind);
|
||||||
|
if (kind !== "movie" && kind !== "tv") throw new Error('kind must be "movie" or "tv"');
|
||||||
|
const id = Number(args.id);
|
||||||
|
await ombi.approve(kind, id);
|
||||||
|
return { approved: { kind, id } };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exposed only when Ombi is configured; otherwise ombi contributes no tools rather than failing the
|
||||||
|
// whole runtime.
|
||||||
|
registerModuleTools("ombi", (env) => {
|
||||||
|
try {
|
||||||
|
return getOmbiTools(OmbiClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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", "servarr/settings.ts", "plex/settings.ts", "connections/index.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# plex's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/plex
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/plex/dist /app/modules/plex/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/plex/dist/index.js,/app/modules/plex/dist/tools/index.js
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
// The Plex API client — plex's own code, living in the module (novox/hq ADR 0039). Moved out of the
|
||||||
|
// shared hal sdk, where a change to Plex's API rebuilt everything; here it rebuilds only plex. Both
|
||||||
|
// this module's tools and its events entrypoint import it, and nothing outside plex does.
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
/** Read a secret the mesh mounted at a file path (an own-secret); absent or unreadable yields
|
||||||
|
* undefined, so callers can fall back rather than crash. */
|
||||||
|
function readSecret(path: string | undefined): string | undefined {
|
||||||
|
if (!path) return undefined;
|
||||||
|
try {
|
||||||
|
return readFileSync(path, "utf8").trim();
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlexLibrary {
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
type: string;
|
||||||
|
count?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlexSession {
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
user: string;
|
||||||
|
player: string;
|
||||||
|
state: string;
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlexItem {
|
||||||
|
title: string;
|
||||||
|
type: string;
|
||||||
|
year?: number;
|
||||||
|
summary?: string;
|
||||||
|
addedAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PlexClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly token: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the module's resolved environment. The token is read from MESH_PLEX_TOKEN, or
|
||||||
|
* discovered from the server's own Preferences.xml under the data directory — the same file Plex
|
||||||
|
* writes it to, so a running server needs nothing configured by hand.
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): PlexClient {
|
||||||
|
const url = env.MESH_PLEX_URL ?? `http://127.0.0.1:${env.PLEX_PORT ?? "32400"}`;
|
||||||
|
const dataDir = env.MESH_PLEX_DATA_DIR ?? "/var/lib/plex";
|
||||||
|
// The manifest sets neither MESH_PLEX_TOKEN_FILE nor MESH_PLEX_TOKEN: the server already keeps its
|
||||||
|
// token in Preferences.xml, read here through the manifest's read-only mount of the config dir.
|
||||||
|
// A token the mesh minted would be one plex.tv never issued, and preferring it would break every
|
||||||
|
// call, so the module declares no token secret. The file and env overrides stay for hand runs.
|
||||||
|
const token = readSecret(env.MESH_PLEX_TOKEN_FILE) ?? env.MESH_PLEX_TOKEN ?? PlexClient.detectToken(dataDir);
|
||||||
|
if (!token) throw new Error("no Plex token — set MESH_PLEX_TOKEN or make the data dir readable");
|
||||||
|
return new PlexClient(url, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Discover the token from the server's Preferences.xml, falling back to null. */
|
||||||
|
static detectToken(dataDir: string): string | null {
|
||||||
|
const prefs = join(dataDir, "config", "Library", "Application Support", "Plex Media Server", "Preferences.xml");
|
||||||
|
if (existsSync(prefs)) {
|
||||||
|
const match = readFileSync(prefs, "utf8").match(/PlexOnlineToken="([^"]+)"/);
|
||||||
|
if (match) return match[1];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async get(path: string): Promise<any> {
|
||||||
|
const url = `${this.baseUrl}${path}`;
|
||||||
|
const sep = url.includes("?") ? "&" : "?";
|
||||||
|
const res = await fetch(`${url}${sep}X-Plex-Token=${this.token}`, { headers: { Accept: "application/json" } });
|
||||||
|
if (!res.ok) throw new Error(`Plex API ${path}: ${res.status} ${await res.text()}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServerInfo(): Promise<{ name: string; version: string; platform: string }> {
|
||||||
|
const mc = (await this.get("/")).MediaContainer;
|
||||||
|
return { name: mc.friendlyName || mc.machineIdentifier, version: mc.version, platform: mc.platform };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLibraries(): Promise<PlexLibrary[]> {
|
||||||
|
const dirs = (await this.get("/library/sections")).MediaContainer?.Directory ?? [];
|
||||||
|
return dirs.map((d: any) => ({ key: d.key, title: d.title, type: d.type, count: d.count }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSessions(): Promise<PlexSession[]> {
|
||||||
|
const sessions = (await this.get("/status/sessions")).MediaContainer?.Metadata ?? [];
|
||||||
|
return sessions.map((s: any) => ({
|
||||||
|
key: s.sessionKey ?? s.ratingKey,
|
||||||
|
title: s.title + (s.grandparentTitle ? ` (${s.grandparentTitle})` : ""),
|
||||||
|
user: s.User?.title ?? "unknown",
|
||||||
|
player: s.Player?.title ?? s.Player?.product ?? "unknown",
|
||||||
|
state: s.Player?.state ?? "unknown",
|
||||||
|
type: s.type,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async search(query: string): Promise<PlexItem[]> {
|
||||||
|
const hubs = (await this.get(`/hubs/search?query=${encodeURIComponent(query)}&limit=20`)).MediaContainer?.Hub ?? [];
|
||||||
|
const results: PlexItem[] = [];
|
||||||
|
for (const hub of hubs) {
|
||||||
|
for (const m of hub.Metadata ?? []) {
|
||||||
|
results.push({
|
||||||
|
title: m.title + (m.grandparentTitle ? ` (${m.grandparentTitle})` : ""),
|
||||||
|
type: m.type,
|
||||||
|
year: m.year,
|
||||||
|
summary: m.summary?.slice(0, 200),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getRecentlyAdded(limit = 20): Promise<PlexItem[]> {
|
||||||
|
const items = (await this.get(`/library/recentlyAdded?X-Plex-Container-Size=${limit}`)).MediaContainer?.Metadata ?? [];
|
||||||
|
return items.map((m: any) => ({
|
||||||
|
title: m.title + (m.grandparentTitle ? ` (${m.grandparentTitle})` : ""),
|
||||||
|
type: m.type,
|
||||||
|
year: m.year,
|
||||||
|
summary: m.summary?.slice(0, 200),
|
||||||
|
addedAt: m.addedAt ? new Date(m.addedAt * 1000).toISOString() : undefined,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ask Plex to rescan a library section — how a "new media arrived" event becomes a visible item. */
|
||||||
|
async refreshLibrary(key: string): Promise<void> {
|
||||||
|
await this.get(`/library/sections/${key}/refresh`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rescan every library, for when what arrived is not known to belong to one. */
|
||||||
|
async refreshAll(): Promise<void> {
|
||||||
|
for (const library of await this.getLibraries()) await this.refreshLibrary(library.key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A health probe that never throws: report whether the Plex server this client is pointed at
|
||||||
|
* answers, and identify it when it does. Every other call assumes the server is up; this is the
|
||||||
|
* one that tells the mesh whether it is, so a diagnosis does not start from a stack trace.
|
||||||
|
*/
|
||||||
|
async reachable(): Promise<{ reachable: boolean; url: string; server?: { name: string; version: string }; error?: string }> {
|
||||||
|
try {
|
||||||
|
const info = await this.getServerInfo();
|
||||||
|
return { reachable: true, url: this.baseUrl, server: { name: info.name, version: info.version } };
|
||||||
|
} catch (err) {
|
||||||
|
return { reachable: false, url: this.baseUrl, error: err instanceof Error ? err.message : String(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// plex's events. The tool runtime imports this once the broker is bound, and it does two things:
|
||||||
|
// it watches the server and emits what happened, and it reacts to the mesh's media events.
|
||||||
|
//
|
||||||
|
// Emits (novox/hq ADR 0041/0042):
|
||||||
|
// module.plex.playback.started / .stopped — someone began or ended watching
|
||||||
|
// module.plex.item.added — a new item appeared in a library
|
||||||
|
// Consumes:
|
||||||
|
// module.*.download.completed — a downloader finished; rescan so the file shows up
|
||||||
|
//
|
||||||
|
// The polling is deliberately unhurried: Plex is a neighbour on the same node, and an event a few
|
||||||
|
// seconds late is an event, whereas hammering the server for immediacy nobody asked for is not.
|
||||||
|
|
||||||
|
import { emit, on } from "@novox/mesh-sdk/events";
|
||||||
|
import { PlexClient, type PlexSession } from "./client.js";
|
||||||
|
|
||||||
|
const plex = PlexClient.fromEnv();
|
||||||
|
|
||||||
|
// Playback, by diffing the set of active sessions. Primed silently on the first look so a server
|
||||||
|
// that was already streaming when this started does not announce it as freshly begun.
|
||||||
|
const active = new Map<string, PlexSession>();
|
||||||
|
let playbackPrimed = false;
|
||||||
|
async function pollSessions(): Promise<void> {
|
||||||
|
const sessions = await plex.getSessions();
|
||||||
|
const now = new Map(sessions.map((s) => [s.key, s]));
|
||||||
|
if (playbackPrimed) {
|
||||||
|
for (const [key, s] of now) {
|
||||||
|
if (!active.has(key)) await emit("playback.started", { title: s.title, user: s.user, player: s.player, kind: s.type });
|
||||||
|
}
|
||||||
|
for (const [key, s] of active) {
|
||||||
|
if (!now.has(key)) await emit("playback.stopped", { title: s.title, user: s.user, player: s.player });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
active.clear();
|
||||||
|
for (const [key, s] of now) active.set(key, s);
|
||||||
|
playbackPrimed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// New items, by diffing recently-added. Primed silently too, or a restart would re-announce the
|
||||||
|
// whole recent list as new.
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let itemsPrimed = false;
|
||||||
|
async function pollRecent(): Promise<void> {
|
||||||
|
const items = await plex.getRecentlyAdded(20);
|
||||||
|
for (const item of items) {
|
||||||
|
const id = `${item.title}@${item.addedAt ?? ""}`;
|
||||||
|
if (!seen.has(id)) {
|
||||||
|
if (itemsPrimed) await emit("item.added", item);
|
||||||
|
seen.add(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
itemsPrimed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A downloader finished somewhere on the mesh: rescan, so what it fetched becomes a visible item
|
||||||
|
// rather than a file Plex has not noticed. Idempotent — a rescan too many costs a little disk I/O.
|
||||||
|
await on("*.download.completed", async () => {
|
||||||
|
await plex.refreshAll();
|
||||||
|
});
|
||||||
|
|
||||||
|
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||||
|
const run = (): void => void fn().catch((err) => console.error(`[plex] ${err}`));
|
||||||
|
setInterval(run, everyMs);
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
tick(pollSessions, 15_000);
|
||||||
|
tick(pollRecent, 60_000);
|
||||||
|
|
||||||
|
console.log("[plex] watching sessions and recently-added, reacting to downloads");
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
{
|
||||||
|
"module": "plex",
|
||||||
|
"version": "1",
|
||||||
|
"provides": [
|
||||||
|
{
|
||||||
|
"name": "plex-api",
|
||||||
|
"scope": "mesh"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"serves": {
|
||||||
|
"plex-api": {
|
||||||
|
"scheme": "http",
|
||||||
|
"port": 32400
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"playback.started",
|
||||||
|
"playback.stopped",
|
||||||
|
"item.added"
|
||||||
|
],
|
||||||
|
"consumes": [
|
||||||
|
"*.download.completed"
|
||||||
|
],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/plex/broker"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "stream",
|
||||||
|
"port": 32400,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "the server itself: the apps, streaming and the web player, direct and through its route"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "gdm-1",
|
||||||
|
"port": 32410,
|
||||||
|
"protocol": "udp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "G'Day Mate discovery: players on the same network find the server without signing in"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "gdm-2",
|
||||||
|
"port": 32412,
|
||||||
|
"protocol": "udp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "G'Day Mate discovery"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "gdm-3",
|
||||||
|
"port": 32413,
|
||||||
|
"protocol": "udp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "G'Day Mate discovery"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "gdm-4",
|
||||||
|
"port": 32414,
|
||||||
|
"protocol": "udp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "G'Day Mate discovery"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accesses": [
|
||||||
|
{
|
||||||
|
"path": "/services/media/movies",
|
||||||
|
"mode": "read"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/series",
|
||||||
|
"mode": "read"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/anime",
|
||||||
|
"mode": "read"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/music",
|
||||||
|
"mode": "read"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/audiobooks",
|
||||||
|
"mode": "read"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/sport-games",
|
||||||
|
"mode": "read"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/live-shows",
|
||||||
|
"mode": "read"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/formula-1",
|
||||||
|
"mode": "read"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/plex",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0755",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "data",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0755",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "transcode",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0755",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server-env",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/server.env",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "ADVERTISE_IP=https://${bound:route:name}/\n"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "plex",
|
||||||
|
"image": "plexinc/pms-docker@sha256:e0ab27395614a8e1a4fdf84c6bc60ac664915cfdde70c52d030c7728a1c48e14",
|
||||||
|
"network": "host",
|
||||||
|
"env": {
|
||||||
|
"PLEX_UID": "1000",
|
||||||
|
"PLEX_GID": "1000",
|
||||||
|
"TZ": "Etc/UTC"
|
||||||
|
},
|
||||||
|
"env-file": [
|
||||||
|
"${dir:state}/server.env"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"${dir:data}:/data",
|
||||||
|
"${dir:transcode}:/transcode",
|
||||||
|
"/services/media/movies:/movies:ro",
|
||||||
|
"/services/media/series:/series:ro",
|
||||||
|
"/services/media/anime:/anime:ro",
|
||||||
|
"/services/media/music:/music:ro",
|
||||||
|
"/services/media/audiobooks:/audiobooks:ro",
|
||||||
|
"/services/media/sport-games:/sport-games:ro",
|
||||||
|
"/services/media/live-shows:/live-shows:ro",
|
||||||
|
"/services/media/formula-1:/formula-1:ro"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-plex",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/plex/broker:/run/secrets/broker:ro",
|
||||||
|
"${dir:config}:/var/lib/plex/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_PLEX_URL": "http://127.0.0.1:${port:32400}",
|
||||||
|
"MESH_PLEX_DATA_DIR": "/var/lib/plex"
|
||||||
|
},
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requires": [
|
||||||
|
"route"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "plex",
|
||||||
|
"endpoint": "stream"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-plex",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "plex — media server. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// plex's tools — moved here from the shared sdk (novox/hq ADR 0039), importing plex'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 { PlexClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getPlexTools(plex: PlexClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "plex_status",
|
||||||
|
description: "Plex server status: server info, libraries, active sessions, recently added.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const [server, libraries, sessions, recent] = await Promise.all([
|
||||||
|
plex.getServerInfo(),
|
||||||
|
plex.getLibraries(),
|
||||||
|
plex.getSessions(),
|
||||||
|
plex.getRecentlyAdded(10),
|
||||||
|
]);
|
||||||
|
return { server, libraries, sessions, recentlyAdded: recent };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "plex_reachable",
|
||||||
|
description: "Health probe: whether the Plex server answers, and which server it is. Never fails.",
|
||||||
|
input: {},
|
||||||
|
run: async () => plex.reachable(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "plex_search",
|
||||||
|
description: "Search across all Plex libraries — movies, shows, episodes, music.",
|
||||||
|
input: { query: { type: "string", description: "the search query" } },
|
||||||
|
run: async (args) => ({ query: String(args.query), results: await plex.search(String(args.query)) }),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "plex_sessions",
|
||||||
|
description: "Active Plex playback sessions — who is watching what, and where.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const sessions = await plex.getSessions();
|
||||||
|
return { count: sessions.length, sessions };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "plex_recently_added",
|
||||||
|
description: "Recently added media in Plex.",
|
||||||
|
input: { limit: { type: "number", description: "how many items (default 20)" } },
|
||||||
|
run: async (args) => ({ items: await plex.getRecentlyAdded(args.limit ? Number(args.limit) : 20) }),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "plex_refresh",
|
||||||
|
description: "Ask Plex to rescan its libraries so new files on disk become visible items.",
|
||||||
|
input: { library: { type: "string", description: "a library section key; omitted rescans all" } },
|
||||||
|
run: async (args) => {
|
||||||
|
if (args.library) {
|
||||||
|
await plex.refreshLibrary(String(args.library));
|
||||||
|
return { refreshed: String(args.library) };
|
||||||
|
}
|
||||||
|
await plex.refreshAll();
|
||||||
|
return { refreshed: "all" };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tools exist only when a token can be found; without one, plex contributes none rather than
|
||||||
|
// failing the whole runtime.
|
||||||
|
registerModuleTools("plex", (env) => {
|
||||||
|
try {
|
||||||
|
return getPlexTools(PlexClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# qbittorrent's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/qbittorrent
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/qbittorrent/dist /app/modules/qbittorrent/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/qbittorrent/dist/index.js,/app/modules/qbittorrent/dist/tools/index.js
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// The qBittorrent API client — qbittorrent's own code, living in the module (novox/hq ADR 0039).
|
||||||
|
// 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 obtained by POSTing credentials, and guards
|
||||||
|
// against CSRF by checking the Referer header. The cookie was `SID` before qBittorrent 5.2 and is
|
||||||
|
// `QBT_SID_<port>` since, and a successful login answers 200 "Ok." before and 204 with no body
|
||||||
|
// since — both are accepted. Node's fetch keeps no cookie jar, so the cookie is
|
||||||
|
// captured on login and carried by hand on every later call, with a single re-login on expiry.
|
||||||
|
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
|
||||||
|
function meshConfig(file?: string): Record<string, string> {
|
||||||
|
if (!file) return {};
|
||||||
|
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
|
||||||
|
catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The WebUI username from qBittorrent's own qBittorrent.conf, in the config directory the mesh
|
||||||
|
* mounts read-only (MESH_QBITTORRENT_CONFIG_DIR, which is the container's /config). The software's
|
||||||
|
* file is the truth about who may log in, so the tools ask it rather than a setting that could
|
||||||
|
* disagree. Absent, unreadable or unset yields undefined. */
|
||||||
|
function confUsername(dir: string | undefined): string | undefined {
|
||||||
|
if (!dir) return undefined;
|
||||||
|
try {
|
||||||
|
const line = readFileSync(`${dir.replace(/\/$/, "")}/qBittorrent/qBittorrent.conf`, "utf8")
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.find((l) => l.startsWith("WebUI\\Username="));
|
||||||
|
const value = line?.slice("WebUI\\Username=".length).trim();
|
||||||
|
return value ? value : undefined;
|
||||||
|
} catch { return undefined; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read a secret the mesh mounted at a file path (an own-secret delivered by `secret accept`);
|
||||||
|
* absent or unreadable yields undefined so callers fall back rather than crash. */
|
||||||
|
function readSecret(file?: string): string | undefined {
|
||||||
|
if (!file) return undefined;
|
||||||
|
try { return readFileSync(file, "utf8").trim(); }
|
||||||
|
catch { return undefined; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class QbittorrentClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
/** The session cookie as `name=value`, sent back exactly as it was set. */
|
||||||
|
private session: 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 is read from qBittorrent.conf,
|
||||||
|
* falling back to "admin", the image's default. The password cannot be read there — qBittorrent
|
||||||
|
* keeps only a PBKDF2 hash — so it is the own-secret the operator accepts.
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): QbittorrentClient {
|
||||||
|
const cfg = meshConfig(env.MESH_QBITTORRENT_CONFIG_FILE);
|
||||||
|
const url = cfg.url ?? env.MESH_QBITTORRENT_URL;
|
||||||
|
const password = cfg.password ?? readSecret(env.MESH_QBITTORRENT_PASSWORD_FILE) ?? env.MESH_QBITTORRENT_PASSWORD;
|
||||||
|
if (!url || !password) {
|
||||||
|
throw new Error("qBittorrent not configured — set MESH_QBITTORRENT_URL and MESH_QBITTORRENT_PASSWORD");
|
||||||
|
}
|
||||||
|
// The WebUI username: a setting or the environment if one says so, else whatever
|
||||||
|
// qBittorrent.conf holds (an adopted machine keeps its own), else the image's "admin".
|
||||||
|
const user = cfg.user ?? env.MESH_QBITTORRENT_USER ?? confUsername(env.MESH_QBITTORRENT_CONFIG_DIR) ?? "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.status === 401) throw new Error("qBittorrent login rejected — check credentials");
|
||||||
|
if (!res.ok) throw new Error(`qBittorrent login: ${res.status} ${await res.text()}`);
|
||||||
|
// 4.x/5.0/5.1 answer 200 "Ok." or 200 "Fails."; 5.2 answers 204 with no body, or 401.
|
||||||
|
const body = (await res.text()).trim();
|
||||||
|
if (res.status !== 204 && body !== "Ok.") {
|
||||||
|
throw new Error("qBittorrent login rejected — check credentials");
|
||||||
|
}
|
||||||
|
const match = res.headers.get("set-cookie")?.match(/((?:QBT_)?SID(?:_\d+)?)=([^;]+)/);
|
||||||
|
if (!match) throw new Error("qBittorrent login returned no session cookie");
|
||||||
|
this.session = `${match[1]}=${match[2]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async call(method: "GET" | "POST", path: string, form?: Record<string, string>): Promise<Response> {
|
||||||
|
if (!this.session) await this.login();
|
||||||
|
const doFetch = (): Promise<Response> => {
|
||||||
|
const headers: Record<string, string> = { Referer: this.baseUrl, Cookie: this.session ?? "" };
|
||||||
|
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 || res.status === 401) {
|
||||||
|
// The session 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()}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 0041/0042):
|
||||||
|
// 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("download.added", { name: t.name, category: t.category, sizeBytes: t.sizeBytes });
|
||||||
|
} else if (before < 1 && t.progress >= 1) {
|
||||||
|
await emit("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");
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
{
|
||||||
|
"module": "qbittorrent",
|
||||||
|
"version": "1",
|
||||||
|
"slug": "qbt",
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"download.added",
|
||||||
|
"download.completed"
|
||||||
|
],
|
||||||
|
"consumes": [],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/qbittorrent/broker",
|
||||||
|
"password": "/var/lib/mesh/qbittorrent/password"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 8112,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "the download client's pages, and the WebUI API its consumers and its own tools call. qBittorrent refuses a request whose Host names a port other than the one it listens on, so it listens on the machine port itself (host network, WEBUI_PORT=${port:8112}) and the two cannot differ on any machine"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "peers",
|
||||||
|
"port": 6881,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "incoming BitTorrent peer connections; announced to trackers and peers, so qBittorrent listens on the machine port itself (TORRENTING_PORT=${port:6881})"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "peers-udp",
|
||||||
|
"port": 6881,
|
||||||
|
"protocol": "udp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "DHT and uTP on the same number as the peer port"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accesses": [
|
||||||
|
{
|
||||||
|
"path": "/services/media/downloads",
|
||||||
|
"mode": "read-write"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/qbittorrent",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "qbittorrent",
|
||||||
|
"image": "lscr.io/linuxserver/qbittorrent@sha256:457e4eec2ee3f5e4ef59f237ad51f6143deba9f7445ab48bb5204a98888ef9aa",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC",
|
||||||
|
"WEBUI_PORT": "${port:8112}",
|
||||||
|
"TORRENTING_PORT": "${port:6881}"
|
||||||
|
},
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"/services/media/downloads:/downloads"
|
||||||
|
],
|
||||||
|
"network": "host"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/config.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-qbittorrent",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/qbittorrent/broker:/run/secrets/broker:ro",
|
||||||
|
"/var/lib/mesh/qbittorrent/password:/run/secrets/password:ro",
|
||||||
|
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||||
|
"${dir:config}:/var/lib/qbittorrent/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_QBITTORRENT_URL": "http://127.0.0.1:${port:8112}",
|
||||||
|
"MESH_QBITTORRENT_PASSWORD_FILE": "/run/secrets/password",
|
||||||
|
"MESH_QBITTORRENT_CONFIG_FILE": "/run/config/config.json",
|
||||||
|
"MESH_QBITTORRENT_CONFIG_DIR": "/var/lib/qbittorrent/config"
|
||||||
|
},
|
||||||
|
"restart-on": [
|
||||||
|
"runtime-config",
|
||||||
|
"needs-password"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"provides": [
|
||||||
|
"qbittorrent-api"
|
||||||
|
],
|
||||||
|
"serves": {
|
||||||
|
"qbittorrent-api": {
|
||||||
|
"scheme": "http",
|
||||||
|
"port": 8112,
|
||||||
|
"url-base": "",
|
||||||
|
"username": "admin"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"requires": [
|
||||||
|
"route"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "qbittorrent",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// qbittorrent's tools — living in the module (novox/hq ADR 0039), 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 [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# radarr's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/radarr
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts downloads/settings.ts downloads/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/radarr/dist /app/modules/radarr/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/radarr/dist/index.js,/app/modules/radarr/dist/tools/index.js
|
||||||
|
# NOT dist/downloads/index.js: that is a step the host runs to completion, named by the `downloads`
|
||||||
|
# container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run inside the
|
||||||
|
# serving sidecar too, and exit it.
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
// The Radarr API client — radarr's own code, living in the module (novox/hq ADR 0039). Ported from
|
||||||
|
// the shared hal `arr` client, but self-contained: in nox each Servarr app owns its own copy, so a
|
||||||
|
// change to Radarr's API rebuilds only radarr and nothing else. Both this module's tools and its
|
||||||
|
// events entrypoint import it, and nothing outside radarr does.
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
// Radarr speaks the v3 API; its content is "movie".
|
||||||
|
const API_VERSION = "v3";
|
||||||
|
const CONTENT_ENDPOINT = "movie";
|
||||||
|
const APP_NAME = "Radarr";
|
||||||
|
|
||||||
|
export interface RadarrQueueItem {
|
||||||
|
/** The queue record id — stable while the item is in the queue, so events can diff on it. */
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
status: string;
|
||||||
|
size: string;
|
||||||
|
sizeleft: string;
|
||||||
|
timeleft?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RadarrCalendarItem {
|
||||||
|
title: string;
|
||||||
|
date: string;
|
||||||
|
overview?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RadarrContentItem {
|
||||||
|
title: string;
|
||||||
|
year?: number;
|
||||||
|
status?: string;
|
||||||
|
monitored: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RadarrClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly apiKey: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the module's resolved environment. The URL defaults to the server on this node (the
|
||||||
|
* runtime shares its network), and the API key is read from MESH_RADARR_API_KEY or, failing that,
|
||||||
|
* discovered from the server's own config.xml under MESH_RADARR_CONFIG_DIR — the same file Radarr
|
||||||
|
* writes it to, so a running server needs nothing configured by hand. Throws when no key can be
|
||||||
|
* found, so the tools/events simply do not load (the harness treats the throw as "exposes
|
||||||
|
* nothing").
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): RadarrClient {
|
||||||
|
const url = env.MESH_RADARR_URL ?? `http://127.0.0.1:${env.MESH_RADARR_PORT ?? "7878"}`;
|
||||||
|
const configDir = env.MESH_RADARR_CONFIG_DIR ?? "/config";
|
||||||
|
const apiKey = env.MESH_RADARR_API_KEY ?? RadarrClient.detectApiKey(configDir);
|
||||||
|
if (!apiKey) {
|
||||||
|
throw new Error("Radarr not configured — set MESH_RADARR_API_KEY or make the config dir readable");
|
||||||
|
}
|
||||||
|
return new RadarrClient(url, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Discover the API key from the server's config.xml, falling back to null. Every Servarr app
|
||||||
|
* writes <ApiKey> into config.xml at the root of its config directory. */
|
||||||
|
static detectApiKey(configDir: string): string | null {
|
||||||
|
const config = join(configDir, "config.xml");
|
||||||
|
if (existsSync(config)) {
|
||||||
|
const match = readFileSync(config, "utf8").match(/<ApiKey>([^<]+)<\/ApiKey>/);
|
||||||
|
if (match) return match[1];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async get(endpoint: string, params?: Record<string, string>): Promise<unknown> {
|
||||||
|
const url = new URL(`${this.baseUrl}/api/${API_VERSION}/${endpoint}`);
|
||||||
|
if (params) {
|
||||||
|
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||||
|
}
|
||||||
|
const res = await fetch(url.toString(), { headers: { "X-Api-Key": this.apiKey } });
|
||||||
|
if (!res.ok) throw new Error(`${APP_NAME} API /${endpoint}: ${res.status} ${await res.text()}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getStatus(): Promise<{ appName: string; version: string }> {
|
||||||
|
const data = (await this.get("system/status")) as { appName?: string; version?: string };
|
||||||
|
return { appName: data.appName || APP_NAME, version: data.version ?? "unknown" };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getContent(limit?: number): Promise<RadarrContentItem[]> {
|
||||||
|
const data = await this.get(CONTENT_ENDPOINT);
|
||||||
|
const items: any[] = Array.isArray(data) ? data : ((data as any)?.records ?? []);
|
||||||
|
const mapped = items.map((item) => ({
|
||||||
|
title: item.title ?? "Unknown",
|
||||||
|
year: item.year,
|
||||||
|
status: item.status,
|
||||||
|
monitored: item.monitored ?? true,
|
||||||
|
}));
|
||||||
|
return limit ? mapped.slice(0, limit) : mapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Library search is a filter over existing content, not an indexer lookup — same as hal's. */
|
||||||
|
async searchContent(term: string): Promise<RadarrContentItem[]> {
|
||||||
|
const all = await this.getContent();
|
||||||
|
const lower = term.toLowerCase();
|
||||||
|
return all.filter((item) => item.title.toLowerCase().includes(lower));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getQueue(): Promise<{ totalRecords: number; items: RadarrQueueItem[] }> {
|
||||||
|
const data = (await this.get("queue", { pageSize: "50" })) as { totalRecords?: number; records?: any[] };
|
||||||
|
const records = data.records ?? [];
|
||||||
|
return {
|
||||||
|
totalRecords: data.totalRecords ?? records.length,
|
||||||
|
items: records.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
title: r.title ?? r.movie?.title ?? "Unknown",
|
||||||
|
status: r.status ?? "unknown",
|
||||||
|
size: formatBytes(r.size ?? 0),
|
||||||
|
sizeleft: formatBytes(r.sizeleft ?? 0),
|
||||||
|
timeleft: r.timeleft,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCalendar(days = 7): Promise<RadarrCalendarItem[]> {
|
||||||
|
const start = new Date().toISOString().split("T")[0];
|
||||||
|
const end = new Date(Date.now() + days * 86400000).toISOString().split("T")[0];
|
||||||
|
const data = await this.get("calendar", { start, end });
|
||||||
|
const items: any[] = Array.isArray(data) ? data : [];
|
||||||
|
return items.map((item) => ({
|
||||||
|
title: item.title ?? item.movie?.title ?? "Unknown",
|
||||||
|
date: item.inCinemas ?? item.digitalRelease ?? "",
|
||||||
|
overview: item.overview?.slice(0, 150),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes === 0) return "0 B";
|
||||||
|
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||||
|
return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
// The downloads step — run once by the host after the app's server starts, and again whenever a
|
||||||
|
// binding, a pair credential or the step's settings change (the container's `restart-on`,
|
||||||
|
// novox/hq ADR 0099). Byte-identical in sonarr, radarr, lidarr and bookshelf; see settings.ts.
|
||||||
|
//
|
||||||
|
// **A step, not a loop**: everything it does is a function of files the mesh writes, and the host
|
||||||
|
// already knows when they change. It connects to no broker.
|
||||||
|
//
|
||||||
|
// Exits non-zero when anything could not be put right — a refused credential, an unreachable
|
||||||
|
// provider, an entry the app would not save — so the node reports the step failed and the host
|
||||||
|
// runs it again on the next apply. Declared last in the manifest, so its failing gates nothing
|
||||||
|
// else of the module's (novox/hq ADR 0136).
|
||||||
|
//
|
||||||
|
// Reads, in MESH_DOWNLOADS_DIR, `<provision>.json` (the binding), `<provision>.secret` (the pair
|
||||||
|
// credential) and the settings file; remembers in MESH_DOWNLOADS_MEMORY the jackett hosts it has
|
||||||
|
// pointed feeds at, so a jackett that moves takes its feeds with it. Never prints a credential.
|
||||||
|
|
||||||
|
import { mkdir, rename, writeFile } from "node:fs/promises";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CLIENTS,
|
||||||
|
JACKETT,
|
||||||
|
acceptRemedy,
|
||||||
|
appConfig,
|
||||||
|
appReady,
|
||||||
|
listEntries,
|
||||||
|
providerTakes,
|
||||||
|
readIfThere,
|
||||||
|
readJson,
|
||||||
|
reconcileClient,
|
||||||
|
reconcileIndexers,
|
||||||
|
scrub,
|
||||||
|
stepSettings,
|
||||||
|
wanted,
|
||||||
|
type App,
|
||||||
|
type Binding,
|
||||||
|
type Http,
|
||||||
|
type Entry,
|
||||||
|
type Outcome,
|
||||||
|
type Took,
|
||||||
|
} from "./settings.js";
|
||||||
|
|
||||||
|
const module = process.env.MESH_DOWNLOADS_APP ?? "app";
|
||||||
|
const dir = process.env.MESH_DOWNLOADS_DIR ?? "/run/downloads";
|
||||||
|
const settingsFile = process.env.MESH_DOWNLOADS_SETTINGS ?? join(dir, "downloads.json");
|
||||||
|
const memoryFile = process.env.MESH_DOWNLOADS_MEMORY ?? "/var/lib/downloads/memory.json";
|
||||||
|
const waitSeconds = Number(process.env.MESH_DOWNLOADS_WAIT_SECONDS ?? "180");
|
||||||
|
const tag = `[${module}-downloads]`;
|
||||||
|
|
||||||
|
const http: Http = { fetch: (u, init) => fetch(u, init) };
|
||||||
|
const secrets: string[] = [];
|
||||||
|
const say = (line: string) => console.log(scrub(`${tag} ${line}`, secrets));
|
||||||
|
const fail = (line: string) => console.error(scrub(`${tag} ${line}`, secrets));
|
||||||
|
|
||||||
|
const config = appConfig((await readIfThere(process.env.MESH_DOWNLOADS_APP_CONFIG)) ?? "");
|
||||||
|
if (!config.apiKey) {
|
||||||
|
fail(`no API key in ${module}'s config.xml yet — ${module} writes it on its first start; the step runs again on the next apply`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
secrets.push(config.apiKey);
|
||||||
|
const app: App = {
|
||||||
|
module,
|
||||||
|
url: `${(process.env.MESH_DOWNLOADS_APP_URL ?? "http://127.0.0.1").replace(/\/$/, "")}${config.urlBase}`,
|
||||||
|
apiKey: config.apiKey,
|
||||||
|
api: process.env.MESH_DOWNLOADS_API ?? "v3",
|
||||||
|
};
|
||||||
|
const settings = stepSettings(await readJson(settingsFile));
|
||||||
|
|
||||||
|
if (!(await appReady(http, app, waitSeconds * 1000))) {
|
||||||
|
fail(`${module} did not answer at ${app.url} within ${waitSeconds}s`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
|
||||||
|
// The download clients.
|
||||||
|
let clients: Entry[];
|
||||||
|
try {
|
||||||
|
clients = await listEntries(http, app, "downloadclient");
|
||||||
|
} catch (err) {
|
||||||
|
fail(err instanceof Error ? err.message : String(err));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
for (const kind of CLIENTS) {
|
||||||
|
const credential = await readIfThere(join(dir, `${kind.provision}.secret`));
|
||||||
|
if (credential) secrets.push(credential.trim());
|
||||||
|
const w = wanted(kind.provision, (await readJson(join(dir, `${kind.provision}.json`))) as Binding | undefined, credential, true);
|
||||||
|
// `in`, not `!w.ok`: the Dockerfile compiles without strict, where a boolean discriminant does not
|
||||||
|
// narrow.
|
||||||
|
if ("problem" in w) {
|
||||||
|
outcomes.push({ what: kind.provision, result: "refused", problem: w.problem });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const ep = w.endpoint;
|
||||||
|
try {
|
||||||
|
if (!(await providerTakes(http, kind.provision, ep)).took) {
|
||||||
|
outcomes.push({
|
||||||
|
what: kind.provision,
|
||||||
|
result: "refused",
|
||||||
|
problem: acceptRemedy(app, settings.node, kind.provision, kind.provider, kind.secretName, ep.from),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: kind.provision,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${kind.provider} could not be asked whether it takes the credential at ${ep.host}:${ep.port}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
outcomes.push(...(await reconcileClient(http, app, kind, settings.names[kind.provision], ep, clients)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The indexers, through jackett.
|
||||||
|
{
|
||||||
|
const credential = await readIfThere(join(dir, `${JACKETT}.secret`));
|
||||||
|
if (credential) secrets.push(credential.trim());
|
||||||
|
const w = wanted(JACKETT, (await readJson(join(dir, `${JACKETT}.json`))) as Binding | undefined, credential, false);
|
||||||
|
if ("problem" in w) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: w.problem });
|
||||||
|
} else {
|
||||||
|
const ep = w.endpoint;
|
||||||
|
let took: Took | undefined;
|
||||||
|
try {
|
||||||
|
took = await providerTakes(http, JACKETT, ep);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: JACKETT,
|
||||||
|
result: "refused",
|
||||||
|
problem: `jackett could not be asked whether it takes the key at ${ep.host}:${ep.port}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (took && !took.took) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: acceptRemedy(app, settings.node, JACKETT, "jackett", "API key", ep.from) });
|
||||||
|
} else if (took) {
|
||||||
|
const memory = ((await readJson(memoryFile)) ?? {}) as Record<string, { hosts?: string[] } | undefined>;
|
||||||
|
const remembered = Array.isArray(memory[JACKETT]?.hosts) ? (memory[JACKETT]?.hosts as string[]) : [];
|
||||||
|
try {
|
||||||
|
const indexers = await listEntries(http, app, "indexer");
|
||||||
|
outcomes.push(
|
||||||
|
...(await reconcileIndexers(http, app, ep, took.configured ?? new Map(), settings.indexers, remembered, indexers)),
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: err instanceof Error ? err.message : String(err) });
|
||||||
|
}
|
||||||
|
// Remember where the feeds now point, so they are still recognised as the mesh's if jackett
|
||||||
|
// moves. Written whole and renamed, so a crash leaves the old memory, never half of one.
|
||||||
|
const hosts = [...new Set([...remembered, ep.host.toLowerCase()])].sort();
|
||||||
|
if (hosts.join() !== [...remembered].sort().join()) {
|
||||||
|
try {
|
||||||
|
await mkdir(dirname(memoryFile), { recursive: true });
|
||||||
|
await writeFile(`${memoryFile}.tmp`, JSON.stringify({ ...memory, [JACKETT]: { hosts } }, null, 2) + "\n", { mode: 0o600 });
|
||||||
|
await rename(`${memoryFile}.tmp`, memoryFile);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: JACKETT,
|
||||||
|
result: "notice",
|
||||||
|
note: `could not remember ${ep.host} as a jackett host (${err instanceof Error ? err.message : String(err)}); if jackett moves, list it in downloads.jackett-api.adopt-hosts`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let failed = 0;
|
||||||
|
for (const o of outcomes) {
|
||||||
|
switch (o.result) {
|
||||||
|
case "unchanged":
|
||||||
|
say(`${o.what}: already as the mesh says${o.untested ? "" : "; connection tested"}`);
|
||||||
|
break;
|
||||||
|
case "written":
|
||||||
|
say(`${o.what}: wrote ${o.fields.join(", ")}${o.untested ? "" : "; connection tested"}`);
|
||||||
|
break;
|
||||||
|
case "created":
|
||||||
|
say(`${o.what}: registered; connection tested`);
|
||||||
|
break;
|
||||||
|
case "notice":
|
||||||
|
say(`${o.what}: ${o.note}`);
|
||||||
|
break;
|
||||||
|
case "refused":
|
||||||
|
failed++;
|
||||||
|
fail(`${o.what}: ${o.problem}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.exitCode = failed > 0 ? 1 : 0;
|
||||||
@@ -0,0 +1,778 @@
|
|||||||
|
// Where a Servarr app reaches its download clients and its indexer proxy — decided by the mesh,
|
||||||
|
// written into the app by the app's own API.
|
||||||
|
//
|
||||||
|
// **One file, four copies.** sonarr, radarr, lidarr and bookshelf (a Readarr fork) keep their
|
||||||
|
// download clients and indexers behind the same API — `/api/v3/…` for the first two, `/api/v1/…`
|
||||||
|
// for the others — so this step is the same code in each. Each module builds from its own
|
||||||
|
// directory (novox/hq ADR 0069), so each carries a byte-identical copy under `downloads/`;
|
||||||
|
// `test/downloads.test.ts` checks the copies agree wherever the siblings are checked out beside
|
||||||
|
// it. Change all four together.
|
||||||
|
//
|
||||||
|
// **Why this exists.** The app keeps its connection to nzbget, qBittorrent and jackett in its own
|
||||||
|
// database, not in a file, so the mesh has nowhere to write `${bound:nzbget-api:at}` for it. The
|
||||||
|
// module requires `nzbget-api`, `qbittorrent-api` and `jackett-api`; the mesh delivers, for each,
|
||||||
|
// a binding (where the provider is — `at` — and what it serves: `port`, `scheme`, `url-base`, and
|
||||||
|
// for a download client the `username`) and a pair credential (nzbget's ControlPassword,
|
||||||
|
// qBittorrent's WebUI password, jackett's API key — each the provider's one and only, accepted by
|
||||||
|
// the operator per pair; the mesh cannot mint them). This step reads those files and makes the
|
||||||
|
// app's entries say the same thing.
|
||||||
|
//
|
||||||
|
// **Which entries are the mesh's.** Never a guess from what an entry looks like:
|
||||||
|
// - a download client is the mesh's when its name is the one the module's settings give for
|
||||||
|
// that provision (`downloads.<provision>.name`) and its kind is that provider's. On a fresh
|
||||||
|
// machine the step registers it under that name; on a migrated one the assignment names the
|
||||||
|
// entry the migration adopts ("NZBGet" on ace).
|
||||||
|
// - a Torznab indexer is the mesh's when it reads a jackett feed
|
||||||
|
// (`…/api/v2.0/indexers/<id>/results/torznab`) on a host the mesh put there — the bound `at`,
|
||||||
|
// one it bound before (remembered by the step), or one the settings adopt
|
||||||
|
// (`downloads.jackett-api.adopt-hosts`, which is how a migration names the entries that pointed
|
||||||
|
// at the old container). `downloads.jackett-api.indexers` lists the jackett indexers the app
|
||||||
|
// should have; one missing is registered.
|
||||||
|
// Everything else — every entry a person made, an nzbget elsewhere, a seedbox's jackett, a Newznab
|
||||||
|
// indexer — is left exactly as it is. **Nothing is ever deleted.**
|
||||||
|
//
|
||||||
|
// **Only the connection, and only when it differs.** Host, port, TLS, base path, user name and
|
||||||
|
// the credential. Categories, priorities, "enabled", seed criteria and every other choice made in
|
||||||
|
// the app are left alone. The stored credential cannot be read back (the app masks it), so the
|
||||||
|
// step asks the app to test the entry with the mesh's host and port and the credential it already
|
||||||
|
// holds: passing, the credential is already the provider's one and only; failing, the delivered
|
||||||
|
// credential is written.
|
||||||
|
//
|
||||||
|
// **A credential the provider refuses is never written.** Until the operator accepts the
|
||||||
|
// provider's secret for this pair, the mesh delivers a value it minted itself, which no provider
|
||||||
|
// will ever accept (novox/hq ADR 0092). Writing it would replace a working password with a dead
|
||||||
|
// one. So it is tried against the provider first; refused, nothing of that provision is written
|
||||||
|
// and the step fails naming the `secret accept` that fixes it.
|
||||||
|
//
|
||||||
|
// Pure logic and a small HTTP seam, so it is tested against fake servers (test/downloads.test.ts).
|
||||||
|
// Never prints a credential, an API key, or a URL carrying one.
|
||||||
|
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
|
||||||
|
/** A download-client provision and the shape of its entry in the app. */
|
||||||
|
export interface ClientKind {
|
||||||
|
provision: "nzbget-api" | "qbittorrent-api";
|
||||||
|
/** The app's `implementation` for it. */
|
||||||
|
implementation: "Nzbget" | "QBittorrent";
|
||||||
|
/** The provider, as a person calls it. */
|
||||||
|
provider: string;
|
||||||
|
/** What the pair credential is, in the provider's words. */
|
||||||
|
secretName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CLIENTS: readonly ClientKind[] = [
|
||||||
|
{ provision: "nzbget-api", implementation: "Nzbget", provider: "nzbget", secretName: "ControlPassword" },
|
||||||
|
{ provision: "qbittorrent-api", implementation: "QBittorrent", provider: "qBittorrent", secretName: "WebUI password" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const JACKETT = "jackett-api";
|
||||||
|
|
||||||
|
/** What the mesh wrote at `binds.<provision>`: the binding document. */
|
||||||
|
export interface Binding {
|
||||||
|
provision?: string;
|
||||||
|
from?: string;
|
||||||
|
at?: string;
|
||||||
|
as?: string;
|
||||||
|
serves?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a provider is, as the mesh bound it, and the credential for it. */
|
||||||
|
export interface Endpoint {
|
||||||
|
scheme: "http" | "https";
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
/** "" at the root, otherwise "/base" — one leading slash, none trailing. */
|
||||||
|
urlBase: string;
|
||||||
|
/** The user a download client logs in as; "" for jackett, which takes a key. */
|
||||||
|
username: string;
|
||||||
|
credential: string;
|
||||||
|
/** The provider's node, for the `secret accept` remedy. */
|
||||||
|
from: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Wanted = { ok: true; endpoint: Endpoint } | { ok: false; problem: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The endpoint the mesh says to use, from a binding and its pair credential.
|
||||||
|
*
|
||||||
|
* Refused rather than guessed when the binding cannot be dialled from the app's own container: a
|
||||||
|
* loopback `at` — what the mesh hands a machine that is not on the private network — is the app's
|
||||||
|
* container itself.
|
||||||
|
*/
|
||||||
|
export function wanted(
|
||||||
|
provision: string,
|
||||||
|
binding: Binding | undefined,
|
||||||
|
credential: string | undefined,
|
||||||
|
needsUser: boolean,
|
||||||
|
): Wanted {
|
||||||
|
if (!binding) {
|
||||||
|
return { ok: false, problem: `no binding for ${provision} was delivered — the mesh writes it before this step runs` };
|
||||||
|
}
|
||||||
|
const host = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||||
|
const serves = binding.serves ?? {};
|
||||||
|
const port = Number(serves.port);
|
||||||
|
if (!host) return { ok: false, problem: `the ${provision} binding names no host (at)` };
|
||||||
|
if (isLoopback(host)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
problem:
|
||||||
|
`the ${provision} binding says the provider is at ${host}, which from the app's own container is the ` +
|
||||||
|
`app itself. The mesh hands loopback to a machine that is not on the private network; put it on the ` +
|
||||||
|
`private network so the provider has an address the app can dial`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves no usable port (${String(serves.port)})` };
|
||||||
|
}
|
||||||
|
const scheme = typeof serves.scheme === "string" && serves.scheme ? serves.scheme : "http";
|
||||||
|
if (scheme !== "http" && scheme !== "https") {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves scheme ${scheme}, which the app cannot dial` };
|
||||||
|
}
|
||||||
|
const username = typeof serves.username === "string" ? serves.username.trim() : "";
|
||||||
|
if (needsUser && !username) {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves no username for the app to log in as` };
|
||||||
|
}
|
||||||
|
const key = (credential ?? "").trim();
|
||||||
|
if (!key) return { ok: false, problem: `the ${provision} credential is empty or was not delivered` };
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
endpoint: {
|
||||||
|
scheme,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
urlBase: normBase(serves["url-base"]),
|
||||||
|
username,
|
||||||
|
credential: key,
|
||||||
|
from: typeof binding.from === "string" ? binding.from : "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A URL base as "" or "/x/y": slashes trimmed, one put back in front. */
|
||||||
|
export function normBase(v: unknown): string {
|
||||||
|
const s = typeof v === "string" ? v.trim().replace(/^\/+|\/+$/g, "") : "";
|
||||||
|
return s === "" ? "" : `/${s}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLoopback(host: string): boolean {
|
||||||
|
const h = host.toLowerCase();
|
||||||
|
return h === "localhost" || h === "::1" || h === "[::1]" || /^127\./.test(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hostForUrl(host: string): string {
|
||||||
|
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The provider's base URL, as the step dials it and as the app is given it. */
|
||||||
|
export function baseUrl(ep: Endpoint): string {
|
||||||
|
return `${ep.scheme}://${hostForUrl(ep.host)}:${ep.port}${ep.urlBase}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// HTTP
|
||||||
|
|
||||||
|
/** The HTTP the step needs, so a test can stand fakes in for the app and the providers. */
|
||||||
|
export interface Http {
|
||||||
|
fetch(
|
||||||
|
url: string,
|
||||||
|
init?: { method?: string; headers?: Record<string, string>; body?: string },
|
||||||
|
): Promise<{ status: number; text(): Promise<string> }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app, as the step reaches it from the host. */
|
||||||
|
export interface App {
|
||||||
|
/** The module, for messages and the remedy: sonarr, radarr, lidarr, bookshelf. */
|
||||||
|
module: string;
|
||||||
|
/** Its own URL, base path included. */
|
||||||
|
url: string;
|
||||||
|
apiKey: string;
|
||||||
|
/** v3 (sonarr, radarr) or v1 (lidarr, bookshelf). */
|
||||||
|
api: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Answer {
|
||||||
|
status: number;
|
||||||
|
body: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function appCall(http: Http, app: App, method: string, path: string, body?: unknown): Promise<Answer> {
|
||||||
|
const res = await http.fetch(`${app.url.replace(/\/$/, "")}/api/${app.api}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
"X-Api-Key": app.apiKey,
|
||||||
|
Accept: "application/json",
|
||||||
|
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||||
|
},
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
let parsed: unknown = undefined;
|
||||||
|
if (text) {
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(text) as unknown;
|
||||||
|
} catch {
|
||||||
|
parsed = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { status: res.status, body: parsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function appGet(http: Http, app: App, path: string): Promise<unknown> {
|
||||||
|
const a = await appCall(http, app, "GET", path);
|
||||||
|
if (a.status < 200 || a.status >= 300) throw new Error(`${app.module} GET ${path} answered ${a.status}`);
|
||||||
|
return a.body;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One of the app's validation failures: the only parts of an answer the step ever prints. */
|
||||||
|
interface Failure {
|
||||||
|
property: string;
|
||||||
|
message: string;
|
||||||
|
warning: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function failuresOf(body: unknown): Failure[] {
|
||||||
|
const list = Array.isArray(body) ? body : [];
|
||||||
|
return list.map((f) => {
|
||||||
|
const o = (f ?? {}) as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
property: String(o.propertyName ?? ""),
|
||||||
|
message: String(o.errorMessage ?? ""),
|
||||||
|
warning: o.isWarning === true,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One shape rather than a union on `ok`: the Dockerfile compiles without strict, where a boolean
|
||||||
|
* discriminant does not narrow.
|
||||||
|
*/
|
||||||
|
interface Verdict {
|
||||||
|
ok: boolean;
|
||||||
|
/** Warnings the app raised on a pass; errors (and any warnings) on a failure. */
|
||||||
|
failures: Failure[];
|
||||||
|
status: number;
|
||||||
|
saved?: Entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function verdict(a: Answer): Verdict {
|
||||||
|
if (a.status >= 200 && a.status < 300) return { ok: true, failures: [], status: a.status };
|
||||||
|
const failures = failuresOf(a.body);
|
||||||
|
if (a.status === 400 && failures.length > 0 && failures.every((f) => f.warning)) return { ok: true, failures, status: a.status };
|
||||||
|
return { ok: false, failures, status: a.status };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's own test of an entry, from the app's own container. */
|
||||||
|
async function appTest(http: Http, app: App, resource: string, entry: Entry): Promise<Verdict> {
|
||||||
|
return verdict(await appCall(http, app, "POST", `/${resource}/test`, entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save an entry. The app tests an enabled entry before saving it; a test that passes with only
|
||||||
|
* warnings ("a category is recommended") is saved with `forceSave`, the same as pressing "save
|
||||||
|
* anyway" in its screen. An error is never forced.
|
||||||
|
*/
|
||||||
|
async function appSave(http: Http, app: App, resource: string, entry: Entry, create: boolean): Promise<Verdict> {
|
||||||
|
const path = create ? `/${resource}` : `/${resource}/${entry.id}`;
|
||||||
|
const method = create ? "POST" : "PUT";
|
||||||
|
let a = await appCall(http, app, method, path, entry);
|
||||||
|
let v = verdict(a);
|
||||||
|
if (v.ok && (a.status < 200 || a.status >= 300)) {
|
||||||
|
a = await appCall(http, app, method, `${path}?forceSave=true`, entry);
|
||||||
|
v = verdict(a);
|
||||||
|
if (v.ok && (a.status < 200 || a.status >= 300)) {
|
||||||
|
return { ok: false, failures: failuresOf(a.body), status: a.status };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!v.ok) return v;
|
||||||
|
return { ...v, saved: (a.body ?? undefined) as Entry | undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Entries
|
||||||
|
|
||||||
|
/** An entry as the app's API gives it: a download client or an indexer. */
|
||||||
|
export interface Entry {
|
||||||
|
id?: number;
|
||||||
|
name?: string;
|
||||||
|
implementation?: string;
|
||||||
|
enable?: boolean;
|
||||||
|
enableRss?: boolean;
|
||||||
|
enableAutomaticSearch?: boolean;
|
||||||
|
enableInteractiveSearch?: boolean;
|
||||||
|
supportsRss?: boolean;
|
||||||
|
supportsSearch?: boolean;
|
||||||
|
fields?: { name: string; value?: unknown; [k: string]: unknown }[];
|
||||||
|
[k: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function field(e: Entry, name: string): unknown {
|
||||||
|
return e.fields?.find((f) => f.name === name)?.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The entry with these fields' values replaced — added when the app's shape lacks one. */
|
||||||
|
export function withFields(e: Entry, values: Record<string, unknown>): Entry {
|
||||||
|
const fields = (e.fields ?? []).map((f) => (f.name in values ? { ...f, value: values[f.name] } : { ...f }));
|
||||||
|
for (const [name, value] of Object.entries(values)) {
|
||||||
|
if (!fields.some((f) => f.name === name)) fields.push({ name, value });
|
||||||
|
}
|
||||||
|
return { ...e, fields };
|
||||||
|
}
|
||||||
|
|
||||||
|
function enabled(e: Entry): boolean {
|
||||||
|
return e.enable === true || e.enableRss === true || e.enableAutomaticSearch === true || e.enableInteractiveSearch === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What one provision, or one entry of it, came to. */
|
||||||
|
export type Outcome =
|
||||||
|
| { what: string; result: "unchanged"; untested?: boolean }
|
||||||
|
| { what: string; result: "written"; fields: string[]; untested?: boolean }
|
||||||
|
| { what: string; result: "created"; fields: string[] }
|
||||||
|
| { what: string; result: "notice"; note: string }
|
||||||
|
| { what: string; result: "refused"; problem: string };
|
||||||
|
|
||||||
|
function said(fs: Failure[]): string {
|
||||||
|
return fs.length === 0 ? "no reason given" : fs.map((f) => (f.property ? `${f.property}: ${f.message}` : f.message)).join("; ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring one of the mesh's entries in line: `connection` is the non-secret fields as the mesh says
|
||||||
|
* them, `differs` which of them the entry does not already say, `secretField` where the credential
|
||||||
|
* goes. Never throws: every failure is an outcome with a reason.
|
||||||
|
*/
|
||||||
|
export async function reconcileEntry(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
resource: "downloadclient" | "indexer",
|
||||||
|
what: string,
|
||||||
|
current: Entry,
|
||||||
|
connection: Record<string, unknown>,
|
||||||
|
differs: string[],
|
||||||
|
secretField: string,
|
||||||
|
credential: string,
|
||||||
|
testable = true,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
try {
|
||||||
|
const base = withFields(current, connection); // the credential as the app holds it — masked
|
||||||
|
if (!testable) {
|
||||||
|
// Nothing to test against (jackett no longer has the indexer it names): the connection is
|
||||||
|
// still the mesh's to state, and the key goes with it when the address changes.
|
||||||
|
if (differs.length === 0) return { what, result: "unchanged", untested: true };
|
||||||
|
const s = await appSave(http, app, resource, withFields(base, { [secretField]: credential }), false);
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not save it: ${said(s.failures)}` };
|
||||||
|
return { what, result: "written", fields: [...differs, secretField], untested: true };
|
||||||
|
}
|
||||||
|
const first = await appTest(http, app, resource, base);
|
||||||
|
if (first.ok) {
|
||||||
|
// The credential the app holds already works against the provider at the mesh's address —
|
||||||
|
// and the provider has exactly one, so it is the delivered one.
|
||||||
|
if (differs.length === 0) return { what, result: "unchanged" };
|
||||||
|
const s = await appSave(http, app, resource, base, false);
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not save it: ${said(s.failures)}` };
|
||||||
|
return { what, result: "written", fields: differs };
|
||||||
|
}
|
||||||
|
// The app's test failed with what it holds. The delivered credential was already checked
|
||||||
|
// against the provider, so writing it is safe; the app tests an enabled entry again on save.
|
||||||
|
const s = await appSave(http, app, resource, withFields(base, { [secretField]: credential }), false);
|
||||||
|
if (!s.ok) {
|
||||||
|
return {
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${app.module} tested it at the mesh's address and would not save it (nothing was written): ${said(s.failures)}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const stored = (await appGet(http, app, `/${resource}/${current.id}`)) as Entry;
|
||||||
|
const second = await appTest(http, app, resource, stored);
|
||||||
|
const fields = [...differs, secretField];
|
||||||
|
if (second.ok) return { what, result: "written", fields };
|
||||||
|
const why = `written (${fields.join(", ")}), and ${app.module}'s own test still fails: ${said(second.failures)}`;
|
||||||
|
return enabled(stored) ? { what, result: "refused", problem: why } : { what, result: "notice", note: `${why} — it is disabled, so nothing uses it` };
|
||||||
|
} catch (err) {
|
||||||
|
return { what, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a new entry from the app's own template for that kind: its defaults, the name, the
|
||||||
|
* connection and the credential. A category the provider does not have (nzbget refuses one it was
|
||||||
|
* not told about) is left empty rather than failing the registration, and said.
|
||||||
|
*/
|
||||||
|
export async function createEntry(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
resource: "downloadclient" | "indexer",
|
||||||
|
what: string,
|
||||||
|
implementation: string,
|
||||||
|
name: string,
|
||||||
|
values: Record<string, unknown>,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
try {
|
||||||
|
const schema = (await appGet(http, app, `/${resource}/schema`)) as Entry[];
|
||||||
|
const template = (schema ?? []).find((s) => s.implementation === implementation);
|
||||||
|
if (!template) return { what, result: "refused", problem: `${app.module} has no ${implementation} to register` };
|
||||||
|
let entry: Entry = withFields({ ...template, id: undefined, name }, values);
|
||||||
|
if (resource === "downloadclient") entry.enable = true;
|
||||||
|
else {
|
||||||
|
entry.enableRss = template.supportsRss !== false;
|
||||||
|
entry.enableAutomaticSearch = template.supportsSearch !== false;
|
||||||
|
entry.enableInteractiveSearch = template.supportsSearch !== false;
|
||||||
|
}
|
||||||
|
let s = await appSave(http, app, resource, entry, true);
|
||||||
|
let note = "";
|
||||||
|
if (!s.ok && s.failures.length > 0 && s.failures.every((f) => /category/i.test(f.property))) {
|
||||||
|
const emptied: Record<string, unknown> = {};
|
||||||
|
for (const f of entry.fields ?? []) if (/category$/i.test(f.name) && !/imported/i.test(f.name)) emptied[f.name] = "";
|
||||||
|
entry = withFields(entry, emptied);
|
||||||
|
s = await appSave(http, app, resource, entry, true);
|
||||||
|
note = " with its category left empty — the provider has none by the app's default name; set one in both";
|
||||||
|
}
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not register it: ${said(s.failures)}` };
|
||||||
|
const created = s.saved;
|
||||||
|
if (created?.id !== undefined) {
|
||||||
|
const t = await appTest(http, app, resource, (await appGet(http, app, `/${resource}/${created.id}`)) as Entry);
|
||||||
|
if (!t.ok) {
|
||||||
|
return { what, result: "refused", problem: `registered as "${name}"${note}, and ${app.module}'s own test fails: ${said(t.failures)}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return note
|
||||||
|
? { what, result: "notice", note: `registered as "${name}"${note}` }
|
||||||
|
: { what, result: "created", fields: Object.keys(values) };
|
||||||
|
} catch (err) {
|
||||||
|
return { what, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Providers: does it take the credential?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does the provider take this credential? `took` it does (for jackett, with the ids of the indexers
|
||||||
|
* it has configured); `refused` it said no; a thrown error when it could not be asked.
|
||||||
|
*/
|
||||||
|
export interface Took {
|
||||||
|
took: boolean;
|
||||||
|
configured?: Map<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function providerTakes(http: Http, provision: string, ep: Endpoint): Promise<Took> {
|
||||||
|
const base = baseUrl(ep);
|
||||||
|
if (provision === "nzbget-api") {
|
||||||
|
const auth = Buffer.from(`${ep.username}:${ep.credential}`).toString("base64");
|
||||||
|
const res = await http.fetch(`${base}/jsonrpc/version`, { method: "GET", headers: { Authorization: `Basic ${auth}` } });
|
||||||
|
await res.text();
|
||||||
|
if (res.status === 401 || res.status === 403) return { took: false };
|
||||||
|
if (res.status >= 200 && res.status < 300) return { took: true };
|
||||||
|
throw new Error(`nzbget answered ${res.status}`);
|
||||||
|
}
|
||||||
|
if (provision === "qbittorrent-api") {
|
||||||
|
const form = `username=${encodeURIComponent(ep.username)}&password=${encodeURIComponent(ep.credential)}`;
|
||||||
|
const res = await http.fetch(`${base}/api/v2/auth/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: form,
|
||||||
|
});
|
||||||
|
const text = (await res.text()).trim();
|
||||||
|
if (res.status === 401 || /^fails\.?$/i.test(text)) return { took: false };
|
||||||
|
if (res.status === 403) {
|
||||||
|
throw new Error(
|
||||||
|
"qBittorrent answered 403: it has banned this address after failed logins (WebUI\\BanDuration); it lifts by itself",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (res.status >= 200 && res.status < 300) return { took: true };
|
||||||
|
throw new Error(`qBittorrent answered ${res.status}`);
|
||||||
|
}
|
||||||
|
if (provision === JACKETT) {
|
||||||
|
const url = `${base}/api/v2.0/indexers/all/results/torznab/api?t=indexers&configured=true&apikey=${encodeURIComponent(ep.credential)}`;
|
||||||
|
const res = await http.fetch(url, { method: "GET" });
|
||||||
|
const text = await res.text();
|
||||||
|
if (res.status === 401 || res.status === 403) return { took: false };
|
||||||
|
if (res.status < 200 || res.status >= 300) throw new Error(`jackett answered ${res.status}`);
|
||||||
|
// jackett answers a wrong key 200 with an error document: code 100, "Invalid API Key".
|
||||||
|
if (/<error\b[^>]*\bcode="100"/i.test(text)) return { took: false };
|
||||||
|
if (/<error\b/i.test(text)) throw new Error("jackett answered with an error document");
|
||||||
|
return { took: true, configured: configuredIndexers(text) };
|
||||||
|
}
|
||||||
|
throw new Error(`no check for ${provision}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** jackett's configured indexers, id → title, from its `t=indexers` feed. */
|
||||||
|
export function configuredIndexers(xml: string): Map<string, string> {
|
||||||
|
const out = new Map<string, string>();
|
||||||
|
const re = /<indexer\b[^>]*\bid="([^"]+)"[^>]*>([\s\S]*?)<\/indexer>/g;
|
||||||
|
for (let m = re.exec(xml); m; m = re.exec(xml)) {
|
||||||
|
const title = /<title>([\s\S]*?)<\/title>/.exec(m[2])?.[1]?.trim() ?? m[1];
|
||||||
|
out.set(m[1], decodeXml(title));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeXml(s: string): string {
|
||||||
|
return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The remedy for a refused credential, in the controller's own words (ADR 0092). */
|
||||||
|
export function acceptRemedy(app: App, node: string, provision: string, provider: string, secretName: string, from: string): string {
|
||||||
|
return (
|
||||||
|
`${provider} refuses the ${provision} credential the mesh delivered, so nothing of ${provision} was written ` +
|
||||||
|
`into ${app.module}. ${provider} has one ${secretName} and the mesh cannot make it: accept it for this pair — ` +
|
||||||
|
`\`secret accept ${node || "<this node>"} ${app.module} ${provision} --provider ${from || "<its node>"} ` +
|
||||||
|
`--from <file holding ${provider}'s ${secretName}>\``
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Download clients
|
||||||
|
|
||||||
|
/** The non-secret fields of a download client as the mesh says them. */
|
||||||
|
export function clientConnection(ep: Endpoint): Record<string, unknown> {
|
||||||
|
return { host: ep.host, port: ep.port, useSsl: ep.scheme === "https", urlBase: ep.urlBase === "" ? null : ep.urlBase, username: ep.username };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which of them the entry does not already say. Names only. */
|
||||||
|
export function clientDiffers(e: Entry, ep: Endpoint): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
if (String(field(e, "host") ?? "").toLowerCase() !== ep.host.toLowerCase()) out.push("host");
|
||||||
|
if (Number(field(e, "port") ?? 0) !== ep.port) out.push("port");
|
||||||
|
if (Boolean(field(e, "useSsl")) !== (ep.scheme === "https")) out.push("useSsl");
|
||||||
|
if (normBase(field(e, "urlBase")) !== ep.urlBase) out.push("urlBase");
|
||||||
|
if (String(field(e, "username") ?? "") !== ep.username) out.push("username");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the app's download client for one provision in line: the entry by that name and kind is
|
||||||
|
* the mesh's and is updated; none, it is registered. An entry by that name of another kind, or by
|
||||||
|
* that name in another case, is somebody else's and is refused rather than touched.
|
||||||
|
*/
|
||||||
|
export async function reconcileClient(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
kind: ClientKind,
|
||||||
|
name: string,
|
||||||
|
ep: Endpoint,
|
||||||
|
entries: Entry[],
|
||||||
|
): Promise<Outcome[]> {
|
||||||
|
const what = `${kind.provision} ("${name}")`;
|
||||||
|
const exact = entries.filter((e) => e.name === name);
|
||||||
|
const alike = entries.filter((e) => e.name !== name && String(e.name ?? "").toLowerCase() === name.toLowerCase());
|
||||||
|
if (exact.length > 0 && exact[0].implementation !== kind.implementation) {
|
||||||
|
return [{
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `the download client named "${name}" is a ${exact[0].implementation}, not ${kind.implementation}; it is not the mesh's and was left alone. Name the mesh's entry otherwise in downloads.${kind.provision}.name`,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
if (exact.length === 0 && alike.length > 0) {
|
||||||
|
return [{
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${app.module} already has "${alike[0].name}", which is not the mesh's name ("${name}") and was left alone. To have the mesh manage it, set downloads.${kind.provision}.name to "${alike[0].name}"`,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
const others = entries.filter((e) => e.implementation === kind.implementation && e.name !== name);
|
||||||
|
if (others.length > 0) {
|
||||||
|
outcomes.push({
|
||||||
|
what,
|
||||||
|
result: "notice",
|
||||||
|
note: `also present and not the mesh's, left alone: ${others.map((o) => `"${o.name}"`).join(", ")}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (exact.length === 0) {
|
||||||
|
outcomes.push(
|
||||||
|
await createEntry(http, app, "downloadclient", what, kind.implementation, name, {
|
||||||
|
...clientConnection(ep),
|
||||||
|
password: ep.credential,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
outcomes.push(
|
||||||
|
await reconcileEntry(http, app, "downloadclient", what, exact[0], clientConnection(ep), clientDiffers(exact[0], ep), "password", ep.credential),
|
||||||
|
);
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Indexers
|
||||||
|
|
||||||
|
const FEED = /\/api\/v2\.0\/indexers\/([^/]+)\/results\/torznab\/?$/;
|
||||||
|
|
||||||
|
/** A Torznab entry reading a jackett feed: the host it points at and the jackett indexer's id. */
|
||||||
|
export function jackettFeed(e: Entry): { host: string; id: string } | undefined {
|
||||||
|
if (e.implementation !== "Torznab") return undefined;
|
||||||
|
const raw = String(field(e, "baseUrl") ?? "").trim();
|
||||||
|
if (!raw) return undefined;
|
||||||
|
let u: URL;
|
||||||
|
try {
|
||||||
|
u = new URL(raw);
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const path = `${u.pathname.replace(/\/+$/, "")}/${String(field(e, "apiPath") ?? "").replace(/^\/+/, "")}`;
|
||||||
|
const m = FEED.exec(path);
|
||||||
|
if (!m) return undefined;
|
||||||
|
return { host: u.hostname.replace(/^\[|\]$/g, "").toLowerCase(), id: decodeURIComponent(m[1]) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The feed's two fields as the mesh says them. */
|
||||||
|
export function feedConnection(ep: Endpoint, id: string): Record<string, unknown> {
|
||||||
|
return { baseUrl: baseUrl(ep), apiPath: `/api/v2.0/indexers/${id}/results/torznab/` };
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameUrl(a: string, b: string): boolean {
|
||||||
|
try {
|
||||||
|
const x = new URL(a);
|
||||||
|
const y = new URL(b);
|
||||||
|
const port = (u: URL) => u.port || (u.protocol === "https:" ? "443" : "80");
|
||||||
|
return (
|
||||||
|
x.protocol === y.protocol &&
|
||||||
|
x.hostname.toLowerCase() === y.hostname.toLowerCase() &&
|
||||||
|
port(x) === port(y) &&
|
||||||
|
x.pathname.replace(/\/+$/, "") === y.pathname.replace(/\/+$/, "")
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedDiffers(e: Entry, ep: Endpoint, id: string): string[] {
|
||||||
|
const want = feedConnection(ep, id);
|
||||||
|
const out: string[] = [];
|
||||||
|
if (!sameUrl(String(field(e, "baseUrl") ?? ""), String(want.baseUrl))) out.push("baseUrl");
|
||||||
|
const path = (v: unknown) => `/${String(v ?? "").replace(/^\/+|\/+$/g, "")}`;
|
||||||
|
if (path(field(e, "apiPath")) !== path(want.apiPath)) out.push("apiPath");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IndexerSettings {
|
||||||
|
/** Hosts whose jackett feeds the mesh takes over — a migration's old names. */
|
||||||
|
adoptHosts: string[];
|
||||||
|
/** jackett indexer ids the app should have. */
|
||||||
|
indexers: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the app's jackett feeds in line: every one the mesh manages is pointed at the bound jackett
|
||||||
|
* with its key, and every listed jackett indexer the app lacks is registered.
|
||||||
|
*/
|
||||||
|
export async function reconcileIndexers(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
ep: Endpoint,
|
||||||
|
configured: Map<string, string>,
|
||||||
|
settings: IndexerSettings,
|
||||||
|
remembered: string[],
|
||||||
|
entries: Entry[],
|
||||||
|
): Promise<Outcome[]> {
|
||||||
|
const ours = new Set([ep.host, ...settings.adoptHosts, ...remembered].map((h) => h.trim().toLowerCase()).filter(Boolean));
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
const managed = new Set<string>();
|
||||||
|
for (const e of entries) {
|
||||||
|
const feed = jackettFeed(e);
|
||||||
|
if (!feed || !ours.has(feed.host)) continue;
|
||||||
|
managed.add(feed.id);
|
||||||
|
const what = `jackett-api ("${e.name}", jackett indexer ${feed.id})`;
|
||||||
|
const known = feed.id === "all" || configured.has(feed.id);
|
||||||
|
const outcome = await reconcileEntry(
|
||||||
|
http, app, "indexer", what, e, feedConnection(ep, feed.id), feedDiffers(e, ep, feed.id), "apiKey", ep.credential, known,
|
||||||
|
);
|
||||||
|
outcomes.push(outcome);
|
||||||
|
if (!known && outcome.result !== "refused") {
|
||||||
|
outcomes.push({ what, result: "notice", note: `jackett has no indexer "${feed.id}" configured, so it was not tested; configure it in jackett or remove the entry in ${app.module}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const id of settings.indexers) {
|
||||||
|
if (managed.has(id)) continue;
|
||||||
|
const what = `jackett-api (jackett indexer ${id})`;
|
||||||
|
if (id !== "all" && !configured.has(id)) {
|
||||||
|
outcomes.push({ what, result: "refused", problem: `downloads.jackett-api.indexers lists "${id}", and jackett has no indexer by that id configured` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const name = `Jackett - ${id === "all" ? "all" : configured.get(id)}`;
|
||||||
|
outcomes.push(await createEntry(http, app, "indexer", what, "Torznab", name, { ...feedConnection(ep, id), apiKey: ep.credential }));
|
||||||
|
}
|
||||||
|
if (outcomes.length === 0) {
|
||||||
|
outcomes.push({ what: "jackett-api", result: "notice", note: `${app.module} has no jackett feed the mesh manages, and downloads.jackett-api.indexers lists none to register` });
|
||||||
|
}
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Files
|
||||||
|
|
||||||
|
/** The module's settings for this step, from its merged `downloads.json`. */
|
||||||
|
export interface StepSettings {
|
||||||
|
node: string;
|
||||||
|
names: Record<string, string>;
|
||||||
|
indexers: IndexerSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stepSettings(raw: unknown): StepSettings {
|
||||||
|
const doc = (raw ?? {}) as Record<string, unknown>;
|
||||||
|
const d = (doc.downloads ?? {}) as Record<string, Record<string, unknown> | undefined>;
|
||||||
|
const names: Record<string, string> = {};
|
||||||
|
for (const k of CLIENTS) {
|
||||||
|
const n = d[k.provision]?.name;
|
||||||
|
names[k.provision] = typeof n === "string" && n.trim() ? n.trim() : k.provision.replace(/-api$/, "");
|
||||||
|
}
|
||||||
|
const j = d[JACKETT] ?? {};
|
||||||
|
const strings = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && x.trim() !== "").map((x) => x.trim()) : []);
|
||||||
|
return {
|
||||||
|
node: typeof doc.node === "string" ? doc.node : "",
|
||||||
|
names,
|
||||||
|
indexers: { adoptHosts: strings(j["adopt-hosts"]), indexers: strings(j.indexers) },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's own key and base path, from its config.xml. */
|
||||||
|
export function appConfig(xml: string): { apiKey: string; urlBase: string } {
|
||||||
|
const tag = (t: string) => new RegExp(`<${t}>([^<]*)</${t}>`).exec(xml)?.[1]?.trim() ?? "";
|
||||||
|
return { apiKey: tag("ApiKey"), urlBase: normBase(tag("UrlBase")) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A file the mesh wrote, or undefined when it is not there. */
|
||||||
|
export async function readIfThere(path: string | undefined): Promise<string | undefined> {
|
||||||
|
if (!path) return undefined;
|
||||||
|
return readFile(path, "utf8").catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A JSON file parsed, or undefined when absent or not JSON. */
|
||||||
|
export async function readJson(path: string | undefined): Promise<unknown> {
|
||||||
|
const raw = await readIfThere(path);
|
||||||
|
if (raw === undefined) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as unknown;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait for the app to answer, because the step runs right after its container starts. */
|
||||||
|
export async function appReady(http: Http, app: App, waitMs: number, pauseMs = 2000): Promise<boolean> {
|
||||||
|
const until = Date.now() + waitMs;
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
const a = await appCall(http, app, "GET", "/system/status");
|
||||||
|
if (a.status === 200) return true;
|
||||||
|
} catch {
|
||||||
|
// not listening yet
|
||||||
|
}
|
||||||
|
if (Date.now() >= until) return false;
|
||||||
|
await new Promise((r) => setTimeout(r, pauseMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listEntries(http: Http, app: App, resource: "downloadclient" | "indexer"): Promise<Entry[]> {
|
||||||
|
return ((await appGet(http, app, `/${resource}`)) as Entry[]) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Anything printed goes through this: the credentials the step holds never reach a log. */
|
||||||
|
export function scrub(text: string, secrets: string[]): string {
|
||||||
|
let out = text;
|
||||||
|
for (const s of secrets) if (s && s.length >= 4) out = out.split(s).join("<redacted>");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(err: unknown): string {
|
||||||
|
return err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
// radarr's events. The tool runtime imports this once the broker is bound. It watches the download
|
||||||
|
// queue and turns its comings and goings into mesh events.
|
||||||
|
//
|
||||||
|
// Emits (novox/hq ADR 0041/0042):
|
||||||
|
// module.radarr.movie.grabbed — a release entered the queue (Radarr grabbed it)
|
||||||
|
// module.radarr.download.completed — a release left the queue, imported. This exact routing key
|
||||||
|
// is what the plex module consumes (module.*.download.completed)
|
||||||
|
// to rescan, so the new movie becomes a visible item.
|
||||||
|
// Consumes: none.
|
||||||
|
//
|
||||||
|
// The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a
|
||||||
|
// restart mid-download does not re-announce everything already in flight as freshly grabbed.
|
||||||
|
|
||||||
|
import { emit } from "@novox/mesh-sdk/events";
|
||||||
|
import { RadarrClient, type RadarrQueueItem } from "./client.js";
|
||||||
|
|
||||||
|
// Building the client throws when Radarr has no URL/key yet. Like the tools (see tools/index.ts),
|
||||||
|
// the events entrypoint must not crash the runtime for that — it stays idle until configured.
|
||||||
|
function buildClient(): RadarrClient | null {
|
||||||
|
try {
|
||||||
|
return RadarrClient.fromEnv();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const radarr = buildClient();
|
||||||
|
|
||||||
|
// Radarr removes an item from the queue once it has been imported; a "warning"/"failed" status is
|
||||||
|
// how a stuck or broken grab shows itself, so we do not call those a completion when they vanish.
|
||||||
|
const FAILED_STATUSES = new Set(["failed", "warning"]);
|
||||||
|
|
||||||
|
const inQueue = new Map<number, RadarrQueueItem>();
|
||||||
|
let primed = false;
|
||||||
|
|
||||||
|
async function pollQueue(radarr: RadarrClient): Promise<void> {
|
||||||
|
const { items } = await radarr.getQueue();
|
||||||
|
const now = new Map(items.map((i) => [i.id, i]));
|
||||||
|
|
||||||
|
if (primed) {
|
||||||
|
// Entered the queue since last look — Radarr grabbed a release.
|
||||||
|
for (const [id, item] of now) {
|
||||||
|
if (!inQueue.has(id)) await emit("movie.grabbed", { title: item.title, status: item.status });
|
||||||
|
}
|
||||||
|
// Left the queue — imported and done, unless it was last seen failing.
|
||||||
|
for (const [id, item] of inQueue) {
|
||||||
|
if (!now.has(id) && !FAILED_STATUSES.has(item.status)) {
|
||||||
|
await emit("download.completed", { title: item.title });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inQueue.clear();
|
||||||
|
for (const [id, item] of now) inQueue.set(id, item);
|
||||||
|
primed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||||
|
const run = (): void => void fn().catch((err) => console.error(`[radarr] ${err}`));
|
||||||
|
setInterval(run, everyMs);
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (radarr) {
|
||||||
|
tick(() => pollQueue(radarr), 30_000);
|
||||||
|
console.log("[radarr] watching the download queue, emitting grabs and completions");
|
||||||
|
} else {
|
||||||
|
console.log("[radarr] not configured — events idle until an API key is available");
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
{
|
||||||
|
"module": "radarr",
|
||||||
|
"version": "1",
|
||||||
|
"provides": [
|
||||||
|
{
|
||||||
|
"name": "radarr-api",
|
||||||
|
"scope": "mesh"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"serves": {
|
||||||
|
"radarr-api": {
|
||||||
|
"scheme": "http",
|
||||||
|
"port": 7878,
|
||||||
|
"url-base": ""
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"movie.grabbed",
|
||||||
|
"download.completed"
|
||||||
|
],
|
||||||
|
"consumes": [],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/radarr/broker"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 7878,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "managing films: its web UI, and the API other modules reach as radarr-api"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accesses": [
|
||||||
|
{
|
||||||
|
"path": "/services/media/movies",
|
||||||
|
"mode": "read-write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/downloads",
|
||||||
|
"mode": "read-write"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/radarr",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "radarr",
|
||||||
|
"image": "lscr.io/linuxserver/radarr@sha256:c960f2b52ec6542dbe6707c5a21e696a7c74fd8b17997454f4d10a55dacee133",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC"
|
||||||
|
},
|
||||||
|
"ports": [
|
||||||
|
"7878"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"/services/media/movies:/movies",
|
||||||
|
"/services/media/downloads:/downloads"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-radarr",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/radarr/broker:/run/secrets/broker:ro",
|
||||||
|
"${dir:config}:/var/lib/radarr/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_RADARR_URL": "http://127.0.0.1:${port:7878}",
|
||||||
|
"MESH_RADARR_CONFIG_DIR": "/var/lib/radarr/config"
|
||||||
|
},
|
||||||
|
"artifact": "runtime"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/downloads.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{\n \"node\": \"${machine:name}\",\n \"downloads\": {\n \"nzbget-api\": {\n \"name\": \"nzbget\"\n },\n \"qbittorrent-api\": {\n \"name\": \"qbittorrent\"\n },\n \"jackett-api\": {\n \"adopt-hosts\": [],\n \"indexers\": []\n }\n }\n}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads-memory",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-radarr-downloads",
|
||||||
|
"network": "host",
|
||||||
|
"run-once": true,
|
||||||
|
"volumes": [
|
||||||
|
"${dir:state}/downloads.json:/run/downloads/downloads.json:ro",
|
||||||
|
"${dir:state}/nzbget-api.json:/run/downloads/nzbget-api.json:ro",
|
||||||
|
"${dir:state}/nzbget-api.secret:/run/downloads/nzbget-api.secret:ro",
|
||||||
|
"${dir:state}/qbittorrent-api.json:/run/downloads/qbittorrent-api.json:ro",
|
||||||
|
"${dir:state}/qbittorrent-api.secret:/run/downloads/qbittorrent-api.secret:ro",
|
||||||
|
"${dir:state}/jackett-api.json:/run/downloads/jackett-api.json:ro",
|
||||||
|
"${dir:state}/jackett-api.secret:/run/downloads/jackett-api.secret:ro",
|
||||||
|
"${dir:config}:/var/lib/radarr/config:ro",
|
||||||
|
"${dir:downloads-memory}:/var/lib/downloads"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_DOWNLOADS_APP": "radarr",
|
||||||
|
"MESH_DOWNLOADS_API": "v3",
|
||||||
|
"MESH_DOWNLOADS_APP_URL": "http://127.0.0.1:${port:7878}",
|
||||||
|
"MESH_DOWNLOADS_APP_CONFIG": "/var/lib/radarr/config/config.xml",
|
||||||
|
"MESH_DOWNLOADS_DIR": "/run/downloads",
|
||||||
|
"MESH_DOWNLOADS_SETTINGS": "/run/downloads/downloads.json",
|
||||||
|
"MESH_DOWNLOADS_MEMORY": "/var/lib/downloads/memory.json"
|
||||||
|
},
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"/app/modules/radarr/dist/downloads/index.js"
|
||||||
|
],
|
||||||
|
"restart-on": [
|
||||||
|
"downloads-config",
|
||||||
|
"bound-nzbget-api",
|
||||||
|
"secret-nzbget-api",
|
||||||
|
"bound-qbittorrent-api",
|
||||||
|
"secret-qbittorrent-api",
|
||||||
|
"bound-jackett-api",
|
||||||
|
"secret-jackett-api"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requires": [
|
||||||
|
"jackett-api",
|
||||||
|
"nzbget-api",
|
||||||
|
"qbittorrent-api",
|
||||||
|
"route"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "movies",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json",
|
||||||
|
"nzbget-api": "${dir:state}/nzbget-api.json",
|
||||||
|
"qbittorrent-api": "${dir:state}/qbittorrent-api.json",
|
||||||
|
"jackett-api": "${dir:state}/jackett-api.json"
|
||||||
|
},
|
||||||
|
"secrets": {
|
||||||
|
"nzbget-api": "${dir:state}/nzbget-api.secret",
|
||||||
|
"qbittorrent-api": "${dir:state}/qbittorrent-api.secret",
|
||||||
|
"jackett-api": "${dir:state}/jackett-api.secret"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-radarr",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "radarr — movie management. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc client.ts index.ts tools/index.ts downloads/settings.ts downloads/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist",
|
||||||
|
"typecheck": "tsc -p tsconfig.json",
|
||||||
|
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
// What holds the downloads step (downloads/settings.ts): the app's download clients and jackett
|
||||||
|
// feeds are made to say what the mesh bound — host, port, TLS, base path, user, credential — and
|
||||||
|
// nothing else they keep is touched; only the mesh's entries are touched, and nothing is ever
|
||||||
|
// deleted; nothing is written when nothing differs; a missing one is registered; and a credential
|
||||||
|
// the provider refuses (the mesh's own minted value, before the operator accepts the provider's)
|
||||||
|
// is never written, with the `secret accept` that fixes it named.
|
||||||
|
//
|
||||||
|
// The app and the providers are fakes: the routes the step touches, answering as the real ones do
|
||||||
|
// (checked against the catalogue's pinned sonarr, radarr, lidarr, bookshelf, nzbget, qBittorrent
|
||||||
|
// and jackett): the app masks a stored password as "********", tests an enabled entry before
|
||||||
|
// saving it, refuses a warning unless forceSave, and jackett answers a wrong key 200 with an error.
|
||||||
|
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CLIENTS,
|
||||||
|
acceptRemedy,
|
||||||
|
jackettFeed,
|
||||||
|
providerTakes,
|
||||||
|
reconcileClient,
|
||||||
|
reconcileIndexers,
|
||||||
|
stepSettings,
|
||||||
|
wanted,
|
||||||
|
type App,
|
||||||
|
type Binding,
|
||||||
|
type Endpoint,
|
||||||
|
type Entry,
|
||||||
|
type Http,
|
||||||
|
} from "../downloads/settings.ts";
|
||||||
|
|
||||||
|
const NZBGET = CLIENTS.find((c) => c.provision === "nzbget-api")!;
|
||||||
|
const QBIT = CLIENTS.find((c) => c.provision === "qbittorrent-api")!;
|
||||||
|
const APP: App = { module: "sonarr", url: "http://127.0.0.1:8989", apiKey: "app-key", api: "v3" };
|
||||||
|
const MASK = "********";
|
||||||
|
|
||||||
|
interface Provider {
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
user?: string;
|
||||||
|
secret: string;
|
||||||
|
configured?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nzbget: Provider = { host: "ace.internal", port: 20201, user: "luffy", secret: "nzb-real" };
|
||||||
|
const qbit: Provider = { host: "ace.internal", port: 8112, user: "luffy", secret: "qbt-real" };
|
||||||
|
const jackett: Provider = { host: "ace.internal", port: 20204, secret: "jackett-real", configured: { rutracker: "RuTracker", torrent9: "Torrent9" } };
|
||||||
|
|
||||||
|
function binding(p: Provider, provision: string, extra: Record<string, unknown> = {}): Binding {
|
||||||
|
return {
|
||||||
|
provision,
|
||||||
|
from: "ace",
|
||||||
|
at: p.host,
|
||||||
|
as: "mesh_ace_sonarr",
|
||||||
|
serves: { scheme: "http", port: p.port, "url-base": "", ...(p.user ? { username: p.user } : {}), ...extra },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function endpoint(p: Provider, provision: string, credential = p.secret): Endpoint {
|
||||||
|
const w = wanted(provision, binding(p, provision), credential, provision !== "jackett-api");
|
||||||
|
if (!w.ok) throw new Error(w.problem);
|
||||||
|
return w.endpoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
const f = (name: string, value: unknown) => ({ name, value });
|
||||||
|
|
||||||
|
function client(id: number, name: string, implementation: string, host: string, port: number, password: string, extra: Record<string, unknown> = {}): Entry {
|
||||||
|
return {
|
||||||
|
id, name, implementation, enable: true, priority: 1, tags: [],
|
||||||
|
fields: [f("host", host), f("port", port), f("useSsl", false), f("urlBase", null), f("username", "luffy"), f("password", password), f("tvCategory", "Series"), ...Object.entries(extra).map(([k, v]) => f(k, v))],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function feed(id: number, name: string, baseUrl: string, jid: string, key: string, on = true): Entry {
|
||||||
|
return {
|
||||||
|
id, name, implementation: "Torznab", enableRss: on, enableAutomaticSearch: on, enableInteractiveSearch: on, priority: 25,
|
||||||
|
fields: [f("baseUrl", baseUrl), f("apiPath", `/api/v2.0/indexers/${jid}/results/torznab/`), f("apiKey", key), f("categories", [5000])],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Call {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
body?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A Servarr app and the three providers behind one fetch. */
|
||||||
|
function fakes(start: { clients?: Entry[]; indexers?: Entry[] }) {
|
||||||
|
const calls: Call[] = [];
|
||||||
|
const store: Record<string, Entry[]> = {
|
||||||
|
downloadclient: structuredClone(start.clients ?? []),
|
||||||
|
indexer: structuredClone(start.indexers ?? []),
|
||||||
|
};
|
||||||
|
let next = 100;
|
||||||
|
const secretOf: Record<string, string> = { downloadclient: "password", indexer: "apiKey" };
|
||||||
|
const masked = (e: Entry): Entry => ({ ...e, fields: e.fields!.map((x) => (x.name === "password" || x.name === "apiKey") && x.value ? { ...x, value: MASK } : { ...x }) });
|
||||||
|
const val = (e: Entry, n: string) => e.fields?.find((x) => x.name === n)?.value;
|
||||||
|
|
||||||
|
/** What the app's own test says: dialled from its container, with its stored secret for a mask. */
|
||||||
|
const appTest = (kind: string, e: Entry): { propertyName: string; errorMessage: string; isWarning: boolean }[] => {
|
||||||
|
let secret = val(e, secretOf[kind]);
|
||||||
|
if (secret === MASK) secret = val(store[kind].find((s) => s.id === e.id) ?? {}, secretOf[kind]);
|
||||||
|
if (kind === "downloadclient") {
|
||||||
|
const p = e.implementation === "Nzbget" ? nzbget : qbit;
|
||||||
|
if (val(e, "host") !== p.host || val(e, "port") !== p.port) return [{ propertyName: "Host", errorMessage: "Unable to connect", isWarning: false }];
|
||||||
|
if (secret !== p.secret || val(e, "username") !== p.user) return [{ propertyName: "Username", errorMessage: "Authentication Failure", isWarning: false }];
|
||||||
|
if (val(e, "tvCategory") === "") return [{ propertyName: "TvCategory", errorMessage: "A category is recommended", isWarning: true }];
|
||||||
|
if (e.implementation === "Nzbget" && val(e, "tvCategory") === "tv") return [{ propertyName: "TvCategory", errorMessage: "Category does not exist", isWarning: false }];
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const u = new URL(String(val(e, "baseUrl")));
|
||||||
|
if (u.hostname !== jackett.host || Number(u.port) !== jackett.port) return [{ propertyName: "BaseUrl", errorMessage: "Unable to connect", isWarning: false }];
|
||||||
|
if (secret !== jackett.secret) return [{ propertyName: "ApiKey", errorMessage: "Invalid API Key", isWarning: false }];
|
||||||
|
const id = /indexers\/([^/]+)\//.exec(String(val(e, "apiPath")))?.[1] ?? "";
|
||||||
|
if (!(id in jackett.configured!)) return [{ propertyName: "", errorMessage: "Unknown indexer", isWarning: false }];
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const http: Http = {
|
||||||
|
async fetch(url, init) {
|
||||||
|
const method = init?.method ?? "GET";
|
||||||
|
const body = init?.body && init.headers?.["Content-Type"] === "application/json" ? (JSON.parse(init.body) as Entry) : init?.body;
|
||||||
|
calls.push({ method, url, body });
|
||||||
|
const reply = (status: number, value?: unknown) => ({ status, text: async () => (value === undefined ? "" : typeof value === "string" ? value : JSON.stringify(value)) });
|
||||||
|
const u = new URL(url);
|
||||||
|
// Providers.
|
||||||
|
if (u.pathname === "/jsonrpc/version") {
|
||||||
|
const want = "Basic " + Buffer.from(`${nzbget.user}:${nzbget.secret}`).toString("base64");
|
||||||
|
return init?.headers?.Authorization === want ? reply(200, { result: "26.0" }) : reply(401);
|
||||||
|
}
|
||||||
|
if (u.pathname === "/api/v2/auth/login") {
|
||||||
|
const form = new URLSearchParams(String(init?.body ?? ""));
|
||||||
|
return form.get("username") === qbit.user && form.get("password") === qbit.secret ? reply(204) : reply(401, "Unauthorized");
|
||||||
|
}
|
||||||
|
if (u.pathname.endsWith("/torznab/api")) {
|
||||||
|
if (u.searchParams.get("apikey") !== jackett.secret) return reply(200, '<?xml version="1.0"?><error code="100" description="Invalid API Key" />');
|
||||||
|
const items = Object.entries(jackett.configured!).map(([id, t]) => `<indexer id="${id}" configured="true"><title>${t}</title></indexer>`).join("");
|
||||||
|
return reply(200, `<?xml version="1.0"?><indexers>${items}</indexers>`);
|
||||||
|
}
|
||||||
|
// The app.
|
||||||
|
if (init?.headers?.["X-Api-Key"] !== APP.apiKey) return reply(401);
|
||||||
|
const m = /^\/api\/v3\/(downloadclient|indexer)(?:\/(schema|test|\d+))?$/.exec(u.pathname);
|
||||||
|
if (!m) return reply(404);
|
||||||
|
const [, kind, sub] = m;
|
||||||
|
const force = u.searchParams.get("forceSave") === "true";
|
||||||
|
if (method === "GET" && !sub) return reply(200, store[kind].map(masked));
|
||||||
|
if (method === "GET" && sub === "schema") {
|
||||||
|
return reply(200, kind === "downloadclient"
|
||||||
|
? [client(0, "", "Nzbget", "localhost", 6789, MASK, {}), client(0, "", "QBittorrent", "localhost", 8080, "", {})].map((e) => ({ ...e, fields: e.fields!.map((x) => x.name === "tvCategory" ? { ...x, value: e.implementation === "Nzbget" ? "tv" : "tv-sonarr" } : x.name === "username" ? { ...x, value: null } : x) }))
|
||||||
|
: [{ ...feed(0, "", "", "x", "", false), supportsRss: true, supportsSearch: true, fields: [f("baseUrl", null), f("apiPath", "/api"), f("apiKey", null), f("categories", [5030, 5040])] }]);
|
||||||
|
}
|
||||||
|
if (method === "GET") {
|
||||||
|
const e = store[kind].find((s) => s.id === Number(sub));
|
||||||
|
return e ? reply(200, masked(e)) : reply(404);
|
||||||
|
}
|
||||||
|
if (method === "POST" && sub === "test") {
|
||||||
|
const fails = appTest(kind, body as Entry);
|
||||||
|
return fails.length ? reply(400, fails) : reply(200);
|
||||||
|
}
|
||||||
|
// Save: tested when enabled; a mask keeps what is stored.
|
||||||
|
const e = body as Entry;
|
||||||
|
const on = e.enable === true || e.enableRss === true || e.enableAutomaticSearch === true;
|
||||||
|
if (on) {
|
||||||
|
const fails = appTest(kind, e);
|
||||||
|
if (fails.some((x) => !x.isWarning) || (fails.length && !force)) return reply(400, fails);
|
||||||
|
}
|
||||||
|
if (method === "POST" && !sub) {
|
||||||
|
if (store[kind].some((s) => String(s.name).toLowerCase() === String(e.name).toLowerCase())) {
|
||||||
|
return reply(400, [{ propertyName: "Name", errorMessage: "Should be unique", isWarning: false }]);
|
||||||
|
}
|
||||||
|
const created = { ...e, id: next++ };
|
||||||
|
store[kind].push(created);
|
||||||
|
return reply(201, masked(created));
|
||||||
|
}
|
||||||
|
if (method === "PUT") {
|
||||||
|
const i = store[kind].findIndex((s) => s.id === Number(sub));
|
||||||
|
if (i < 0) return reply(404);
|
||||||
|
const was = store[kind][i];
|
||||||
|
store[kind][i] = { ...e, fields: e.fields!.map((x) => x.value === MASK ? { ...x, value: val(was, x.name) } : x) };
|
||||||
|
return reply(202, masked(store[kind][i]));
|
||||||
|
}
|
||||||
|
return reply(405);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const saves = () => calls.filter((c) => (c.method === "PUT" || (c.method === "POST" && !c.url.endsWith("/test"))) && c.url.includes("/api/v3/"));
|
||||||
|
return { http, calls, store, saves };
|
||||||
|
}
|
||||||
|
|
||||||
|
const aceClients = () => [
|
||||||
|
client(1, "NZBGet", "Nzbget", "nzbget", 6789, "nzb-real"),
|
||||||
|
client(2, "qBitTorrent", "QBittorrent", "qbittorrent", 8112, "qbt-real"),
|
||||||
|
];
|
||||||
|
|
||||||
|
test("the migration's download client is repointed, its category and everything else kept", async () => {
|
||||||
|
const f = fakes({ clients: aceClients() });
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(nzbget, "nzbget-api"), f.store.downloadclient.map((e) => ({ ...e })));
|
||||||
|
assert.deepEqual(out, [{ what: 'nzbget-api ("NZBGet")', result: "written", fields: ["host", "port"] }]);
|
||||||
|
const saved = f.store.downloadclient.find((e) => e.id === 1)!;
|
||||||
|
const v = (n: string) => saved.fields!.find((x) => x.name === n)?.value;
|
||||||
|
assert.equal(v("host"), "ace.internal");
|
||||||
|
assert.equal(v("port"), 20201);
|
||||||
|
assert.equal(v("tvCategory"), "Series");
|
||||||
|
assert.equal(v("password"), "nzb-real", "the password it held works, so it was kept, not rewritten");
|
||||||
|
assert.equal(saved.priority, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rerun: already as the mesh says, nothing saved", async () => {
|
||||||
|
const f = fakes({ clients: [client(1, "NZBGet", "Nzbget", "ace.internal", 20201, "nzb-real")] });
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(nzbget, "nzbget-api"), f.store.downloadclient);
|
||||||
|
assert.deepEqual(out, [{ what: 'nzbget-api ("NZBGet")', result: "unchanged" }]);
|
||||||
|
assert.equal(f.saves().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a stale password is replaced by the delivered one, which the provider took first", async () => {
|
||||||
|
const f = fakes({ clients: [client(2, "qBitTorrent", "QBittorrent", "ace.internal", 8112, "old-pass")] });
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qBitTorrent", endpoint(qbit, "qbittorrent-api"), f.store.downloadclient);
|
||||||
|
assert.deepEqual(out, [{ what: 'qbittorrent-api ("qBitTorrent")', result: "written", fields: ["password"] }]);
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "password")?.value, "qbt-real");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a minted credential is refused by the provider: nothing written, the accept named", async () => {
|
||||||
|
const f = fakes({ clients: aceClients() });
|
||||||
|
const ep = endpoint(nzbget, "nzbget-api", "a-value-the-mesh-minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "nzbget-api", ep), { took: false });
|
||||||
|
const remedy = acceptRemedy(APP, "ace", "nzbget-api", "nzbget", "ControlPassword", ep.from);
|
||||||
|
assert.match(remedy, /`secret accept ace sonarr nzbget-api --provider ace --from <file holding nzbget's ControlPassword>`/);
|
||||||
|
assert.doesNotMatch(remedy, /minted/);
|
||||||
|
assert.equal(f.calls.some((c) => c.url.includes("/api/v3/")), false, "the app was not even asked");
|
||||||
|
const q = endpoint(qbit, "qbittorrent-api", "minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "qbittorrent-api", q), { took: false });
|
||||||
|
const j = endpoint(jackett, "jackett-api", "minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "jackett-api", j), { took: false });
|
||||||
|
assert.equal(f.calls.find((c) => c.url.includes("apikey="))?.url.includes("jackett-real"), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a fresh app gets the mesh's client registered, under the mesh's name", async () => {
|
||||||
|
const f = fakes({});
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qbittorrent", endpoint(qbit, "qbittorrent-api"), []);
|
||||||
|
assert.equal(out[0].result, "created");
|
||||||
|
const e = f.store.downloadclient[0];
|
||||||
|
assert.equal(e.name, "qbittorrent");
|
||||||
|
assert.equal(e.enable, true);
|
||||||
|
assert.equal(e.fields!.find((x) => x.name === "tvCategory")?.value, "tv-sonarr", "the app's own default category");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("nzbget without the app's default category: registered with none, and said", async () => {
|
||||||
|
const f = fakes({});
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "nzbget", endpoint(nzbget, "nzbget-api"), []);
|
||||||
|
assert.equal(out[0].result, "notice");
|
||||||
|
assert.match((out[0] as { note: string }).note, /category left empty/);
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "tvCategory")?.value, "");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("somebody else's entries are never touched: another name of the same kind, and a clash of names", async () => {
|
||||||
|
const mine = client(7, "My seedbox", "QBittorrent", "seedbox.example", 443, "theirs");
|
||||||
|
const f = fakes({ clients: [mine] });
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qbittorrent", endpoint(qbit, "qbittorrent-api"), f.store.downloadclient);
|
||||||
|
assert.equal(out[0].result, "notice");
|
||||||
|
assert.deepEqual(f.store.downloadclient.find((e) => e.id === 7), mine);
|
||||||
|
// Same name in another case: refused, and the setting that adopts it named.
|
||||||
|
const g = fakes({ clients: aceClients() });
|
||||||
|
const clash = await reconcileClient(g.http, APP, NZBGET, "nzbget", endpoint(nzbget, "nzbget-api"), g.store.downloadclient);
|
||||||
|
assert.equal(clash[0].result, "refused");
|
||||||
|
assert.match((clash[0] as { problem: string }).problem, /downloads\.nzbget-api\.name to "NZBGet"/);
|
||||||
|
assert.equal(g.saves().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("jackett feeds: the migration's are repointed, a person's is left, a listed one is registered", async () => {
|
||||||
|
const personal = feed(9, "Seedbox jackett", "https://jackett.seedbox.example", "rutracker", "their-key");
|
||||||
|
const f = fakes({
|
||||||
|
indexers: [
|
||||||
|
feed(5, "Torznab - RuTracker", "https://indexers.zurag.be", "rutracker-ru", "jackett-real", false),
|
||||||
|
feed(6, "Torznab - Torrent9", "https://indexers.zurag.be", "torrent9", "jackett-real", false),
|
||||||
|
feed(4, "Jackett - RARBG", "http://jackett:9117", "therarbg", "old", false),
|
||||||
|
personal,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const configured = new Map(Object.entries(jackett.configured!));
|
||||||
|
const out = await reconcileIndexers(
|
||||||
|
f.http, APP, endpoint(jackett, "jackett-api"), configured,
|
||||||
|
{ adoptHosts: ["indexers.zurag.be", "jackett"], indexers: ["rutracker"] }, [], f.store.indexer,
|
||||||
|
);
|
||||||
|
const byWhat = Object.fromEntries(out.map((o) => [o.what + ":" + o.result, o]));
|
||||||
|
// torrent9: jackett has it; repointed, key already right, tested.
|
||||||
|
assert.ok(byWhat['jackett-api ("Torznab - Torrent9", jackett indexer torrent9):written']);
|
||||||
|
// rutracker-ru and therarbg: jackett has neither — repointed with the key, untested, and said.
|
||||||
|
assert.ok(byWhat['jackett-api ("Jackett - RARBG", jackett indexer therarbg):written']);
|
||||||
|
assert.ok(byWhat['jackett-api ("Jackett - RARBG", jackett indexer therarbg):notice']);
|
||||||
|
// rutracker is listed and nothing of the mesh's reads it: registered.
|
||||||
|
assert.ok(byWhat["jackett-api (jackett indexer rutracker):created"]);
|
||||||
|
assert.deepEqual(f.store.indexer.find((e) => e.id === 9), personal, "a person's jackett is not the mesh's");
|
||||||
|
const t9 = f.store.indexer.find((e) => e.id === 6)!;
|
||||||
|
assert.equal(t9.fields!.find((x) => x.name === "baseUrl")?.value, "http://ace.internal:20204");
|
||||||
|
assert.equal(t9.enableRss, false, "disabled stays disabled");
|
||||||
|
const created = f.store.indexer.find((e) => e.name === "Jackett - RuTracker")!;
|
||||||
|
assert.equal(created.enableRss, true);
|
||||||
|
assert.equal(f.calls.some((c) => c.method === "DELETE"), false, "nothing is ever deleted");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("jackett feeds rerun: nothing saved, and a remembered host keeps a moved jackett's feeds", async () => {
|
||||||
|
const f = fakes({ indexers: [feed(6, "Torznab - Torrent9", "http://ace.internal:20204", "torrent9", "jackett-real")] });
|
||||||
|
const configured = new Map(Object.entries(jackett.configured!));
|
||||||
|
const out = await reconcileIndexers(f.http, APP, endpoint(jackett, "jackett-api"), configured, { adoptHosts: [], indexers: ["torrent9"] }, [], f.store.indexer);
|
||||||
|
assert.deepEqual(out.map((o) => o.result), ["unchanged"]);
|
||||||
|
assert.equal(f.saves().length, 0);
|
||||||
|
// jackett moved to novox: the feed on ace.internal is still the mesh's because it was remembered.
|
||||||
|
const moved = { ...jackett, host: "novox.internal" };
|
||||||
|
const g = fakes({ indexers: [feed(6, "Torznab - Torrent9", "http://ace.internal:20204", "torrent9", "jackett-real")] });
|
||||||
|
const saved = jackett.host;
|
||||||
|
jackett.host = moved.host;
|
||||||
|
try {
|
||||||
|
const again = await reconcileIndexers(g.http, APP, endpoint(moved, "jackett-api"), configured, { adoptHosts: [], indexers: [] }, ["ace.internal"], g.store.indexer);
|
||||||
|
assert.equal(again[0].result, "written");
|
||||||
|
assert.equal(g.store.indexer[0].fields!.find((x) => x.name === "baseUrl")?.value, "http://novox.internal:20204");
|
||||||
|
} finally {
|
||||||
|
jackett.host = saved;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an enabled entry the app cannot test at the mesh's address is not saved", async () => {
|
||||||
|
const f = fakes({ clients: [client(1, "NZBGet", "Nzbget", "nzbget", 6789, "nzb-real")] });
|
||||||
|
const elsewhere = { ...nzbget, port: 1 };
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(elsewhere, "nzbget-api"), f.store.downloadclient);
|
||||||
|
assert.equal(out[0].result, "refused");
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "host")?.value, "nzbget", "left as it was");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("bindings: loopback, no user, no credential are refused; the base path is normalised", () => {
|
||||||
|
assert.equal(wanted("nzbget-api", { ...binding(nzbget, "nzbget-api"), at: "127.0.0.1" }, "x", true).ok, false);
|
||||||
|
assert.equal(wanted("nzbget-api", binding({ ...nzbget, user: undefined }, "nzbget-api"), "x", true).ok, false);
|
||||||
|
assert.equal(wanted("nzbget-api", binding(nzbget, "nzbget-api"), " \n", true).ok, false);
|
||||||
|
const w = wanted("jackett-api", binding(jackett, "jackett-api", { "url-base": "jackett/" }), "k", false);
|
||||||
|
assert.equal(w.ok && w.endpoint.urlBase, "/jackett");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a feed is read whole: base path in the base URL or in the API path", () => {
|
||||||
|
const e = feed(1, "x", "http://ace.internal:9117/jackett", "rutracker", "k");
|
||||||
|
assert.deepEqual(jackettFeed(e), { host: "ace.internal", id: "rutracker" });
|
||||||
|
assert.equal(jackettFeed({ ...e, implementation: "Newznab" }), undefined);
|
||||||
|
assert.equal(jackettFeed({ ...e, fields: [f("baseUrl", "https://api.nzbgeek.info"), f("apiPath", "/api")] }), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("settings: names default to the provider's, adoption and registration read from the merged file", () => {
|
||||||
|
assert.deepEqual(stepSettings({ node: "ace" }), { node: "ace", names: { "nzbget-api": "nzbget", "qbittorrent-api": "qbittorrent" }, indexers: { adoptHosts: [], indexers: [] } });
|
||||||
|
const s = stepSettings({ node: "ace", downloads: { "nzbget-api": { name: "NZBGet" }, "jackett-api": { "adopt-hosts": ["jackett"], indexers: ["torrent9", 3] } } });
|
||||||
|
assert.equal(s.names["nzbget-api"], "NZBGet");
|
||||||
|
assert.deepEqual(s.indexers, { adoptHosts: ["jackett"], indexers: ["torrent9"] });
|
||||||
|
});
|
||||||
|
|
||||||
|
// The four copies are one step. Where the siblings are checked out beside this module, they must
|
||||||
|
// be byte-identical — a fix made in one and not the others is a bug in three apps.
|
||||||
|
test("the step is the same in sonarr, radarr, lidarr and bookshelf", () => {
|
||||||
|
const here = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||||
|
const modules = dirname(here);
|
||||||
|
for (const file of ["downloads/settings.ts", "downloads/index.ts", "test/downloads.test.ts"]) {
|
||||||
|
const mine = readFileSync(join(here, file), "utf8");
|
||||||
|
for (const sibling of ["sonarr", "radarr", "lidarr", "bookshelf"]) {
|
||||||
|
const theirs = join(modules, sibling, file);
|
||||||
|
if (existsSync(theirs)) assert.equal(readFileSync(theirs, "utf8"), mine, `${sibling}/${file} differs`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// radarr's tools — ported from the shared hal sdk (novox/hq ADR 0039), importing radarr's own
|
||||||
|
// client. They return structured data (not pre-formatted text as hal did); the mesh serves them
|
||||||
|
// through the sdk's tool harness.
|
||||||
|
|
||||||
|
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||||
|
import { RadarrClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getRadarrTools(radarr: RadarrClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "radarr_status",
|
||||||
|
description: "Radarr status overview: version, movie count, monitored count, queue size.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const [status, content, queue] = await Promise.all([
|
||||||
|
radarr.getStatus(),
|
||||||
|
radarr.getContent(),
|
||||||
|
radarr.getQueue(),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
app: status.appName,
|
||||||
|
version: status.version,
|
||||||
|
movies: content.length,
|
||||||
|
monitored: content.filter((c) => c.monitored).length,
|
||||||
|
queue: queue.totalRecords,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "radarr_library",
|
||||||
|
description: "List movies from the Radarr library.",
|
||||||
|
input: { limit: { type: "number", description: "max items to return (default 50)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const items = await radarr.getContent(args.limit ? Number(args.limit) : 50);
|
||||||
|
return { count: items.length, movies: items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "radarr_search",
|
||||||
|
description: "Search the Radarr library for movies by title (filters existing content, not indexers).",
|
||||||
|
input: { query: { type: "string", description: "the search term" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const query = String(args.query);
|
||||||
|
return { query, results: await radarr.searchContent(query) };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "radarr_queue",
|
||||||
|
description: "Show the Radarr download queue — what is downloading and how far along.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const queue = await radarr.getQueue();
|
||||||
|
return { count: queue.totalRecords, items: queue.items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "radarr_calendar",
|
||||||
|
description: "Upcoming movie releases from the Radarr calendar.",
|
||||||
|
input: { days: { type: "number", description: "how many days to look ahead (default 7)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const days = args.days ? Number(args.days) : 7;
|
||||||
|
const items = await radarr.getCalendar(days);
|
||||||
|
items.sort((a, b) => a.date.localeCompare(b.date));
|
||||||
|
return { days, count: items.length, items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tools exist only when Radarr is configured; without a URL and key, radarr contributes none
|
||||||
|
// rather than failing the whole runtime.
|
||||||
|
registerModuleTools("radarr", (env) => {
|
||||||
|
try {
|
||||||
|
return getRadarrTools(RadarrClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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", "downloads/settings.ts", "downloads/index.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# sonarr's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/sonarr
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts downloads/settings.ts downloads/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/sonarr/dist /app/modules/sonarr/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/sonarr/dist/index.js,/app/modules/sonarr/dist/tools/index.js
|
||||||
|
# NOT dist/downloads/index.js: that is a step the host runs to completion, named by the `downloads`
|
||||||
|
# container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run inside the
|
||||||
|
# serving sidecar too, and exit it.
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
// The Sonarr API client — sonarr's own code, living in the module (novox/hq ADR 0039). Ported from
|
||||||
|
// the shared hal `arr` client, but self-contained: in nox each Servarr app owns its own copy, so a
|
||||||
|
// change to Sonarr's API rebuilds only sonarr and nothing else. Both this module's tools and its
|
||||||
|
// events entrypoint import it, and nothing outside sonarr does.
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
// Sonarr speaks the v3 API; its content is "series".
|
||||||
|
const API_VERSION = "v3";
|
||||||
|
const CONTENT_ENDPOINT = "series";
|
||||||
|
const APP_NAME = "Sonarr";
|
||||||
|
|
||||||
|
export interface SonarrQueueItem {
|
||||||
|
/** The queue record id — stable while the item is in the queue, so events can diff on it. */
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
status: string;
|
||||||
|
size: string;
|
||||||
|
sizeleft: string;
|
||||||
|
timeleft?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SonarrCalendarItem {
|
||||||
|
title: string;
|
||||||
|
date: string;
|
||||||
|
overview?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SonarrContentItem {
|
||||||
|
title: string;
|
||||||
|
year?: number;
|
||||||
|
status?: string;
|
||||||
|
monitored: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SonarrClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly apiKey: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the module's resolved environment. The URL defaults to the server on this node
|
||||||
|
* (the runtime shares its network), and the API key is read from MESH_SONARR_API_KEY or, failing
|
||||||
|
* that, discovered from the server's own config.xml under MESH_SONARR_CONFIG_DIR — the same file
|
||||||
|
* Sonarr writes it to, so a running server needs nothing configured by hand (as plex does with
|
||||||
|
* its token). Throws when no key can be found, so the tools/events simply do not load (the harness
|
||||||
|
* treats the throw as "exposes nothing").
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): SonarrClient {
|
||||||
|
const url = env.MESH_SONARR_URL ?? `http://127.0.0.1:${env.MESH_SONARR_PORT ?? "8989"}`;
|
||||||
|
const configDir = env.MESH_SONARR_CONFIG_DIR ?? "/config";
|
||||||
|
const apiKey = env.MESH_SONARR_API_KEY ?? SonarrClient.detectApiKey(configDir);
|
||||||
|
if (!apiKey) {
|
||||||
|
throw new Error("Sonarr not configured — set MESH_SONARR_API_KEY or make the config dir readable");
|
||||||
|
}
|
||||||
|
return new SonarrClient(url, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Discover the API key from the server's config.xml, falling back to null. Every Servarr app
|
||||||
|
* writes <ApiKey> into config.xml at the root of its config directory. */
|
||||||
|
static detectApiKey(configDir: string): string | null {
|
||||||
|
const config = join(configDir, "config.xml");
|
||||||
|
if (existsSync(config)) {
|
||||||
|
const match = readFileSync(config, "utf8").match(/<ApiKey>([^<]+)<\/ApiKey>/);
|
||||||
|
if (match) return match[1];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async get(endpoint: string, params?: Record<string, string>): Promise<unknown> {
|
||||||
|
const url = new URL(`${this.baseUrl}/api/${API_VERSION}/${endpoint}`);
|
||||||
|
if (params) {
|
||||||
|
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||||
|
}
|
||||||
|
const res = await fetch(url.toString(), { headers: { "X-Api-Key": this.apiKey } });
|
||||||
|
if (!res.ok) throw new Error(`${APP_NAME} API /${endpoint}: ${res.status} ${await res.text()}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getStatus(): Promise<{ appName: string; version: string }> {
|
||||||
|
const data = (await this.get("system/status")) as { appName?: string; version?: string };
|
||||||
|
return { appName: data.appName || APP_NAME, version: data.version ?? "unknown" };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getContent(limit?: number): Promise<SonarrContentItem[]> {
|
||||||
|
const data = await this.get(CONTENT_ENDPOINT);
|
||||||
|
const items: any[] = Array.isArray(data) ? data : ((data as any)?.records ?? []);
|
||||||
|
const mapped = items.map((item) => ({
|
||||||
|
title: item.title ?? "Unknown",
|
||||||
|
year: item.year,
|
||||||
|
status: item.status,
|
||||||
|
monitored: item.monitored ?? true,
|
||||||
|
}));
|
||||||
|
return limit ? mapped.slice(0, limit) : mapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Library search is a filter over existing content, not an indexer lookup — same as hal's. */
|
||||||
|
async searchContent(term: string): Promise<SonarrContentItem[]> {
|
||||||
|
const all = await this.getContent();
|
||||||
|
const lower = term.toLowerCase();
|
||||||
|
return all.filter((item) => item.title.toLowerCase().includes(lower));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getQueue(): Promise<{ totalRecords: number; items: SonarrQueueItem[] }> {
|
||||||
|
const data = (await this.get("queue", { pageSize: "50" })) as { totalRecords?: number; records?: any[] };
|
||||||
|
const records = data.records ?? [];
|
||||||
|
return {
|
||||||
|
totalRecords: data.totalRecords ?? records.length,
|
||||||
|
items: records.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
title: r.title ?? r.series?.title ?? "Unknown",
|
||||||
|
status: r.status ?? "unknown",
|
||||||
|
size: formatBytes(r.size ?? 0),
|
||||||
|
sizeleft: formatBytes(r.sizeleft ?? 0),
|
||||||
|
timeleft: r.timeleft,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCalendar(days = 7): Promise<SonarrCalendarItem[]> {
|
||||||
|
const start = new Date().toISOString().split("T")[0];
|
||||||
|
const end = new Date(Date.now() + days * 86400000).toISOString().split("T")[0];
|
||||||
|
const data = await this.get("calendar", { start, end });
|
||||||
|
const items: any[] = Array.isArray(data) ? data : [];
|
||||||
|
return items.map((item) => ({
|
||||||
|
title: item.title ?? item.series?.title ?? "Unknown",
|
||||||
|
date: item.airDateUtc ?? "",
|
||||||
|
overview: item.overview?.slice(0, 150),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes === 0) return "0 B";
|
||||||
|
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||||
|
return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
// The downloads step — run once by the host after the app's server starts, and again whenever a
|
||||||
|
// binding, a pair credential or the step's settings change (the container's `restart-on`,
|
||||||
|
// novox/hq ADR 0099). Byte-identical in sonarr, radarr, lidarr and bookshelf; see settings.ts.
|
||||||
|
//
|
||||||
|
// **A step, not a loop**: everything it does is a function of files the mesh writes, and the host
|
||||||
|
// already knows when they change. It connects to no broker.
|
||||||
|
//
|
||||||
|
// Exits non-zero when anything could not be put right — a refused credential, an unreachable
|
||||||
|
// provider, an entry the app would not save — so the node reports the step failed and the host
|
||||||
|
// runs it again on the next apply. Declared last in the manifest, so its failing gates nothing
|
||||||
|
// else of the module's (novox/hq ADR 0136).
|
||||||
|
//
|
||||||
|
// Reads, in MESH_DOWNLOADS_DIR, `<provision>.json` (the binding), `<provision>.secret` (the pair
|
||||||
|
// credential) and the settings file; remembers in MESH_DOWNLOADS_MEMORY the jackett hosts it has
|
||||||
|
// pointed feeds at, so a jackett that moves takes its feeds with it. Never prints a credential.
|
||||||
|
|
||||||
|
import { mkdir, rename, writeFile } from "node:fs/promises";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CLIENTS,
|
||||||
|
JACKETT,
|
||||||
|
acceptRemedy,
|
||||||
|
appConfig,
|
||||||
|
appReady,
|
||||||
|
listEntries,
|
||||||
|
providerTakes,
|
||||||
|
readIfThere,
|
||||||
|
readJson,
|
||||||
|
reconcileClient,
|
||||||
|
reconcileIndexers,
|
||||||
|
scrub,
|
||||||
|
stepSettings,
|
||||||
|
wanted,
|
||||||
|
type App,
|
||||||
|
type Binding,
|
||||||
|
type Http,
|
||||||
|
type Entry,
|
||||||
|
type Outcome,
|
||||||
|
type Took,
|
||||||
|
} from "./settings.js";
|
||||||
|
|
||||||
|
const module = process.env.MESH_DOWNLOADS_APP ?? "app";
|
||||||
|
const dir = process.env.MESH_DOWNLOADS_DIR ?? "/run/downloads";
|
||||||
|
const settingsFile = process.env.MESH_DOWNLOADS_SETTINGS ?? join(dir, "downloads.json");
|
||||||
|
const memoryFile = process.env.MESH_DOWNLOADS_MEMORY ?? "/var/lib/downloads/memory.json";
|
||||||
|
const waitSeconds = Number(process.env.MESH_DOWNLOADS_WAIT_SECONDS ?? "180");
|
||||||
|
const tag = `[${module}-downloads]`;
|
||||||
|
|
||||||
|
const http: Http = { fetch: (u, init) => fetch(u, init) };
|
||||||
|
const secrets: string[] = [];
|
||||||
|
const say = (line: string) => console.log(scrub(`${tag} ${line}`, secrets));
|
||||||
|
const fail = (line: string) => console.error(scrub(`${tag} ${line}`, secrets));
|
||||||
|
|
||||||
|
const config = appConfig((await readIfThere(process.env.MESH_DOWNLOADS_APP_CONFIG)) ?? "");
|
||||||
|
if (!config.apiKey) {
|
||||||
|
fail(`no API key in ${module}'s config.xml yet — ${module} writes it on its first start; the step runs again on the next apply`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
secrets.push(config.apiKey);
|
||||||
|
const app: App = {
|
||||||
|
module,
|
||||||
|
url: `${(process.env.MESH_DOWNLOADS_APP_URL ?? "http://127.0.0.1").replace(/\/$/, "")}${config.urlBase}`,
|
||||||
|
apiKey: config.apiKey,
|
||||||
|
api: process.env.MESH_DOWNLOADS_API ?? "v3",
|
||||||
|
};
|
||||||
|
const settings = stepSettings(await readJson(settingsFile));
|
||||||
|
|
||||||
|
if (!(await appReady(http, app, waitSeconds * 1000))) {
|
||||||
|
fail(`${module} did not answer at ${app.url} within ${waitSeconds}s`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
|
||||||
|
// The download clients.
|
||||||
|
let clients: Entry[];
|
||||||
|
try {
|
||||||
|
clients = await listEntries(http, app, "downloadclient");
|
||||||
|
} catch (err) {
|
||||||
|
fail(err instanceof Error ? err.message : String(err));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
for (const kind of CLIENTS) {
|
||||||
|
const credential = await readIfThere(join(dir, `${kind.provision}.secret`));
|
||||||
|
if (credential) secrets.push(credential.trim());
|
||||||
|
const w = wanted(kind.provision, (await readJson(join(dir, `${kind.provision}.json`))) as Binding | undefined, credential, true);
|
||||||
|
// `in`, not `!w.ok`: the Dockerfile compiles without strict, where a boolean discriminant does not
|
||||||
|
// narrow.
|
||||||
|
if ("problem" in w) {
|
||||||
|
outcomes.push({ what: kind.provision, result: "refused", problem: w.problem });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const ep = w.endpoint;
|
||||||
|
try {
|
||||||
|
if (!(await providerTakes(http, kind.provision, ep)).took) {
|
||||||
|
outcomes.push({
|
||||||
|
what: kind.provision,
|
||||||
|
result: "refused",
|
||||||
|
problem: acceptRemedy(app, settings.node, kind.provision, kind.provider, kind.secretName, ep.from),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: kind.provision,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${kind.provider} could not be asked whether it takes the credential at ${ep.host}:${ep.port}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
outcomes.push(...(await reconcileClient(http, app, kind, settings.names[kind.provision], ep, clients)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The indexers, through jackett.
|
||||||
|
{
|
||||||
|
const credential = await readIfThere(join(dir, `${JACKETT}.secret`));
|
||||||
|
if (credential) secrets.push(credential.trim());
|
||||||
|
const w = wanted(JACKETT, (await readJson(join(dir, `${JACKETT}.json`))) as Binding | undefined, credential, false);
|
||||||
|
if ("problem" in w) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: w.problem });
|
||||||
|
} else {
|
||||||
|
const ep = w.endpoint;
|
||||||
|
let took: Took | undefined;
|
||||||
|
try {
|
||||||
|
took = await providerTakes(http, JACKETT, ep);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: JACKETT,
|
||||||
|
result: "refused",
|
||||||
|
problem: `jackett could not be asked whether it takes the key at ${ep.host}:${ep.port}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (took && !took.took) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: acceptRemedy(app, settings.node, JACKETT, "jackett", "API key", ep.from) });
|
||||||
|
} else if (took) {
|
||||||
|
const memory = ((await readJson(memoryFile)) ?? {}) as Record<string, { hosts?: string[] } | undefined>;
|
||||||
|
const remembered = Array.isArray(memory[JACKETT]?.hosts) ? (memory[JACKETT]?.hosts as string[]) : [];
|
||||||
|
try {
|
||||||
|
const indexers = await listEntries(http, app, "indexer");
|
||||||
|
outcomes.push(
|
||||||
|
...(await reconcileIndexers(http, app, ep, took.configured ?? new Map(), settings.indexers, remembered, indexers)),
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({ what: JACKETT, result: "refused", problem: err instanceof Error ? err.message : String(err) });
|
||||||
|
}
|
||||||
|
// Remember where the feeds now point, so they are still recognised as the mesh's if jackett
|
||||||
|
// moves. Written whole and renamed, so a crash leaves the old memory, never half of one.
|
||||||
|
const hosts = [...new Set([...remembered, ep.host.toLowerCase()])].sort();
|
||||||
|
if (hosts.join() !== [...remembered].sort().join()) {
|
||||||
|
try {
|
||||||
|
await mkdir(dirname(memoryFile), { recursive: true });
|
||||||
|
await writeFile(`${memoryFile}.tmp`, JSON.stringify({ ...memory, [JACKETT]: { hosts } }, null, 2) + "\n", { mode: 0o600 });
|
||||||
|
await rename(`${memoryFile}.tmp`, memoryFile);
|
||||||
|
} catch (err) {
|
||||||
|
outcomes.push({
|
||||||
|
what: JACKETT,
|
||||||
|
result: "notice",
|
||||||
|
note: `could not remember ${ep.host} as a jackett host (${err instanceof Error ? err.message : String(err)}); if jackett moves, list it in downloads.jackett-api.adopt-hosts`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let failed = 0;
|
||||||
|
for (const o of outcomes) {
|
||||||
|
switch (o.result) {
|
||||||
|
case "unchanged":
|
||||||
|
say(`${o.what}: already as the mesh says${o.untested ? "" : "; connection tested"}`);
|
||||||
|
break;
|
||||||
|
case "written":
|
||||||
|
say(`${o.what}: wrote ${o.fields.join(", ")}${o.untested ? "" : "; connection tested"}`);
|
||||||
|
break;
|
||||||
|
case "created":
|
||||||
|
say(`${o.what}: registered; connection tested`);
|
||||||
|
break;
|
||||||
|
case "notice":
|
||||||
|
say(`${o.what}: ${o.note}`);
|
||||||
|
break;
|
||||||
|
case "refused":
|
||||||
|
failed++;
|
||||||
|
fail(`${o.what}: ${o.problem}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.exitCode = failed > 0 ? 1 : 0;
|
||||||
@@ -0,0 +1,778 @@
|
|||||||
|
// Where a Servarr app reaches its download clients and its indexer proxy — decided by the mesh,
|
||||||
|
// written into the app by the app's own API.
|
||||||
|
//
|
||||||
|
// **One file, four copies.** sonarr, radarr, lidarr and bookshelf (a Readarr fork) keep their
|
||||||
|
// download clients and indexers behind the same API — `/api/v3/…` for the first two, `/api/v1/…`
|
||||||
|
// for the others — so this step is the same code in each. Each module builds from its own
|
||||||
|
// directory (novox/hq ADR 0069), so each carries a byte-identical copy under `downloads/`;
|
||||||
|
// `test/downloads.test.ts` checks the copies agree wherever the siblings are checked out beside
|
||||||
|
// it. Change all four together.
|
||||||
|
//
|
||||||
|
// **Why this exists.** The app keeps its connection to nzbget, qBittorrent and jackett in its own
|
||||||
|
// database, not in a file, so the mesh has nowhere to write `${bound:nzbget-api:at}` for it. The
|
||||||
|
// module requires `nzbget-api`, `qbittorrent-api` and `jackett-api`; the mesh delivers, for each,
|
||||||
|
// a binding (where the provider is — `at` — and what it serves: `port`, `scheme`, `url-base`, and
|
||||||
|
// for a download client the `username`) and a pair credential (nzbget's ControlPassword,
|
||||||
|
// qBittorrent's WebUI password, jackett's API key — each the provider's one and only, accepted by
|
||||||
|
// the operator per pair; the mesh cannot mint them). This step reads those files and makes the
|
||||||
|
// app's entries say the same thing.
|
||||||
|
//
|
||||||
|
// **Which entries are the mesh's.** Never a guess from what an entry looks like:
|
||||||
|
// - a download client is the mesh's when its name is the one the module's settings give for
|
||||||
|
// that provision (`downloads.<provision>.name`) and its kind is that provider's. On a fresh
|
||||||
|
// machine the step registers it under that name; on a migrated one the assignment names the
|
||||||
|
// entry the migration adopts ("NZBGet" on ace).
|
||||||
|
// - a Torznab indexer is the mesh's when it reads a jackett feed
|
||||||
|
// (`…/api/v2.0/indexers/<id>/results/torznab`) on a host the mesh put there — the bound `at`,
|
||||||
|
// one it bound before (remembered by the step), or one the settings adopt
|
||||||
|
// (`downloads.jackett-api.adopt-hosts`, which is how a migration names the entries that pointed
|
||||||
|
// at the old container). `downloads.jackett-api.indexers` lists the jackett indexers the app
|
||||||
|
// should have; one missing is registered.
|
||||||
|
// Everything else — every entry a person made, an nzbget elsewhere, a seedbox's jackett, a Newznab
|
||||||
|
// indexer — is left exactly as it is. **Nothing is ever deleted.**
|
||||||
|
//
|
||||||
|
// **Only the connection, and only when it differs.** Host, port, TLS, base path, user name and
|
||||||
|
// the credential. Categories, priorities, "enabled", seed criteria and every other choice made in
|
||||||
|
// the app are left alone. The stored credential cannot be read back (the app masks it), so the
|
||||||
|
// step asks the app to test the entry with the mesh's host and port and the credential it already
|
||||||
|
// holds: passing, the credential is already the provider's one and only; failing, the delivered
|
||||||
|
// credential is written.
|
||||||
|
//
|
||||||
|
// **A credential the provider refuses is never written.** Until the operator accepts the
|
||||||
|
// provider's secret for this pair, the mesh delivers a value it minted itself, which no provider
|
||||||
|
// will ever accept (novox/hq ADR 0092). Writing it would replace a working password with a dead
|
||||||
|
// one. So it is tried against the provider first; refused, nothing of that provision is written
|
||||||
|
// and the step fails naming the `secret accept` that fixes it.
|
||||||
|
//
|
||||||
|
// Pure logic and a small HTTP seam, so it is tested against fake servers (test/downloads.test.ts).
|
||||||
|
// Never prints a credential, an API key, or a URL carrying one.
|
||||||
|
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
|
||||||
|
/** A download-client provision and the shape of its entry in the app. */
|
||||||
|
export interface ClientKind {
|
||||||
|
provision: "nzbget-api" | "qbittorrent-api";
|
||||||
|
/** The app's `implementation` for it. */
|
||||||
|
implementation: "Nzbget" | "QBittorrent";
|
||||||
|
/** The provider, as a person calls it. */
|
||||||
|
provider: string;
|
||||||
|
/** What the pair credential is, in the provider's words. */
|
||||||
|
secretName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CLIENTS: readonly ClientKind[] = [
|
||||||
|
{ provision: "nzbget-api", implementation: "Nzbget", provider: "nzbget", secretName: "ControlPassword" },
|
||||||
|
{ provision: "qbittorrent-api", implementation: "QBittorrent", provider: "qBittorrent", secretName: "WebUI password" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const JACKETT = "jackett-api";
|
||||||
|
|
||||||
|
/** What the mesh wrote at `binds.<provision>`: the binding document. */
|
||||||
|
export interface Binding {
|
||||||
|
provision?: string;
|
||||||
|
from?: string;
|
||||||
|
at?: string;
|
||||||
|
as?: string;
|
||||||
|
serves?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a provider is, as the mesh bound it, and the credential for it. */
|
||||||
|
export interface Endpoint {
|
||||||
|
scheme: "http" | "https";
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
/** "" at the root, otherwise "/base" — one leading slash, none trailing. */
|
||||||
|
urlBase: string;
|
||||||
|
/** The user a download client logs in as; "" for jackett, which takes a key. */
|
||||||
|
username: string;
|
||||||
|
credential: string;
|
||||||
|
/** The provider's node, for the `secret accept` remedy. */
|
||||||
|
from: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Wanted = { ok: true; endpoint: Endpoint } | { ok: false; problem: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The endpoint the mesh says to use, from a binding and its pair credential.
|
||||||
|
*
|
||||||
|
* Refused rather than guessed when the binding cannot be dialled from the app's own container: a
|
||||||
|
* loopback `at` — what the mesh hands a machine that is not on the private network — is the app's
|
||||||
|
* container itself.
|
||||||
|
*/
|
||||||
|
export function wanted(
|
||||||
|
provision: string,
|
||||||
|
binding: Binding | undefined,
|
||||||
|
credential: string | undefined,
|
||||||
|
needsUser: boolean,
|
||||||
|
): Wanted {
|
||||||
|
if (!binding) {
|
||||||
|
return { ok: false, problem: `no binding for ${provision} was delivered — the mesh writes it before this step runs` };
|
||||||
|
}
|
||||||
|
const host = typeof binding.at === "string" ? binding.at.trim() : "";
|
||||||
|
const serves = binding.serves ?? {};
|
||||||
|
const port = Number(serves.port);
|
||||||
|
if (!host) return { ok: false, problem: `the ${provision} binding names no host (at)` };
|
||||||
|
if (isLoopback(host)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
problem:
|
||||||
|
`the ${provision} binding says the provider is at ${host}, which from the app's own container is the ` +
|
||||||
|
`app itself. The mesh hands loopback to a machine that is not on the private network; put it on the ` +
|
||||||
|
`private network so the provider has an address the app can dial`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves no usable port (${String(serves.port)})` };
|
||||||
|
}
|
||||||
|
const scheme = typeof serves.scheme === "string" && serves.scheme ? serves.scheme : "http";
|
||||||
|
if (scheme !== "http" && scheme !== "https") {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves scheme ${scheme}, which the app cannot dial` };
|
||||||
|
}
|
||||||
|
const username = typeof serves.username === "string" ? serves.username.trim() : "";
|
||||||
|
if (needsUser && !username) {
|
||||||
|
return { ok: false, problem: `the ${provision} binding serves no username for the app to log in as` };
|
||||||
|
}
|
||||||
|
const key = (credential ?? "").trim();
|
||||||
|
if (!key) return { ok: false, problem: `the ${provision} credential is empty or was not delivered` };
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
endpoint: {
|
||||||
|
scheme,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
urlBase: normBase(serves["url-base"]),
|
||||||
|
username,
|
||||||
|
credential: key,
|
||||||
|
from: typeof binding.from === "string" ? binding.from : "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A URL base as "" or "/x/y": slashes trimmed, one put back in front. */
|
||||||
|
export function normBase(v: unknown): string {
|
||||||
|
const s = typeof v === "string" ? v.trim().replace(/^\/+|\/+$/g, "") : "";
|
||||||
|
return s === "" ? "" : `/${s}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLoopback(host: string): boolean {
|
||||||
|
const h = host.toLowerCase();
|
||||||
|
return h === "localhost" || h === "::1" || h === "[::1]" || /^127\./.test(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hostForUrl(host: string): string {
|
||||||
|
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The provider's base URL, as the step dials it and as the app is given it. */
|
||||||
|
export function baseUrl(ep: Endpoint): string {
|
||||||
|
return `${ep.scheme}://${hostForUrl(ep.host)}:${ep.port}${ep.urlBase}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// HTTP
|
||||||
|
|
||||||
|
/** The HTTP the step needs, so a test can stand fakes in for the app and the providers. */
|
||||||
|
export interface Http {
|
||||||
|
fetch(
|
||||||
|
url: string,
|
||||||
|
init?: { method?: string; headers?: Record<string, string>; body?: string },
|
||||||
|
): Promise<{ status: number; text(): Promise<string> }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app, as the step reaches it from the host. */
|
||||||
|
export interface App {
|
||||||
|
/** The module, for messages and the remedy: sonarr, radarr, lidarr, bookshelf. */
|
||||||
|
module: string;
|
||||||
|
/** Its own URL, base path included. */
|
||||||
|
url: string;
|
||||||
|
apiKey: string;
|
||||||
|
/** v3 (sonarr, radarr) or v1 (lidarr, bookshelf). */
|
||||||
|
api: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Answer {
|
||||||
|
status: number;
|
||||||
|
body: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function appCall(http: Http, app: App, method: string, path: string, body?: unknown): Promise<Answer> {
|
||||||
|
const res = await http.fetch(`${app.url.replace(/\/$/, "")}/api/${app.api}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
"X-Api-Key": app.apiKey,
|
||||||
|
Accept: "application/json",
|
||||||
|
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||||
|
},
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
let parsed: unknown = undefined;
|
||||||
|
if (text) {
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(text) as unknown;
|
||||||
|
} catch {
|
||||||
|
parsed = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { status: res.status, body: parsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function appGet(http: Http, app: App, path: string): Promise<unknown> {
|
||||||
|
const a = await appCall(http, app, "GET", path);
|
||||||
|
if (a.status < 200 || a.status >= 300) throw new Error(`${app.module} GET ${path} answered ${a.status}`);
|
||||||
|
return a.body;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One of the app's validation failures: the only parts of an answer the step ever prints. */
|
||||||
|
interface Failure {
|
||||||
|
property: string;
|
||||||
|
message: string;
|
||||||
|
warning: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function failuresOf(body: unknown): Failure[] {
|
||||||
|
const list = Array.isArray(body) ? body : [];
|
||||||
|
return list.map((f) => {
|
||||||
|
const o = (f ?? {}) as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
property: String(o.propertyName ?? ""),
|
||||||
|
message: String(o.errorMessage ?? ""),
|
||||||
|
warning: o.isWarning === true,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One shape rather than a union on `ok`: the Dockerfile compiles without strict, where a boolean
|
||||||
|
* discriminant does not narrow.
|
||||||
|
*/
|
||||||
|
interface Verdict {
|
||||||
|
ok: boolean;
|
||||||
|
/** Warnings the app raised on a pass; errors (and any warnings) on a failure. */
|
||||||
|
failures: Failure[];
|
||||||
|
status: number;
|
||||||
|
saved?: Entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function verdict(a: Answer): Verdict {
|
||||||
|
if (a.status >= 200 && a.status < 300) return { ok: true, failures: [], status: a.status };
|
||||||
|
const failures = failuresOf(a.body);
|
||||||
|
if (a.status === 400 && failures.length > 0 && failures.every((f) => f.warning)) return { ok: true, failures, status: a.status };
|
||||||
|
return { ok: false, failures, status: a.status };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's own test of an entry, from the app's own container. */
|
||||||
|
async function appTest(http: Http, app: App, resource: string, entry: Entry): Promise<Verdict> {
|
||||||
|
return verdict(await appCall(http, app, "POST", `/${resource}/test`, entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save an entry. The app tests an enabled entry before saving it; a test that passes with only
|
||||||
|
* warnings ("a category is recommended") is saved with `forceSave`, the same as pressing "save
|
||||||
|
* anyway" in its screen. An error is never forced.
|
||||||
|
*/
|
||||||
|
async function appSave(http: Http, app: App, resource: string, entry: Entry, create: boolean): Promise<Verdict> {
|
||||||
|
const path = create ? `/${resource}` : `/${resource}/${entry.id}`;
|
||||||
|
const method = create ? "POST" : "PUT";
|
||||||
|
let a = await appCall(http, app, method, path, entry);
|
||||||
|
let v = verdict(a);
|
||||||
|
if (v.ok && (a.status < 200 || a.status >= 300)) {
|
||||||
|
a = await appCall(http, app, method, `${path}?forceSave=true`, entry);
|
||||||
|
v = verdict(a);
|
||||||
|
if (v.ok && (a.status < 200 || a.status >= 300)) {
|
||||||
|
return { ok: false, failures: failuresOf(a.body), status: a.status };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!v.ok) return v;
|
||||||
|
return { ...v, saved: (a.body ?? undefined) as Entry | undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Entries
|
||||||
|
|
||||||
|
/** An entry as the app's API gives it: a download client or an indexer. */
|
||||||
|
export interface Entry {
|
||||||
|
id?: number;
|
||||||
|
name?: string;
|
||||||
|
implementation?: string;
|
||||||
|
enable?: boolean;
|
||||||
|
enableRss?: boolean;
|
||||||
|
enableAutomaticSearch?: boolean;
|
||||||
|
enableInteractiveSearch?: boolean;
|
||||||
|
supportsRss?: boolean;
|
||||||
|
supportsSearch?: boolean;
|
||||||
|
fields?: { name: string; value?: unknown; [k: string]: unknown }[];
|
||||||
|
[k: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function field(e: Entry, name: string): unknown {
|
||||||
|
return e.fields?.find((f) => f.name === name)?.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The entry with these fields' values replaced — added when the app's shape lacks one. */
|
||||||
|
export function withFields(e: Entry, values: Record<string, unknown>): Entry {
|
||||||
|
const fields = (e.fields ?? []).map((f) => (f.name in values ? { ...f, value: values[f.name] } : { ...f }));
|
||||||
|
for (const [name, value] of Object.entries(values)) {
|
||||||
|
if (!fields.some((f) => f.name === name)) fields.push({ name, value });
|
||||||
|
}
|
||||||
|
return { ...e, fields };
|
||||||
|
}
|
||||||
|
|
||||||
|
function enabled(e: Entry): boolean {
|
||||||
|
return e.enable === true || e.enableRss === true || e.enableAutomaticSearch === true || e.enableInteractiveSearch === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What one provision, or one entry of it, came to. */
|
||||||
|
export type Outcome =
|
||||||
|
| { what: string; result: "unchanged"; untested?: boolean }
|
||||||
|
| { what: string; result: "written"; fields: string[]; untested?: boolean }
|
||||||
|
| { what: string; result: "created"; fields: string[] }
|
||||||
|
| { what: string; result: "notice"; note: string }
|
||||||
|
| { what: string; result: "refused"; problem: string };
|
||||||
|
|
||||||
|
function said(fs: Failure[]): string {
|
||||||
|
return fs.length === 0 ? "no reason given" : fs.map((f) => (f.property ? `${f.property}: ${f.message}` : f.message)).join("; ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring one of the mesh's entries in line: `connection` is the non-secret fields as the mesh says
|
||||||
|
* them, `differs` which of them the entry does not already say, `secretField` where the credential
|
||||||
|
* goes. Never throws: every failure is an outcome with a reason.
|
||||||
|
*/
|
||||||
|
export async function reconcileEntry(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
resource: "downloadclient" | "indexer",
|
||||||
|
what: string,
|
||||||
|
current: Entry,
|
||||||
|
connection: Record<string, unknown>,
|
||||||
|
differs: string[],
|
||||||
|
secretField: string,
|
||||||
|
credential: string,
|
||||||
|
testable = true,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
try {
|
||||||
|
const base = withFields(current, connection); // the credential as the app holds it — masked
|
||||||
|
if (!testable) {
|
||||||
|
// Nothing to test against (jackett no longer has the indexer it names): the connection is
|
||||||
|
// still the mesh's to state, and the key goes with it when the address changes.
|
||||||
|
if (differs.length === 0) return { what, result: "unchanged", untested: true };
|
||||||
|
const s = await appSave(http, app, resource, withFields(base, { [secretField]: credential }), false);
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not save it: ${said(s.failures)}` };
|
||||||
|
return { what, result: "written", fields: [...differs, secretField], untested: true };
|
||||||
|
}
|
||||||
|
const first = await appTest(http, app, resource, base);
|
||||||
|
if (first.ok) {
|
||||||
|
// The credential the app holds already works against the provider at the mesh's address —
|
||||||
|
// and the provider has exactly one, so it is the delivered one.
|
||||||
|
if (differs.length === 0) return { what, result: "unchanged" };
|
||||||
|
const s = await appSave(http, app, resource, base, false);
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not save it: ${said(s.failures)}` };
|
||||||
|
return { what, result: "written", fields: differs };
|
||||||
|
}
|
||||||
|
// The app's test failed with what it holds. The delivered credential was already checked
|
||||||
|
// against the provider, so writing it is safe; the app tests an enabled entry again on save.
|
||||||
|
const s = await appSave(http, app, resource, withFields(base, { [secretField]: credential }), false);
|
||||||
|
if (!s.ok) {
|
||||||
|
return {
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${app.module} tested it at the mesh's address and would not save it (nothing was written): ${said(s.failures)}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const stored = (await appGet(http, app, `/${resource}/${current.id}`)) as Entry;
|
||||||
|
const second = await appTest(http, app, resource, stored);
|
||||||
|
const fields = [...differs, secretField];
|
||||||
|
if (second.ok) return { what, result: "written", fields };
|
||||||
|
const why = `written (${fields.join(", ")}), and ${app.module}'s own test still fails: ${said(second.failures)}`;
|
||||||
|
return enabled(stored) ? { what, result: "refused", problem: why } : { what, result: "notice", note: `${why} — it is disabled, so nothing uses it` };
|
||||||
|
} catch (err) {
|
||||||
|
return { what, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a new entry from the app's own template for that kind: its defaults, the name, the
|
||||||
|
* connection and the credential. A category the provider does not have (nzbget refuses one it was
|
||||||
|
* not told about) is left empty rather than failing the registration, and said.
|
||||||
|
*/
|
||||||
|
export async function createEntry(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
resource: "downloadclient" | "indexer",
|
||||||
|
what: string,
|
||||||
|
implementation: string,
|
||||||
|
name: string,
|
||||||
|
values: Record<string, unknown>,
|
||||||
|
): Promise<Outcome> {
|
||||||
|
try {
|
||||||
|
const schema = (await appGet(http, app, `/${resource}/schema`)) as Entry[];
|
||||||
|
const template = (schema ?? []).find((s) => s.implementation === implementation);
|
||||||
|
if (!template) return { what, result: "refused", problem: `${app.module} has no ${implementation} to register` };
|
||||||
|
let entry: Entry = withFields({ ...template, id: undefined, name }, values);
|
||||||
|
if (resource === "downloadclient") entry.enable = true;
|
||||||
|
else {
|
||||||
|
entry.enableRss = template.supportsRss !== false;
|
||||||
|
entry.enableAutomaticSearch = template.supportsSearch !== false;
|
||||||
|
entry.enableInteractiveSearch = template.supportsSearch !== false;
|
||||||
|
}
|
||||||
|
let s = await appSave(http, app, resource, entry, true);
|
||||||
|
let note = "";
|
||||||
|
if (!s.ok && s.failures.length > 0 && s.failures.every((f) => /category/i.test(f.property))) {
|
||||||
|
const emptied: Record<string, unknown> = {};
|
||||||
|
for (const f of entry.fields ?? []) if (/category$/i.test(f.name) && !/imported/i.test(f.name)) emptied[f.name] = "";
|
||||||
|
entry = withFields(entry, emptied);
|
||||||
|
s = await appSave(http, app, resource, entry, true);
|
||||||
|
note = " with its category left empty — the provider has none by the app's default name; set one in both";
|
||||||
|
}
|
||||||
|
if (!s.ok) return { what, result: "refused", problem: `${app.module} would not register it: ${said(s.failures)}` };
|
||||||
|
const created = s.saved;
|
||||||
|
if (created?.id !== undefined) {
|
||||||
|
const t = await appTest(http, app, resource, (await appGet(http, app, `/${resource}/${created.id}`)) as Entry);
|
||||||
|
if (!t.ok) {
|
||||||
|
return { what, result: "refused", problem: `registered as "${name}"${note}, and ${app.module}'s own test fails: ${said(t.failures)}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return note
|
||||||
|
? { what, result: "notice", note: `registered as "${name}"${note}` }
|
||||||
|
: { what, result: "created", fields: Object.keys(values) };
|
||||||
|
} catch (err) {
|
||||||
|
return { what, result: "refused", problem: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Providers: does it take the credential?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does the provider take this credential? `took` it does (for jackett, with the ids of the indexers
|
||||||
|
* it has configured); `refused` it said no; a thrown error when it could not be asked.
|
||||||
|
*/
|
||||||
|
export interface Took {
|
||||||
|
took: boolean;
|
||||||
|
configured?: Map<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function providerTakes(http: Http, provision: string, ep: Endpoint): Promise<Took> {
|
||||||
|
const base = baseUrl(ep);
|
||||||
|
if (provision === "nzbget-api") {
|
||||||
|
const auth = Buffer.from(`${ep.username}:${ep.credential}`).toString("base64");
|
||||||
|
const res = await http.fetch(`${base}/jsonrpc/version`, { method: "GET", headers: { Authorization: `Basic ${auth}` } });
|
||||||
|
await res.text();
|
||||||
|
if (res.status === 401 || res.status === 403) return { took: false };
|
||||||
|
if (res.status >= 200 && res.status < 300) return { took: true };
|
||||||
|
throw new Error(`nzbget answered ${res.status}`);
|
||||||
|
}
|
||||||
|
if (provision === "qbittorrent-api") {
|
||||||
|
const form = `username=${encodeURIComponent(ep.username)}&password=${encodeURIComponent(ep.credential)}`;
|
||||||
|
const res = await http.fetch(`${base}/api/v2/auth/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: form,
|
||||||
|
});
|
||||||
|
const text = (await res.text()).trim();
|
||||||
|
if (res.status === 401 || /^fails\.?$/i.test(text)) return { took: false };
|
||||||
|
if (res.status === 403) {
|
||||||
|
throw new Error(
|
||||||
|
"qBittorrent answered 403: it has banned this address after failed logins (WebUI\\BanDuration); it lifts by itself",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (res.status >= 200 && res.status < 300) return { took: true };
|
||||||
|
throw new Error(`qBittorrent answered ${res.status}`);
|
||||||
|
}
|
||||||
|
if (provision === JACKETT) {
|
||||||
|
const url = `${base}/api/v2.0/indexers/all/results/torznab/api?t=indexers&configured=true&apikey=${encodeURIComponent(ep.credential)}`;
|
||||||
|
const res = await http.fetch(url, { method: "GET" });
|
||||||
|
const text = await res.text();
|
||||||
|
if (res.status === 401 || res.status === 403) return { took: false };
|
||||||
|
if (res.status < 200 || res.status >= 300) throw new Error(`jackett answered ${res.status}`);
|
||||||
|
// jackett answers a wrong key 200 with an error document: code 100, "Invalid API Key".
|
||||||
|
if (/<error\b[^>]*\bcode="100"/i.test(text)) return { took: false };
|
||||||
|
if (/<error\b/i.test(text)) throw new Error("jackett answered with an error document");
|
||||||
|
return { took: true, configured: configuredIndexers(text) };
|
||||||
|
}
|
||||||
|
throw new Error(`no check for ${provision}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** jackett's configured indexers, id → title, from its `t=indexers` feed. */
|
||||||
|
export function configuredIndexers(xml: string): Map<string, string> {
|
||||||
|
const out = new Map<string, string>();
|
||||||
|
const re = /<indexer\b[^>]*\bid="([^"]+)"[^>]*>([\s\S]*?)<\/indexer>/g;
|
||||||
|
for (let m = re.exec(xml); m; m = re.exec(xml)) {
|
||||||
|
const title = /<title>([\s\S]*?)<\/title>/.exec(m[2])?.[1]?.trim() ?? m[1];
|
||||||
|
out.set(m[1], decodeXml(title));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeXml(s: string): string {
|
||||||
|
return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The remedy for a refused credential, in the controller's own words (ADR 0092). */
|
||||||
|
export function acceptRemedy(app: App, node: string, provision: string, provider: string, secretName: string, from: string): string {
|
||||||
|
return (
|
||||||
|
`${provider} refuses the ${provision} credential the mesh delivered, so nothing of ${provision} was written ` +
|
||||||
|
`into ${app.module}. ${provider} has one ${secretName} and the mesh cannot make it: accept it for this pair — ` +
|
||||||
|
`\`secret accept ${node || "<this node>"} ${app.module} ${provision} --provider ${from || "<its node>"} ` +
|
||||||
|
`--from <file holding ${provider}'s ${secretName}>\``
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Download clients
|
||||||
|
|
||||||
|
/** The non-secret fields of a download client as the mesh says them. */
|
||||||
|
export function clientConnection(ep: Endpoint): Record<string, unknown> {
|
||||||
|
return { host: ep.host, port: ep.port, useSsl: ep.scheme === "https", urlBase: ep.urlBase === "" ? null : ep.urlBase, username: ep.username };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which of them the entry does not already say. Names only. */
|
||||||
|
export function clientDiffers(e: Entry, ep: Endpoint): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
if (String(field(e, "host") ?? "").toLowerCase() !== ep.host.toLowerCase()) out.push("host");
|
||||||
|
if (Number(field(e, "port") ?? 0) !== ep.port) out.push("port");
|
||||||
|
if (Boolean(field(e, "useSsl")) !== (ep.scheme === "https")) out.push("useSsl");
|
||||||
|
if (normBase(field(e, "urlBase")) !== ep.urlBase) out.push("urlBase");
|
||||||
|
if (String(field(e, "username") ?? "") !== ep.username) out.push("username");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the app's download client for one provision in line: the entry by that name and kind is
|
||||||
|
* the mesh's and is updated; none, it is registered. An entry by that name of another kind, or by
|
||||||
|
* that name in another case, is somebody else's and is refused rather than touched.
|
||||||
|
*/
|
||||||
|
export async function reconcileClient(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
kind: ClientKind,
|
||||||
|
name: string,
|
||||||
|
ep: Endpoint,
|
||||||
|
entries: Entry[],
|
||||||
|
): Promise<Outcome[]> {
|
||||||
|
const what = `${kind.provision} ("${name}")`;
|
||||||
|
const exact = entries.filter((e) => e.name === name);
|
||||||
|
const alike = entries.filter((e) => e.name !== name && String(e.name ?? "").toLowerCase() === name.toLowerCase());
|
||||||
|
if (exact.length > 0 && exact[0].implementation !== kind.implementation) {
|
||||||
|
return [{
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `the download client named "${name}" is a ${exact[0].implementation}, not ${kind.implementation}; it is not the mesh's and was left alone. Name the mesh's entry otherwise in downloads.${kind.provision}.name`,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
if (exact.length === 0 && alike.length > 0) {
|
||||||
|
return [{
|
||||||
|
what,
|
||||||
|
result: "refused",
|
||||||
|
problem: `${app.module} already has "${alike[0].name}", which is not the mesh's name ("${name}") and was left alone. To have the mesh manage it, set downloads.${kind.provision}.name to "${alike[0].name}"`,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
const others = entries.filter((e) => e.implementation === kind.implementation && e.name !== name);
|
||||||
|
if (others.length > 0) {
|
||||||
|
outcomes.push({
|
||||||
|
what,
|
||||||
|
result: "notice",
|
||||||
|
note: `also present and not the mesh's, left alone: ${others.map((o) => `"${o.name}"`).join(", ")}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (exact.length === 0) {
|
||||||
|
outcomes.push(
|
||||||
|
await createEntry(http, app, "downloadclient", what, kind.implementation, name, {
|
||||||
|
...clientConnection(ep),
|
||||||
|
password: ep.credential,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
outcomes.push(
|
||||||
|
await reconcileEntry(http, app, "downloadclient", what, exact[0], clientConnection(ep), clientDiffers(exact[0], ep), "password", ep.credential),
|
||||||
|
);
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Indexers
|
||||||
|
|
||||||
|
const FEED = /\/api\/v2\.0\/indexers\/([^/]+)\/results\/torznab\/?$/;
|
||||||
|
|
||||||
|
/** A Torznab entry reading a jackett feed: the host it points at and the jackett indexer's id. */
|
||||||
|
export function jackettFeed(e: Entry): { host: string; id: string } | undefined {
|
||||||
|
if (e.implementation !== "Torznab") return undefined;
|
||||||
|
const raw = String(field(e, "baseUrl") ?? "").trim();
|
||||||
|
if (!raw) return undefined;
|
||||||
|
let u: URL;
|
||||||
|
try {
|
||||||
|
u = new URL(raw);
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const path = `${u.pathname.replace(/\/+$/, "")}/${String(field(e, "apiPath") ?? "").replace(/^\/+/, "")}`;
|
||||||
|
const m = FEED.exec(path);
|
||||||
|
if (!m) return undefined;
|
||||||
|
return { host: u.hostname.replace(/^\[|\]$/g, "").toLowerCase(), id: decodeURIComponent(m[1]) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The feed's two fields as the mesh says them. */
|
||||||
|
export function feedConnection(ep: Endpoint, id: string): Record<string, unknown> {
|
||||||
|
return { baseUrl: baseUrl(ep), apiPath: `/api/v2.0/indexers/${id}/results/torznab/` };
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameUrl(a: string, b: string): boolean {
|
||||||
|
try {
|
||||||
|
const x = new URL(a);
|
||||||
|
const y = new URL(b);
|
||||||
|
const port = (u: URL) => u.port || (u.protocol === "https:" ? "443" : "80");
|
||||||
|
return (
|
||||||
|
x.protocol === y.protocol &&
|
||||||
|
x.hostname.toLowerCase() === y.hostname.toLowerCase() &&
|
||||||
|
port(x) === port(y) &&
|
||||||
|
x.pathname.replace(/\/+$/, "") === y.pathname.replace(/\/+$/, "")
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedDiffers(e: Entry, ep: Endpoint, id: string): string[] {
|
||||||
|
const want = feedConnection(ep, id);
|
||||||
|
const out: string[] = [];
|
||||||
|
if (!sameUrl(String(field(e, "baseUrl") ?? ""), String(want.baseUrl))) out.push("baseUrl");
|
||||||
|
const path = (v: unknown) => `/${String(v ?? "").replace(/^\/+|\/+$/g, "")}`;
|
||||||
|
if (path(field(e, "apiPath")) !== path(want.apiPath)) out.push("apiPath");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IndexerSettings {
|
||||||
|
/** Hosts whose jackett feeds the mesh takes over — a migration's old names. */
|
||||||
|
adoptHosts: string[];
|
||||||
|
/** jackett indexer ids the app should have. */
|
||||||
|
indexers: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the app's jackett feeds in line: every one the mesh manages is pointed at the bound jackett
|
||||||
|
* with its key, and every listed jackett indexer the app lacks is registered.
|
||||||
|
*/
|
||||||
|
export async function reconcileIndexers(
|
||||||
|
http: Http,
|
||||||
|
app: App,
|
||||||
|
ep: Endpoint,
|
||||||
|
configured: Map<string, string>,
|
||||||
|
settings: IndexerSettings,
|
||||||
|
remembered: string[],
|
||||||
|
entries: Entry[],
|
||||||
|
): Promise<Outcome[]> {
|
||||||
|
const ours = new Set([ep.host, ...settings.adoptHosts, ...remembered].map((h) => h.trim().toLowerCase()).filter(Boolean));
|
||||||
|
const outcomes: Outcome[] = [];
|
||||||
|
const managed = new Set<string>();
|
||||||
|
for (const e of entries) {
|
||||||
|
const feed = jackettFeed(e);
|
||||||
|
if (!feed || !ours.has(feed.host)) continue;
|
||||||
|
managed.add(feed.id);
|
||||||
|
const what = `jackett-api ("${e.name}", jackett indexer ${feed.id})`;
|
||||||
|
const known = feed.id === "all" || configured.has(feed.id);
|
||||||
|
const outcome = await reconcileEntry(
|
||||||
|
http, app, "indexer", what, e, feedConnection(ep, feed.id), feedDiffers(e, ep, feed.id), "apiKey", ep.credential, known,
|
||||||
|
);
|
||||||
|
outcomes.push(outcome);
|
||||||
|
if (!known && outcome.result !== "refused") {
|
||||||
|
outcomes.push({ what, result: "notice", note: `jackett has no indexer "${feed.id}" configured, so it was not tested; configure it in jackett or remove the entry in ${app.module}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const id of settings.indexers) {
|
||||||
|
if (managed.has(id)) continue;
|
||||||
|
const what = `jackett-api (jackett indexer ${id})`;
|
||||||
|
if (id !== "all" && !configured.has(id)) {
|
||||||
|
outcomes.push({ what, result: "refused", problem: `downloads.jackett-api.indexers lists "${id}", and jackett has no indexer by that id configured` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const name = `Jackett - ${id === "all" ? "all" : configured.get(id)}`;
|
||||||
|
outcomes.push(await createEntry(http, app, "indexer", what, "Torznab", name, { ...feedConnection(ep, id), apiKey: ep.credential }));
|
||||||
|
}
|
||||||
|
if (outcomes.length === 0) {
|
||||||
|
outcomes.push({ what: "jackett-api", result: "notice", note: `${app.module} has no jackett feed the mesh manages, and downloads.jackett-api.indexers lists none to register` });
|
||||||
|
}
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Files
|
||||||
|
|
||||||
|
/** The module's settings for this step, from its merged `downloads.json`. */
|
||||||
|
export interface StepSettings {
|
||||||
|
node: string;
|
||||||
|
names: Record<string, string>;
|
||||||
|
indexers: IndexerSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stepSettings(raw: unknown): StepSettings {
|
||||||
|
const doc = (raw ?? {}) as Record<string, unknown>;
|
||||||
|
const d = (doc.downloads ?? {}) as Record<string, Record<string, unknown> | undefined>;
|
||||||
|
const names: Record<string, string> = {};
|
||||||
|
for (const k of CLIENTS) {
|
||||||
|
const n = d[k.provision]?.name;
|
||||||
|
names[k.provision] = typeof n === "string" && n.trim() ? n.trim() : k.provision.replace(/-api$/, "");
|
||||||
|
}
|
||||||
|
const j = d[JACKETT] ?? {};
|
||||||
|
const strings = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && x.trim() !== "").map((x) => x.trim()) : []);
|
||||||
|
return {
|
||||||
|
node: typeof doc.node === "string" ? doc.node : "",
|
||||||
|
names,
|
||||||
|
indexers: { adoptHosts: strings(j["adopt-hosts"]), indexers: strings(j.indexers) },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's own key and base path, from its config.xml. */
|
||||||
|
export function appConfig(xml: string): { apiKey: string; urlBase: string } {
|
||||||
|
const tag = (t: string) => new RegExp(`<${t}>([^<]*)</${t}>`).exec(xml)?.[1]?.trim() ?? "";
|
||||||
|
return { apiKey: tag("ApiKey"), urlBase: normBase(tag("UrlBase")) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A file the mesh wrote, or undefined when it is not there. */
|
||||||
|
export async function readIfThere(path: string | undefined): Promise<string | undefined> {
|
||||||
|
if (!path) return undefined;
|
||||||
|
return readFile(path, "utf8").catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A JSON file parsed, or undefined when absent or not JSON. */
|
||||||
|
export async function readJson(path: string | undefined): Promise<unknown> {
|
||||||
|
const raw = await readIfThere(path);
|
||||||
|
if (raw === undefined) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as unknown;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait for the app to answer, because the step runs right after its container starts. */
|
||||||
|
export async function appReady(http: Http, app: App, waitMs: number, pauseMs = 2000): Promise<boolean> {
|
||||||
|
const until = Date.now() + waitMs;
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
const a = await appCall(http, app, "GET", "/system/status");
|
||||||
|
if (a.status === 200) return true;
|
||||||
|
} catch {
|
||||||
|
// not listening yet
|
||||||
|
}
|
||||||
|
if (Date.now() >= until) return false;
|
||||||
|
await new Promise((r) => setTimeout(r, pauseMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listEntries(http: Http, app: App, resource: "downloadclient" | "indexer"): Promise<Entry[]> {
|
||||||
|
return ((await appGet(http, app, `/${resource}`)) as Entry[]) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Anything printed goes through this: the credentials the step holds never reach a log. */
|
||||||
|
export function scrub(text: string, secrets: string[]): string {
|
||||||
|
let out = text;
|
||||||
|
for (const s of secrets) if (s && s.length >= 4) out = out.split(s).join("<redacted>");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(err: unknown): string {
|
||||||
|
return err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
// sonarr's events. The tool runtime imports this once the broker is bound. It watches the download
|
||||||
|
// queue and turns its comings and goings into mesh events.
|
||||||
|
//
|
||||||
|
// Emits (novox/hq ADR 0041/0042):
|
||||||
|
// module.sonarr.episode.grabbed — a release entered the queue (Sonarr grabbed it)
|
||||||
|
// module.sonarr.download.completed — a release left the queue, imported. This exact routing key
|
||||||
|
// is what the plex module consumes (module.*.download.completed)
|
||||||
|
// to rescan, so the new episode becomes a visible item.
|
||||||
|
// Consumes: none.
|
||||||
|
//
|
||||||
|
// The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a
|
||||||
|
// restart mid-download does not re-announce everything already in flight as freshly grabbed.
|
||||||
|
|
||||||
|
import { emit } from "@novox/mesh-sdk/events";
|
||||||
|
import { SonarrClient, type SonarrQueueItem } from "./client.js";
|
||||||
|
|
||||||
|
// Building the client throws when Sonarr has no URL/key yet. Like the tools (see tools/index.ts),
|
||||||
|
// the events entrypoint must not crash the runtime for that — it stays idle until configured.
|
||||||
|
function buildClient(): SonarrClient | null {
|
||||||
|
try {
|
||||||
|
return SonarrClient.fromEnv();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sonarr = buildClient();
|
||||||
|
|
||||||
|
// Sonarr removes an item from the queue once it has been imported; a "warning"/"failed" status is
|
||||||
|
// how a stuck or broken grab shows itself, so we do not call those a completion when they vanish.
|
||||||
|
const FAILED_STATUSES = new Set(["failed", "warning"]);
|
||||||
|
|
||||||
|
const inQueue = new Map<number, SonarrQueueItem>();
|
||||||
|
let primed = false;
|
||||||
|
|
||||||
|
async function pollQueue(sonarr: SonarrClient): Promise<void> {
|
||||||
|
const { items } = await sonarr.getQueue();
|
||||||
|
const now = new Map(items.map((i) => [i.id, i]));
|
||||||
|
|
||||||
|
if (primed) {
|
||||||
|
// Entered the queue since last look — Sonarr grabbed a release.
|
||||||
|
for (const [id, item] of now) {
|
||||||
|
if (!inQueue.has(id)) await emit("episode.grabbed", { title: item.title, status: item.status });
|
||||||
|
}
|
||||||
|
// Left the queue — imported and done, unless it was last seen failing.
|
||||||
|
for (const [id, item] of inQueue) {
|
||||||
|
if (!now.has(id) && !FAILED_STATUSES.has(item.status)) {
|
||||||
|
await emit("download.completed", { title: item.title });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inQueue.clear();
|
||||||
|
for (const [id, item] of now) inQueue.set(id, item);
|
||||||
|
primed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||||
|
const run = (): void => void fn().catch((err) => console.error(`[sonarr] ${err}`));
|
||||||
|
setInterval(run, everyMs);
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (sonarr) {
|
||||||
|
tick(() => pollQueue(sonarr), 30_000);
|
||||||
|
console.log("[sonarr] watching the download queue, emitting grabs and completions");
|
||||||
|
} else {
|
||||||
|
console.log("[sonarr] not configured — events idle until an API key is available");
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
{
|
||||||
|
"module": "sonarr",
|
||||||
|
"version": "1",
|
||||||
|
"provides": [
|
||||||
|
{
|
||||||
|
"name": "sonarr-api",
|
||||||
|
"scope": "mesh"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"serves": {
|
||||||
|
"sonarr-api": {
|
||||||
|
"scheme": "http",
|
||||||
|
"port": 8989,
|
||||||
|
"url-base": ""
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"capabilities": [
|
||||||
|
"container-runtime"
|
||||||
|
],
|
||||||
|
"emits": [
|
||||||
|
"episode.grabbed",
|
||||||
|
"download.completed"
|
||||||
|
],
|
||||||
|
"consumes": [],
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "/var/lib/mesh/sonarr/broker"
|
||||||
|
},
|
||||||
|
"listens": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"port": 8989,
|
||||||
|
"protocol": "tcp",
|
||||||
|
"from": "mesh",
|
||||||
|
"why": "managing series: its web UI, and the API other modules reach as sonarr-api"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accesses": [
|
||||||
|
{
|
||||||
|
"path": "/services/media/series",
|
||||||
|
"mode": "read-write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/anime",
|
||||||
|
"mode": "read-write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/services/media/downloads",
|
||||||
|
"mode": "read-write"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "mesh-state",
|
||||||
|
"type": "directory",
|
||||||
|
"path": "/var/lib/mesh/sonarr",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "state",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"place": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "config",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700",
|
||||||
|
"owner": "1000:1000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "server",
|
||||||
|
"type": "container",
|
||||||
|
"name": "sonarr",
|
||||||
|
"image": "lscr.io/linuxserver/sonarr@sha256:a5c1a5fecbef946927ab90ad68df319ac5fe644057e5fc18cd993f01ac07b2b2",
|
||||||
|
"env": {
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"TZ": "Etc/UTC"
|
||||||
|
},
|
||||||
|
"ports": [
|
||||||
|
"8989"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"${dir:config}:/config",
|
||||||
|
"/services/media/series:/series",
|
||||||
|
"/services/media/anime:/anime",
|
||||||
|
"/services/media/downloads:/downloads"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "runtime",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-sonarr",
|
||||||
|
"network": "host",
|
||||||
|
"volumes": [
|
||||||
|
"/var/lib/mesh/sonarr/broker:/run/secrets/broker:ro",
|
||||||
|
"${dir:config}:/var/lib/sonarr/config:ro"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||||
|
"MESH_SONARR_URL": "http://127.0.0.1:${port:8989}",
|
||||||
|
"MESH_SONARR_CONFIG_DIR": "/var/lib/sonarr/config"
|
||||||
|
},
|
||||||
|
"artifact": "runtime"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads-config",
|
||||||
|
"type": "file",
|
||||||
|
"path": "${dir:state}/downloads.json",
|
||||||
|
"mode": "0600",
|
||||||
|
"content": "{\n \"node\": \"${machine:name}\",\n \"downloads\": {\n \"nzbget-api\": {\n \"name\": \"nzbget\"\n },\n \"qbittorrent-api\": {\n \"name\": \"qbittorrent\"\n },\n \"jackett-api\": {\n \"adopt-hosts\": [],\n \"indexers\": []\n }\n }\n}\n",
|
||||||
|
"merge": "json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads-memory",
|
||||||
|
"type": "directory",
|
||||||
|
"mode": "0700"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "downloads",
|
||||||
|
"type": "container",
|
||||||
|
"name": "mesh-sonarr-downloads",
|
||||||
|
"network": "host",
|
||||||
|
"run-once": true,
|
||||||
|
"volumes": [
|
||||||
|
"${dir:state}/downloads.json:/run/downloads/downloads.json:ro",
|
||||||
|
"${dir:state}/nzbget-api.json:/run/downloads/nzbget-api.json:ro",
|
||||||
|
"${dir:state}/nzbget-api.secret:/run/downloads/nzbget-api.secret:ro",
|
||||||
|
"${dir:state}/qbittorrent-api.json:/run/downloads/qbittorrent-api.json:ro",
|
||||||
|
"${dir:state}/qbittorrent-api.secret:/run/downloads/qbittorrent-api.secret:ro",
|
||||||
|
"${dir:state}/jackett-api.json:/run/downloads/jackett-api.json:ro",
|
||||||
|
"${dir:state}/jackett-api.secret:/run/downloads/jackett-api.secret:ro",
|
||||||
|
"${dir:config}:/var/lib/sonarr/config:ro",
|
||||||
|
"${dir:downloads-memory}:/var/lib/downloads"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"MESH_DOWNLOADS_APP": "sonarr",
|
||||||
|
"MESH_DOWNLOADS_API": "v3",
|
||||||
|
"MESH_DOWNLOADS_APP_URL": "http://127.0.0.1:${port:8989}",
|
||||||
|
"MESH_DOWNLOADS_APP_CONFIG": "/var/lib/sonarr/config/config.xml",
|
||||||
|
"MESH_DOWNLOADS_DIR": "/run/downloads",
|
||||||
|
"MESH_DOWNLOADS_SETTINGS": "/run/downloads/downloads.json",
|
||||||
|
"MESH_DOWNLOADS_MEMORY": "/var/lib/downloads/memory.json"
|
||||||
|
},
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"/app/modules/sonarr/dist/downloads/index.js"
|
||||||
|
],
|
||||||
|
"restart-on": [
|
||||||
|
"downloads-config",
|
||||||
|
"bound-nzbget-api",
|
||||||
|
"secret-nzbget-api",
|
||||||
|
"bound-qbittorrent-api",
|
||||||
|
"secret-qbittorrent-api",
|
||||||
|
"bound-jackett-api",
|
||||||
|
"secret-jackett-api"
|
||||||
|
],
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requires": [
|
||||||
|
"jackett-api",
|
||||||
|
"nzbget-api",
|
||||||
|
"qbittorrent-api",
|
||||||
|
"route"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"route": {
|
||||||
|
"label": "series",
|
||||||
|
"endpoint": "web"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binds": {
|
||||||
|
"route": "${dir:state}/route.json",
|
||||||
|
"nzbget-api": "${dir:state}/nzbget-api.json",
|
||||||
|
"qbittorrent-api": "${dir:state}/qbittorrent-api.json",
|
||||||
|
"jackett-api": "${dir:state}/jackett-api.json"
|
||||||
|
},
|
||||||
|
"secrets": {
|
||||||
|
"nzbget-api": "${dir:state}/nzbget-api.secret",
|
||||||
|
"qbittorrent-api": "${dir:state}/qbittorrent-api.secret",
|
||||||
|
"jackett-api": "${dir:state}/jackett-api.secret"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"on": [
|
||||||
|
{
|
||||||
|
"arg": "BUILD_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"arg": "RUNTIME_BASE",
|
||||||
|
"module": "mesh-tools",
|
||||||
|
"artifact": "runtime"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"artifacts": [
|
||||||
|
{
|
||||||
|
"name": "runtime",
|
||||||
|
"kind": "image",
|
||||||
|
"from": "Dockerfile"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "@novox/module-sonarr",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "sonarr — TV series management. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc client.ts index.ts tools/index.ts downloads/settings.ts downloads/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist",
|
||||||
|
"typecheck": "tsc -p tsconfig.json",
|
||||||
|
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@novox/mesh-sdk": "^0.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
// What holds the downloads step (downloads/settings.ts): the app's download clients and jackett
|
||||||
|
// feeds are made to say what the mesh bound — host, port, TLS, base path, user, credential — and
|
||||||
|
// nothing else they keep is touched; only the mesh's entries are touched, and nothing is ever
|
||||||
|
// deleted; nothing is written when nothing differs; a missing one is registered; and a credential
|
||||||
|
// the provider refuses (the mesh's own minted value, before the operator accepts the provider's)
|
||||||
|
// is never written, with the `secret accept` that fixes it named.
|
||||||
|
//
|
||||||
|
// The app and the providers are fakes: the routes the step touches, answering as the real ones do
|
||||||
|
// (checked against the catalogue's pinned sonarr, radarr, lidarr, bookshelf, nzbget, qBittorrent
|
||||||
|
// and jackett): the app masks a stored password as "********", tests an enabled entry before
|
||||||
|
// saving it, refuses a warning unless forceSave, and jackett answers a wrong key 200 with an error.
|
||||||
|
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CLIENTS,
|
||||||
|
acceptRemedy,
|
||||||
|
jackettFeed,
|
||||||
|
providerTakes,
|
||||||
|
reconcileClient,
|
||||||
|
reconcileIndexers,
|
||||||
|
stepSettings,
|
||||||
|
wanted,
|
||||||
|
type App,
|
||||||
|
type Binding,
|
||||||
|
type Endpoint,
|
||||||
|
type Entry,
|
||||||
|
type Http,
|
||||||
|
} from "../downloads/settings.ts";
|
||||||
|
|
||||||
|
const NZBGET = CLIENTS.find((c) => c.provision === "nzbget-api")!;
|
||||||
|
const QBIT = CLIENTS.find((c) => c.provision === "qbittorrent-api")!;
|
||||||
|
const APP: App = { module: "sonarr", url: "http://127.0.0.1:8989", apiKey: "app-key", api: "v3" };
|
||||||
|
const MASK = "********";
|
||||||
|
|
||||||
|
interface Provider {
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
user?: string;
|
||||||
|
secret: string;
|
||||||
|
configured?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nzbget: Provider = { host: "ace.internal", port: 20201, user: "luffy", secret: "nzb-real" };
|
||||||
|
const qbit: Provider = { host: "ace.internal", port: 8112, user: "luffy", secret: "qbt-real" };
|
||||||
|
const jackett: Provider = { host: "ace.internal", port: 20204, secret: "jackett-real", configured: { rutracker: "RuTracker", torrent9: "Torrent9" } };
|
||||||
|
|
||||||
|
function binding(p: Provider, provision: string, extra: Record<string, unknown> = {}): Binding {
|
||||||
|
return {
|
||||||
|
provision,
|
||||||
|
from: "ace",
|
||||||
|
at: p.host,
|
||||||
|
as: "mesh_ace_sonarr",
|
||||||
|
serves: { scheme: "http", port: p.port, "url-base": "", ...(p.user ? { username: p.user } : {}), ...extra },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function endpoint(p: Provider, provision: string, credential = p.secret): Endpoint {
|
||||||
|
const w = wanted(provision, binding(p, provision), credential, provision !== "jackett-api");
|
||||||
|
if (!w.ok) throw new Error(w.problem);
|
||||||
|
return w.endpoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
const f = (name: string, value: unknown) => ({ name, value });
|
||||||
|
|
||||||
|
function client(id: number, name: string, implementation: string, host: string, port: number, password: string, extra: Record<string, unknown> = {}): Entry {
|
||||||
|
return {
|
||||||
|
id, name, implementation, enable: true, priority: 1, tags: [],
|
||||||
|
fields: [f("host", host), f("port", port), f("useSsl", false), f("urlBase", null), f("username", "luffy"), f("password", password), f("tvCategory", "Series"), ...Object.entries(extra).map(([k, v]) => f(k, v))],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function feed(id: number, name: string, baseUrl: string, jid: string, key: string, on = true): Entry {
|
||||||
|
return {
|
||||||
|
id, name, implementation: "Torznab", enableRss: on, enableAutomaticSearch: on, enableInteractiveSearch: on, priority: 25,
|
||||||
|
fields: [f("baseUrl", baseUrl), f("apiPath", `/api/v2.0/indexers/${jid}/results/torznab/`), f("apiKey", key), f("categories", [5000])],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Call {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
body?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A Servarr app and the three providers behind one fetch. */
|
||||||
|
function fakes(start: { clients?: Entry[]; indexers?: Entry[] }) {
|
||||||
|
const calls: Call[] = [];
|
||||||
|
const store: Record<string, Entry[]> = {
|
||||||
|
downloadclient: structuredClone(start.clients ?? []),
|
||||||
|
indexer: structuredClone(start.indexers ?? []),
|
||||||
|
};
|
||||||
|
let next = 100;
|
||||||
|
const secretOf: Record<string, string> = { downloadclient: "password", indexer: "apiKey" };
|
||||||
|
const masked = (e: Entry): Entry => ({ ...e, fields: e.fields!.map((x) => (x.name === "password" || x.name === "apiKey") && x.value ? { ...x, value: MASK } : { ...x }) });
|
||||||
|
const val = (e: Entry, n: string) => e.fields?.find((x) => x.name === n)?.value;
|
||||||
|
|
||||||
|
/** What the app's own test says: dialled from its container, with its stored secret for a mask. */
|
||||||
|
const appTest = (kind: string, e: Entry): { propertyName: string; errorMessage: string; isWarning: boolean }[] => {
|
||||||
|
let secret = val(e, secretOf[kind]);
|
||||||
|
if (secret === MASK) secret = val(store[kind].find((s) => s.id === e.id) ?? {}, secretOf[kind]);
|
||||||
|
if (kind === "downloadclient") {
|
||||||
|
const p = e.implementation === "Nzbget" ? nzbget : qbit;
|
||||||
|
if (val(e, "host") !== p.host || val(e, "port") !== p.port) return [{ propertyName: "Host", errorMessage: "Unable to connect", isWarning: false }];
|
||||||
|
if (secret !== p.secret || val(e, "username") !== p.user) return [{ propertyName: "Username", errorMessage: "Authentication Failure", isWarning: false }];
|
||||||
|
if (val(e, "tvCategory") === "") return [{ propertyName: "TvCategory", errorMessage: "A category is recommended", isWarning: true }];
|
||||||
|
if (e.implementation === "Nzbget" && val(e, "tvCategory") === "tv") return [{ propertyName: "TvCategory", errorMessage: "Category does not exist", isWarning: false }];
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const u = new URL(String(val(e, "baseUrl")));
|
||||||
|
if (u.hostname !== jackett.host || Number(u.port) !== jackett.port) return [{ propertyName: "BaseUrl", errorMessage: "Unable to connect", isWarning: false }];
|
||||||
|
if (secret !== jackett.secret) return [{ propertyName: "ApiKey", errorMessage: "Invalid API Key", isWarning: false }];
|
||||||
|
const id = /indexers\/([^/]+)\//.exec(String(val(e, "apiPath")))?.[1] ?? "";
|
||||||
|
if (!(id in jackett.configured!)) return [{ propertyName: "", errorMessage: "Unknown indexer", isWarning: false }];
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const http: Http = {
|
||||||
|
async fetch(url, init) {
|
||||||
|
const method = init?.method ?? "GET";
|
||||||
|
const body = init?.body && init.headers?.["Content-Type"] === "application/json" ? (JSON.parse(init.body) as Entry) : init?.body;
|
||||||
|
calls.push({ method, url, body });
|
||||||
|
const reply = (status: number, value?: unknown) => ({ status, text: async () => (value === undefined ? "" : typeof value === "string" ? value : JSON.stringify(value)) });
|
||||||
|
const u = new URL(url);
|
||||||
|
// Providers.
|
||||||
|
if (u.pathname === "/jsonrpc/version") {
|
||||||
|
const want = "Basic " + Buffer.from(`${nzbget.user}:${nzbget.secret}`).toString("base64");
|
||||||
|
return init?.headers?.Authorization === want ? reply(200, { result: "26.0" }) : reply(401);
|
||||||
|
}
|
||||||
|
if (u.pathname === "/api/v2/auth/login") {
|
||||||
|
const form = new URLSearchParams(String(init?.body ?? ""));
|
||||||
|
return form.get("username") === qbit.user && form.get("password") === qbit.secret ? reply(204) : reply(401, "Unauthorized");
|
||||||
|
}
|
||||||
|
if (u.pathname.endsWith("/torznab/api")) {
|
||||||
|
if (u.searchParams.get("apikey") !== jackett.secret) return reply(200, '<?xml version="1.0"?><error code="100" description="Invalid API Key" />');
|
||||||
|
const items = Object.entries(jackett.configured!).map(([id, t]) => `<indexer id="${id}" configured="true"><title>${t}</title></indexer>`).join("");
|
||||||
|
return reply(200, `<?xml version="1.0"?><indexers>${items}</indexers>`);
|
||||||
|
}
|
||||||
|
// The app.
|
||||||
|
if (init?.headers?.["X-Api-Key"] !== APP.apiKey) return reply(401);
|
||||||
|
const m = /^\/api\/v3\/(downloadclient|indexer)(?:\/(schema|test|\d+))?$/.exec(u.pathname);
|
||||||
|
if (!m) return reply(404);
|
||||||
|
const [, kind, sub] = m;
|
||||||
|
const force = u.searchParams.get("forceSave") === "true";
|
||||||
|
if (method === "GET" && !sub) return reply(200, store[kind].map(masked));
|
||||||
|
if (method === "GET" && sub === "schema") {
|
||||||
|
return reply(200, kind === "downloadclient"
|
||||||
|
? [client(0, "", "Nzbget", "localhost", 6789, MASK, {}), client(0, "", "QBittorrent", "localhost", 8080, "", {})].map((e) => ({ ...e, fields: e.fields!.map((x) => x.name === "tvCategory" ? { ...x, value: e.implementation === "Nzbget" ? "tv" : "tv-sonarr" } : x.name === "username" ? { ...x, value: null } : x) }))
|
||||||
|
: [{ ...feed(0, "", "", "x", "", false), supportsRss: true, supportsSearch: true, fields: [f("baseUrl", null), f("apiPath", "/api"), f("apiKey", null), f("categories", [5030, 5040])] }]);
|
||||||
|
}
|
||||||
|
if (method === "GET") {
|
||||||
|
const e = store[kind].find((s) => s.id === Number(sub));
|
||||||
|
return e ? reply(200, masked(e)) : reply(404);
|
||||||
|
}
|
||||||
|
if (method === "POST" && sub === "test") {
|
||||||
|
const fails = appTest(kind, body as Entry);
|
||||||
|
return fails.length ? reply(400, fails) : reply(200);
|
||||||
|
}
|
||||||
|
// Save: tested when enabled; a mask keeps what is stored.
|
||||||
|
const e = body as Entry;
|
||||||
|
const on = e.enable === true || e.enableRss === true || e.enableAutomaticSearch === true;
|
||||||
|
if (on) {
|
||||||
|
const fails = appTest(kind, e);
|
||||||
|
if (fails.some((x) => !x.isWarning) || (fails.length && !force)) return reply(400, fails);
|
||||||
|
}
|
||||||
|
if (method === "POST" && !sub) {
|
||||||
|
if (store[kind].some((s) => String(s.name).toLowerCase() === String(e.name).toLowerCase())) {
|
||||||
|
return reply(400, [{ propertyName: "Name", errorMessage: "Should be unique", isWarning: false }]);
|
||||||
|
}
|
||||||
|
const created = { ...e, id: next++ };
|
||||||
|
store[kind].push(created);
|
||||||
|
return reply(201, masked(created));
|
||||||
|
}
|
||||||
|
if (method === "PUT") {
|
||||||
|
const i = store[kind].findIndex((s) => s.id === Number(sub));
|
||||||
|
if (i < 0) return reply(404);
|
||||||
|
const was = store[kind][i];
|
||||||
|
store[kind][i] = { ...e, fields: e.fields!.map((x) => x.value === MASK ? { ...x, value: val(was, x.name) } : x) };
|
||||||
|
return reply(202, masked(store[kind][i]));
|
||||||
|
}
|
||||||
|
return reply(405);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const saves = () => calls.filter((c) => (c.method === "PUT" || (c.method === "POST" && !c.url.endsWith("/test"))) && c.url.includes("/api/v3/"));
|
||||||
|
return { http, calls, store, saves };
|
||||||
|
}
|
||||||
|
|
||||||
|
const aceClients = () => [
|
||||||
|
client(1, "NZBGet", "Nzbget", "nzbget", 6789, "nzb-real"),
|
||||||
|
client(2, "qBitTorrent", "QBittorrent", "qbittorrent", 8112, "qbt-real"),
|
||||||
|
];
|
||||||
|
|
||||||
|
test("the migration's download client is repointed, its category and everything else kept", async () => {
|
||||||
|
const f = fakes({ clients: aceClients() });
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(nzbget, "nzbget-api"), f.store.downloadclient.map((e) => ({ ...e })));
|
||||||
|
assert.deepEqual(out, [{ what: 'nzbget-api ("NZBGet")', result: "written", fields: ["host", "port"] }]);
|
||||||
|
const saved = f.store.downloadclient.find((e) => e.id === 1)!;
|
||||||
|
const v = (n: string) => saved.fields!.find((x) => x.name === n)?.value;
|
||||||
|
assert.equal(v("host"), "ace.internal");
|
||||||
|
assert.equal(v("port"), 20201);
|
||||||
|
assert.equal(v("tvCategory"), "Series");
|
||||||
|
assert.equal(v("password"), "nzb-real", "the password it held works, so it was kept, not rewritten");
|
||||||
|
assert.equal(saved.priority, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rerun: already as the mesh says, nothing saved", async () => {
|
||||||
|
const f = fakes({ clients: [client(1, "NZBGet", "Nzbget", "ace.internal", 20201, "nzb-real")] });
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(nzbget, "nzbget-api"), f.store.downloadclient);
|
||||||
|
assert.deepEqual(out, [{ what: 'nzbget-api ("NZBGet")', result: "unchanged" }]);
|
||||||
|
assert.equal(f.saves().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a stale password is replaced by the delivered one, which the provider took first", async () => {
|
||||||
|
const f = fakes({ clients: [client(2, "qBitTorrent", "QBittorrent", "ace.internal", 8112, "old-pass")] });
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qBitTorrent", endpoint(qbit, "qbittorrent-api"), f.store.downloadclient);
|
||||||
|
assert.deepEqual(out, [{ what: 'qbittorrent-api ("qBitTorrent")', result: "written", fields: ["password"] }]);
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "password")?.value, "qbt-real");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a minted credential is refused by the provider: nothing written, the accept named", async () => {
|
||||||
|
const f = fakes({ clients: aceClients() });
|
||||||
|
const ep = endpoint(nzbget, "nzbget-api", "a-value-the-mesh-minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "nzbget-api", ep), { took: false });
|
||||||
|
const remedy = acceptRemedy(APP, "ace", "nzbget-api", "nzbget", "ControlPassword", ep.from);
|
||||||
|
assert.match(remedy, /`secret accept ace sonarr nzbget-api --provider ace --from <file holding nzbget's ControlPassword>`/);
|
||||||
|
assert.doesNotMatch(remedy, /minted/);
|
||||||
|
assert.equal(f.calls.some((c) => c.url.includes("/api/v3/")), false, "the app was not even asked");
|
||||||
|
const q = endpoint(qbit, "qbittorrent-api", "minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "qbittorrent-api", q), { took: false });
|
||||||
|
const j = endpoint(jackett, "jackett-api", "minted");
|
||||||
|
assert.deepEqual(await providerTakes(f.http, "jackett-api", j), { took: false });
|
||||||
|
assert.equal(f.calls.find((c) => c.url.includes("apikey="))?.url.includes("jackett-real"), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a fresh app gets the mesh's client registered, under the mesh's name", async () => {
|
||||||
|
const f = fakes({});
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qbittorrent", endpoint(qbit, "qbittorrent-api"), []);
|
||||||
|
assert.equal(out[0].result, "created");
|
||||||
|
const e = f.store.downloadclient[0];
|
||||||
|
assert.equal(e.name, "qbittorrent");
|
||||||
|
assert.equal(e.enable, true);
|
||||||
|
assert.equal(e.fields!.find((x) => x.name === "tvCategory")?.value, "tv-sonarr", "the app's own default category");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("nzbget without the app's default category: registered with none, and said", async () => {
|
||||||
|
const f = fakes({});
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "nzbget", endpoint(nzbget, "nzbget-api"), []);
|
||||||
|
assert.equal(out[0].result, "notice");
|
||||||
|
assert.match((out[0] as { note: string }).note, /category left empty/);
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "tvCategory")?.value, "");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("somebody else's entries are never touched: another name of the same kind, and a clash of names", async () => {
|
||||||
|
const mine = client(7, "My seedbox", "QBittorrent", "seedbox.example", 443, "theirs");
|
||||||
|
const f = fakes({ clients: [mine] });
|
||||||
|
const out = await reconcileClient(f.http, APP, QBIT, "qbittorrent", endpoint(qbit, "qbittorrent-api"), f.store.downloadclient);
|
||||||
|
assert.equal(out[0].result, "notice");
|
||||||
|
assert.deepEqual(f.store.downloadclient.find((e) => e.id === 7), mine);
|
||||||
|
// Same name in another case: refused, and the setting that adopts it named.
|
||||||
|
const g = fakes({ clients: aceClients() });
|
||||||
|
const clash = await reconcileClient(g.http, APP, NZBGET, "nzbget", endpoint(nzbget, "nzbget-api"), g.store.downloadclient);
|
||||||
|
assert.equal(clash[0].result, "refused");
|
||||||
|
assert.match((clash[0] as { problem: string }).problem, /downloads\.nzbget-api\.name to "NZBGet"/);
|
||||||
|
assert.equal(g.saves().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("jackett feeds: the migration's are repointed, a person's is left, a listed one is registered", async () => {
|
||||||
|
const personal = feed(9, "Seedbox jackett", "https://jackett.seedbox.example", "rutracker", "their-key");
|
||||||
|
const f = fakes({
|
||||||
|
indexers: [
|
||||||
|
feed(5, "Torznab - RuTracker", "https://indexers.zurag.be", "rutracker-ru", "jackett-real", false),
|
||||||
|
feed(6, "Torznab - Torrent9", "https://indexers.zurag.be", "torrent9", "jackett-real", false),
|
||||||
|
feed(4, "Jackett - RARBG", "http://jackett:9117", "therarbg", "old", false),
|
||||||
|
personal,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const configured = new Map(Object.entries(jackett.configured!));
|
||||||
|
const out = await reconcileIndexers(
|
||||||
|
f.http, APP, endpoint(jackett, "jackett-api"), configured,
|
||||||
|
{ adoptHosts: ["indexers.zurag.be", "jackett"], indexers: ["rutracker"] }, [], f.store.indexer,
|
||||||
|
);
|
||||||
|
const byWhat = Object.fromEntries(out.map((o) => [o.what + ":" + o.result, o]));
|
||||||
|
// torrent9: jackett has it; repointed, key already right, tested.
|
||||||
|
assert.ok(byWhat['jackett-api ("Torznab - Torrent9", jackett indexer torrent9):written']);
|
||||||
|
// rutracker-ru and therarbg: jackett has neither — repointed with the key, untested, and said.
|
||||||
|
assert.ok(byWhat['jackett-api ("Jackett - RARBG", jackett indexer therarbg):written']);
|
||||||
|
assert.ok(byWhat['jackett-api ("Jackett - RARBG", jackett indexer therarbg):notice']);
|
||||||
|
// rutracker is listed and nothing of the mesh's reads it: registered.
|
||||||
|
assert.ok(byWhat["jackett-api (jackett indexer rutracker):created"]);
|
||||||
|
assert.deepEqual(f.store.indexer.find((e) => e.id === 9), personal, "a person's jackett is not the mesh's");
|
||||||
|
const t9 = f.store.indexer.find((e) => e.id === 6)!;
|
||||||
|
assert.equal(t9.fields!.find((x) => x.name === "baseUrl")?.value, "http://ace.internal:20204");
|
||||||
|
assert.equal(t9.enableRss, false, "disabled stays disabled");
|
||||||
|
const created = f.store.indexer.find((e) => e.name === "Jackett - RuTracker")!;
|
||||||
|
assert.equal(created.enableRss, true);
|
||||||
|
assert.equal(f.calls.some((c) => c.method === "DELETE"), false, "nothing is ever deleted");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("jackett feeds rerun: nothing saved, and a remembered host keeps a moved jackett's feeds", async () => {
|
||||||
|
const f = fakes({ indexers: [feed(6, "Torznab - Torrent9", "http://ace.internal:20204", "torrent9", "jackett-real")] });
|
||||||
|
const configured = new Map(Object.entries(jackett.configured!));
|
||||||
|
const out = await reconcileIndexers(f.http, APP, endpoint(jackett, "jackett-api"), configured, { adoptHosts: [], indexers: ["torrent9"] }, [], f.store.indexer);
|
||||||
|
assert.deepEqual(out.map((o) => o.result), ["unchanged"]);
|
||||||
|
assert.equal(f.saves().length, 0);
|
||||||
|
// jackett moved to novox: the feed on ace.internal is still the mesh's because it was remembered.
|
||||||
|
const moved = { ...jackett, host: "novox.internal" };
|
||||||
|
const g = fakes({ indexers: [feed(6, "Torznab - Torrent9", "http://ace.internal:20204", "torrent9", "jackett-real")] });
|
||||||
|
const saved = jackett.host;
|
||||||
|
jackett.host = moved.host;
|
||||||
|
try {
|
||||||
|
const again = await reconcileIndexers(g.http, APP, endpoint(moved, "jackett-api"), configured, { adoptHosts: [], indexers: [] }, ["ace.internal"], g.store.indexer);
|
||||||
|
assert.equal(again[0].result, "written");
|
||||||
|
assert.equal(g.store.indexer[0].fields!.find((x) => x.name === "baseUrl")?.value, "http://novox.internal:20204");
|
||||||
|
} finally {
|
||||||
|
jackett.host = saved;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an enabled entry the app cannot test at the mesh's address is not saved", async () => {
|
||||||
|
const f = fakes({ clients: [client(1, "NZBGet", "Nzbget", "nzbget", 6789, "nzb-real")] });
|
||||||
|
const elsewhere = { ...nzbget, port: 1 };
|
||||||
|
const out = await reconcileClient(f.http, APP, NZBGET, "NZBGet", endpoint(elsewhere, "nzbget-api"), f.store.downloadclient);
|
||||||
|
assert.equal(out[0].result, "refused");
|
||||||
|
assert.equal(f.store.downloadclient[0].fields!.find((x) => x.name === "host")?.value, "nzbget", "left as it was");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("bindings: loopback, no user, no credential are refused; the base path is normalised", () => {
|
||||||
|
assert.equal(wanted("nzbget-api", { ...binding(nzbget, "nzbget-api"), at: "127.0.0.1" }, "x", true).ok, false);
|
||||||
|
assert.equal(wanted("nzbget-api", binding({ ...nzbget, user: undefined }, "nzbget-api"), "x", true).ok, false);
|
||||||
|
assert.equal(wanted("nzbget-api", binding(nzbget, "nzbget-api"), " \n", true).ok, false);
|
||||||
|
const w = wanted("jackett-api", binding(jackett, "jackett-api", { "url-base": "jackett/" }), "k", false);
|
||||||
|
assert.equal(w.ok && w.endpoint.urlBase, "/jackett");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a feed is read whole: base path in the base URL or in the API path", () => {
|
||||||
|
const e = feed(1, "x", "http://ace.internal:9117/jackett", "rutracker", "k");
|
||||||
|
assert.deepEqual(jackettFeed(e), { host: "ace.internal", id: "rutracker" });
|
||||||
|
assert.equal(jackettFeed({ ...e, implementation: "Newznab" }), undefined);
|
||||||
|
assert.equal(jackettFeed({ ...e, fields: [f("baseUrl", "https://api.nzbgeek.info"), f("apiPath", "/api")] }), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("settings: names default to the provider's, adoption and registration read from the merged file", () => {
|
||||||
|
assert.deepEqual(stepSettings({ node: "ace" }), { node: "ace", names: { "nzbget-api": "nzbget", "qbittorrent-api": "qbittorrent" }, indexers: { adoptHosts: [], indexers: [] } });
|
||||||
|
const s = stepSettings({ node: "ace", downloads: { "nzbget-api": { name: "NZBGet" }, "jackett-api": { "adopt-hosts": ["jackett"], indexers: ["torrent9", 3] } } });
|
||||||
|
assert.equal(s.names["nzbget-api"], "NZBGet");
|
||||||
|
assert.deepEqual(s.indexers, { adoptHosts: ["jackett"], indexers: ["torrent9"] });
|
||||||
|
});
|
||||||
|
|
||||||
|
// The four copies are one step. Where the siblings are checked out beside this module, they must
|
||||||
|
// be byte-identical — a fix made in one and not the others is a bug in three apps.
|
||||||
|
test("the step is the same in sonarr, radarr, lidarr and bookshelf", () => {
|
||||||
|
const here = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||||
|
const modules = dirname(here);
|
||||||
|
for (const file of ["downloads/settings.ts", "downloads/index.ts", "test/downloads.test.ts"]) {
|
||||||
|
const mine = readFileSync(join(here, file), "utf8");
|
||||||
|
for (const sibling of ["sonarr", "radarr", "lidarr", "bookshelf"]) {
|
||||||
|
const theirs = join(modules, sibling, file);
|
||||||
|
if (existsSync(theirs)) assert.equal(readFileSync(theirs, "utf8"), mine, `${sibling}/${file} differs`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// sonarr's tools — ported from the shared hal sdk (novox/hq ADR 0039), importing sonarr's own
|
||||||
|
// client. They return structured data (not pre-formatted text as hal did); the mesh serves them
|
||||||
|
// through the sdk's tool harness.
|
||||||
|
|
||||||
|
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||||
|
import { SonarrClient } from "../client.js";
|
||||||
|
|
||||||
|
export function getSonarrTools(sonarr: SonarrClient): ToolDefinition[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "sonarr_status",
|
||||||
|
description: "Sonarr status overview: version, series count, monitored count, queue size.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const [status, content, queue] = await Promise.all([
|
||||||
|
sonarr.getStatus(),
|
||||||
|
sonarr.getContent(),
|
||||||
|
sonarr.getQueue(),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
app: status.appName,
|
||||||
|
version: status.version,
|
||||||
|
series: content.length,
|
||||||
|
monitored: content.filter((c) => c.monitored).length,
|
||||||
|
queue: queue.totalRecords,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sonarr_library",
|
||||||
|
description: "List series from the Sonarr library.",
|
||||||
|
input: { limit: { type: "number", description: "max items to return (default 50)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const items = await sonarr.getContent(args.limit ? Number(args.limit) : 50);
|
||||||
|
return { count: items.length, series: items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sonarr_search",
|
||||||
|
description: "Search the Sonarr library for series by title (filters existing content, not indexers).",
|
||||||
|
input: { query: { type: "string", description: "the search term" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const query = String(args.query);
|
||||||
|
return { query, results: await sonarr.searchContent(query) };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sonarr_queue",
|
||||||
|
description: "Show the Sonarr download queue — what is downloading and how far along.",
|
||||||
|
input: {},
|
||||||
|
run: async () => {
|
||||||
|
const queue = await sonarr.getQueue();
|
||||||
|
return { count: queue.totalRecords, items: queue.items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sonarr_calendar",
|
||||||
|
description: "Upcoming episode releases from the Sonarr calendar.",
|
||||||
|
input: { days: { type: "number", description: "how many days to look ahead (default 7)" } },
|
||||||
|
run: async (args) => {
|
||||||
|
const days = args.days ? Number(args.days) : 7;
|
||||||
|
const items = await sonarr.getCalendar(days);
|
||||||
|
items.sort((a, b) => a.date.localeCompare(b.date));
|
||||||
|
return { days, count: items.length, items };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tools exist only when Sonarr is configured; without a URL and key, sonarr contributes none
|
||||||
|
// rather than failing the whole runtime.
|
||||||
|
registerModuleTools("sonarr", (env) => {
|
||||||
|
try {
|
||||||
|
return getSonarrTools(SonarrClient.fromEnv(env));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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", "downloads/settings.ts", "downloads/index.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# tautulli's runtime: the tool runtime, carrying this module's compiled code.
|
||||||
|
#
|
||||||
|
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||||
|
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||||
|
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||||
|
# happens to have the siblings.
|
||||||
|
#
|
||||||
|
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||||
|
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||||
|
ARG BUILD_BASE
|
||||||
|
ARG RUNTIME_BASE
|
||||||
|
|
||||||
|
FROM ${BUILD_BASE} AS build
|
||||||
|
WORKDIR /app/modules/tautulli
|
||||||
|
COPY . .
|
||||||
|
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts plex/check.ts plex/index.ts \
|
||||||
|
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||||
|
|
||||||
|
FROM ${RUNTIME_BASE}
|
||||||
|
COPY --from=build /app/modules/tautulli/dist /app/modules/tautulli/dist
|
||||||
|
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||||
|
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||||
|
# the convention novox/hq issues 060/061 settled.
|
||||||
|
ENV MESH_TOOL_MODULES=/app/modules/tautulli/dist/index.js,/app/modules/tautulli/dist/tools/index.js
|
||||||
|
# NOT dist/plex/index.js: that is a step the host runs to completion, named by the `plex`
|
||||||
|
# container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run inside the
|
||||||
|
# serving sidecar too, and exit it.
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
// Tautulli's API client — tautulli's own code, living in the module (novox/hq ADR 0039). Both this
|
||||||
|
// module's tools and its events entrypoint import it, and nothing outside tautulli does.
|
||||||
|
//
|
||||||
|
// Tautulli speaks one endpoint: GET /api/v2?apikey=…&cmd=…&<params>, answering
|
||||||
|
// { response: { result: "success" | "error", message, data } }. This client unwraps that envelope
|
||||||
|
// and hands back only the data.
|
||||||
|
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
export interface TautulliSession {
|
||||||
|
user: string;
|
||||||
|
title: string;
|
||||||
|
mediaType: string;
|
||||||
|
state: string;
|
||||||
|
progressPercent: number;
|
||||||
|
player: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TautulliWatch {
|
||||||
|
/** Tautulli's history row id — the stable identity a recorded watch is diffed on. */
|
||||||
|
id: number;
|
||||||
|
user: string;
|
||||||
|
title: string;
|
||||||
|
mediaType: string;
|
||||||
|
/** "watched" | "watching" | ... — Tautulli's own watched_status label. */
|
||||||
|
watchedStatus: string;
|
||||||
|
percentComplete: number;
|
||||||
|
/** Unix seconds the play started, as Tautulli reports it. */
|
||||||
|
date?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TautulliHomeStat {
|
||||||
|
statId: string;
|
||||||
|
rows: Array<Record<string, unknown>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
|
||||||
|
function meshConfig(file?: string): Record<string, string> {
|
||||||
|
if (!file) return {};
|
||||||
|
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
|
||||||
|
catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The API key Tautulli minted for itself, read from its own config.ini (mounted read-only).
|
||||||
|
*
|
||||||
|
* Tautulli owns this key: it writes it on first run and every client of its API — this runtime
|
||||||
|
* included — must present the same one. So the mesh does not mint or hold it; the one place it
|
||||||
|
* lives is the file Tautulli keeps, and a key regenerated in Tautulli's settings is simply read
|
||||||
|
* again on the next start. Undefined when there is no file or no key yet (a fresh install whose
|
||||||
|
* setup wizard has not run).
|
||||||
|
*/
|
||||||
|
export function keyOfTautulli(dir?: string): string | undefined {
|
||||||
|
if (!dir) return undefined;
|
||||||
|
let ini: string;
|
||||||
|
try { ini = readFileSync(`${dir.replace(/\/$/, "")}/config.ini`, "utf8"); }
|
||||||
|
catch { return undefined; }
|
||||||
|
let section = "";
|
||||||
|
for (const raw of ini.split(/\r?\n/)) {
|
||||||
|
const line = raw.trim();
|
||||||
|
const header = /^\[(.+)\]$/.exec(line);
|
||||||
|
if (header) { section = header[1]; continue; }
|
||||||
|
if (section !== "General") continue;
|
||||||
|
const kv = /^api_key\s*=\s*"?([^"]*)"?$/.exec(line);
|
||||||
|
if (kv && kv[1]) return kv[1];
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TautulliClient {
|
||||||
|
readonly baseUrl: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
url: string,
|
||||||
|
private readonly apiKey: string,
|
||||||
|
) {
|
||||||
|
this.baseUrl = url.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build from the module's resolved environment. The API key is the one Tautulli minted for
|
||||||
|
* itself (Settings → Web Interface), read from its config.ini under MESH_TAUTULLI_CONFIG_DIR;
|
||||||
|
* MESH_TAUTULLI_APIKEY still wins where it is set. The base URL defaults to the local container.
|
||||||
|
* Throws when no key is configured — the module then contributes nothing rather than failing.
|
||||||
|
*/
|
||||||
|
static fromEnv(env: NodeJS.ProcessEnv = process.env): TautulliClient {
|
||||||
|
const cfg = meshConfig(env.MESH_TAUTULLI_CONFIG_FILE);
|
||||||
|
const url = cfg.url ?? (env.MESH_TAUTULLI_URL ?? `http://127.0.0.1:${env.TAUTULLI_PORT ?? "8181"}`);
|
||||||
|
const apiKey = cfg.apiKey ?? env.MESH_TAUTULLI_APIKEY ?? keyOfTautulli(env.MESH_TAUTULLI_CONFIG_DIR);
|
||||||
|
if (!apiKey) throw new Error("no Tautulli API key — Tautulli's config.ini has none yet (finish its setup and enable the API)");
|
||||||
|
return new TautulliClient(url, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Call one Tautulli command and return its unwrapped data, throwing on a non-success result. */
|
||||||
|
private async cmd(command: string, params: Record<string, string> = {}): Promise<any> {
|
||||||
|
const q = new URLSearchParams({ apikey: this.apiKey, cmd: command, ...params });
|
||||||
|
const res = await fetch(`${this.baseUrl}/api/v2?${q.toString()}`);
|
||||||
|
if (!res.ok) throw new Error(`Tautulli ${command}: ${res.status} ${await res.text()}`);
|
||||||
|
const body = (await res.json()).response ?? {};
|
||||||
|
if (body.result !== "success") throw new Error(`Tautulli ${command}: ${body.message ?? "error"}`);
|
||||||
|
return body.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getActivity(): Promise<{ streamCount: number; sessions: TautulliSession[] }> {
|
||||||
|
const data = await this.cmd("get_activity");
|
||||||
|
const sessions = ((data?.sessions ?? []) as any[]).map((s) => ({
|
||||||
|
user: s.friendly_name ?? s.user ?? "unknown",
|
||||||
|
title: s.full_title ?? s.title ?? "unknown",
|
||||||
|
mediaType: s.media_type ?? "unknown",
|
||||||
|
state: s.state ?? "unknown",
|
||||||
|
progressPercent: Number(s.progress_percent ?? 0),
|
||||||
|
player: s.player ?? "unknown",
|
||||||
|
}));
|
||||||
|
return { streamCount: Number(data?.stream_count ?? sessions.length), sessions };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getHistory(length = 25): Promise<TautulliWatch[]> {
|
||||||
|
const data = await this.cmd("get_history", { length: String(length), order_column: "date", order_dir: "desc" });
|
||||||
|
return ((data?.data ?? []) as any[]).map((r) => ({
|
||||||
|
id: Number(r.row_id ?? r.id ?? r.reference_id ?? 0),
|
||||||
|
user: r.friendly_name ?? r.user ?? "unknown",
|
||||||
|
title: r.full_title ?? r.title ?? "unknown",
|
||||||
|
mediaType: r.media_type ?? "unknown",
|
||||||
|
watchedStatus: String(r.watched_status ?? ""),
|
||||||
|
percentComplete: Number(r.percent_complete ?? 0),
|
||||||
|
date: r.date != null ? Number(r.date) : undefined,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The home-page statistics blocks — most-watched shows, most-active users, and so on. */
|
||||||
|
async getHomeStats(): Promise<TautulliHomeStat[]> {
|
||||||
|
const data = (await this.cmd("get_home_stats")) as any[];
|
||||||
|
return (data ?? []).map((s) => ({ statId: s.stat_id, rows: s.rows ?? [] }));
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user