@soffits/dsh-media-hub 0.15.2 → 0.15.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +5 -3
- package/client.js +4 -4
- package/dist/index.js +345 -346
- package/locale/en.json +3 -1
- package/locale/fr.json +3 -1
- package/locale/zh.json +3 -1
- package/package.json +1 -1
- package/web/boundary.js +31 -0
- package/web/library-view.js +1 -1
- package/web/panel.css +1 -0
package/dist/index.js
CHANGED
|
@@ -9855,6 +9855,11 @@ defineMethod("transform", [
|
|
|
9855
9855
|
|
|
9856
9856
|
// src/delivery.js
|
|
9857
9857
|
import { basename } from "node:path";
|
|
9858
|
+
|
|
9859
|
+
// src/errors.js
|
|
9860
|
+
var codedError = (code, message, fields = {}) => Object.assign(new Error(message), { code, ...fields });
|
|
9861
|
+
|
|
9862
|
+
// src/delivery.js
|
|
9858
9863
|
var PREFIX = "media-hub";
|
|
9859
9864
|
var DELIVERY_MODES = Object.freeze(["origin", "r2"]);
|
|
9860
9865
|
function createDelivery({ mode }) {
|
|
@@ -9869,11 +9874,11 @@ function createDelivery({ mode }) {
|
|
|
9869
9874
|
if (mode === "r2") {
|
|
9870
9875
|
const reason = 'R2 delivery is not built yet; use delivery mode "origin".';
|
|
9871
9876
|
const missing = () => {
|
|
9872
|
-
throw
|
|
9877
|
+
throw codedError("unsupported", reason);
|
|
9873
9878
|
};
|
|
9874
9879
|
return { mode, available: false, reason, mediaUrl: missing, subtitleUrl: missing };
|
|
9875
9880
|
}
|
|
9876
|
-
throw
|
|
9881
|
+
throw codedError("invalid", `unknown delivery mode ${String(mode)}`);
|
|
9877
9882
|
}
|
|
9878
9883
|
|
|
9879
9884
|
// src/proxy.js
|
|
@@ -10454,7 +10459,6 @@ function omit2(obj, ...keys) {
|
|
|
10454
10459
|
|
|
10455
10460
|
// src/hosts.js
|
|
10456
10461
|
import { readFile, stat } from "node:fs/promises";
|
|
10457
|
-
var hostsError = (code, message) => Object.assign(new Error(message), { code });
|
|
10458
10462
|
function hostOf(url) {
|
|
10459
10463
|
try {
|
|
10460
10464
|
return new URL(url).hostname.toLowerCase().replace(/\.$/, "");
|
|
@@ -10481,7 +10485,7 @@ function createHostRules(rules = [], io = {}) {
|
|
|
10481
10485
|
if (files.get(rule.hostsFile)?.version !== current) files.set(rule.hostsFile, { version: current, patterns: parseHosts(await read(rule.hostsFile)) });
|
|
10482
10486
|
} catch (error) {
|
|
10483
10487
|
files.delete(rule.hostsFile);
|
|
10484
|
-
throw
|
|
10488
|
+
throw codedError("hosts_unreadable", `cannot read the hosts file ${rule.hostsFile}: ${error.message}`);
|
|
10485
10489
|
}
|
|
10486
10490
|
return [...listed2, ...files.get(rule.hostsFile).patterns];
|
|
10487
10491
|
}
|
|
@@ -10507,7 +10511,6 @@ var PROXY_URL = /^(socks4a?|socks5h?|https?):\/\/[^\s/]+\/?$/;
|
|
|
10507
10511
|
var MAX_REDIRECTS = 5;
|
|
10508
10512
|
var USER_AGENT = "dsh-media-hub";
|
|
10509
10513
|
var PROBE_TIMEOUT_MS = 3e3;
|
|
10510
|
-
var proxyError = (code, message) => Object.assign(new Error(message), { code });
|
|
10511
10514
|
function proxyAnswers(proxy, timeoutMs = PROBE_TIMEOUT_MS) {
|
|
10512
10515
|
const { hostname, port, protocol } = new URL(proxy);
|
|
10513
10516
|
const defaultPort = protocol.startsWith("socks") ? 1080 : protocol === "https:" ? 443 : 80;
|
|
@@ -10529,7 +10532,7 @@ function createProxies(rules = [], io = {}) {
|
|
|
10529
10532
|
try {
|
|
10530
10533
|
return (await hostRules.match(url, page))?.url ?? "";
|
|
10531
10534
|
} catch (error) {
|
|
10532
|
-
throw
|
|
10535
|
+
throw codedError("proxy_unavailable", error.message);
|
|
10533
10536
|
}
|
|
10534
10537
|
}
|
|
10535
10538
|
function agentFor(proxy) {
|
|
@@ -10539,12 +10542,12 @@ function createProxies(rules = [], io = {}) {
|
|
|
10539
10542
|
}
|
|
10540
10543
|
async function get(url, page, timeoutMs) {
|
|
10541
10544
|
const protocol = new URL(url).protocol;
|
|
10542
|
-
if (protocol !== "https:" && protocol !== "http:") throw
|
|
10545
|
+
if (protocol !== "https:" && protocol !== "http:") throw codedError("invalid", `not a web address: ${url}`);
|
|
10543
10546
|
const agent = agentFor(await route(url, page));
|
|
10544
10547
|
return new Promise((resolve8, reject) => {
|
|
10545
10548
|
const send = protocol === "https:" ? httpsRequest : httpRequest;
|
|
10546
10549
|
const req = send(url, { agent, headers: { "user-agent": USER_AGENT, accept: "image/*,*/*;q=0.5" }, timeout: timeoutMs }, resolve8);
|
|
10547
|
-
req.on("timeout", () => req.destroy(
|
|
10550
|
+
req.on("timeout", () => req.destroy(codedError("timeout", `no answer from ${hostOf(url)} in ${timeoutMs / 1e3} s`)));
|
|
10548
10551
|
req.on("error", reject);
|
|
10549
10552
|
req.end();
|
|
10550
10553
|
});
|
|
@@ -10567,28 +10570,26 @@ function createProxies(rules = [], io = {}) {
|
|
|
10567
10570
|
}
|
|
10568
10571
|
if (statusCode !== 200) {
|
|
10569
10572
|
response.resume();
|
|
10570
|
-
throw
|
|
10573
|
+
throw codedError("fetch_failed", `${hostOf(target)} answered ${statusCode}`);
|
|
10571
10574
|
}
|
|
10572
10575
|
if (Number(headers["content-length"]) > maxBytes) {
|
|
10573
10576
|
response.destroy();
|
|
10574
|
-
throw
|
|
10577
|
+
throw codedError("too_large", `the file is over ${maxBytes} bytes`);
|
|
10575
10578
|
}
|
|
10576
10579
|
let received = 0;
|
|
10577
10580
|
response.on("data", (chunk) => {
|
|
10578
10581
|
received += chunk.length;
|
|
10579
|
-
if (received > maxBytes) response.destroy(
|
|
10582
|
+
if (received > maxBytes) response.destroy(codedError("too_large", `the file is over ${maxBytes} bytes`));
|
|
10580
10583
|
});
|
|
10581
10584
|
await pipeline(response, createWriteStream(file));
|
|
10582
10585
|
return;
|
|
10583
10586
|
}
|
|
10584
|
-
throw
|
|
10587
|
+
throw codedError("fetch_failed", `more than ${MAX_REDIRECTS} redirects from ${hostOf(url)}`);
|
|
10585
10588
|
}
|
|
10586
10589
|
};
|
|
10587
10590
|
}
|
|
10588
10591
|
|
|
10589
10592
|
// src/sources/command.js
|
|
10590
|
-
import { createHash } from "node:crypto";
|
|
10591
|
-
import { createReadStream } from "node:fs";
|
|
10592
10593
|
import { mkdir, rm, stat as stat2 } from "node:fs/promises";
|
|
10593
10594
|
import { basename as basename2, join as join2 } from "node:path";
|
|
10594
10595
|
|
|
@@ -10642,12 +10643,21 @@ function heightChoices(raw) {
|
|
|
10642
10643
|
return heights.length > 1 ? [AUTO, ...heights] : [];
|
|
10643
10644
|
}
|
|
10644
10645
|
|
|
10646
|
+
// src/sha256.js
|
|
10647
|
+
import { createHash } from "node:crypto";
|
|
10648
|
+
import { createReadStream } from "node:fs";
|
|
10649
|
+
function sha256Of(path) {
|
|
10650
|
+
return new Promise((resolve8, reject) => {
|
|
10651
|
+
const hash = createHash("sha256");
|
|
10652
|
+
createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve8(hash.digest("hex")));
|
|
10653
|
+
});
|
|
10654
|
+
}
|
|
10655
|
+
|
|
10645
10656
|
// src/sources/process.js
|
|
10646
10657
|
import { spawn } from "node:child_process";
|
|
10647
10658
|
import { access, constants } from "node:fs/promises";
|
|
10648
10659
|
import { delimiter, isAbsolute, join } from "node:path";
|
|
10649
10660
|
var MAX_OUTPUT = 16 * 1024 * 1024;
|
|
10650
|
-
var sourceError = (code, message) => Object.assign(new Error(message), { code });
|
|
10651
10661
|
async function commandExists(command, path = process.env.PATH ?? "") {
|
|
10652
10662
|
const candidates = isAbsolute(command) ? [command] : path.split(delimiter).filter(Boolean).map((dir) => join(dir, command));
|
|
10653
10663
|
for (const candidate of candidates) {
|
|
@@ -10699,7 +10709,7 @@ function run(argv, { signal, timeoutMs, onStdoutLine, cwd, env, input } = {}) {
|
|
|
10699
10709
|
});
|
|
10700
10710
|
child.on("error", (error) => {
|
|
10701
10711
|
if (timer) clearTimeout(timer);
|
|
10702
|
-
reject(error.code === "ENOENT" ?
|
|
10712
|
+
reject(error.code === "ENOENT" ? codedError("unavailable", `${command} is not installed`) : error);
|
|
10703
10713
|
});
|
|
10704
10714
|
child.on("close", (code) => {
|
|
10705
10715
|
if (timer) clearTimeout(timer);
|
|
@@ -10725,7 +10735,6 @@ var TRENDING_LIMIT = 20;
|
|
|
10725
10735
|
var QUERY_TIMEOUT_MS = 6e4;
|
|
10726
10736
|
var COVER_TIMEOUT_MS = 3e4;
|
|
10727
10737
|
var ID = /^[^\s\0]{1,200}$/;
|
|
10728
|
-
var sourceError2 = (code, message) => Object.assign(new Error(message), { code });
|
|
10729
10738
|
var text = (value) => typeof value === "string" || typeof value === "number" ? String(value).trim() : "";
|
|
10730
10739
|
var numberOrNull = (value) => Number.isFinite(value) ? value : null;
|
|
10731
10740
|
var STATUSES = /* @__PURE__ */ new Set(["finished", "ongoing", "stopped"]);
|
|
@@ -10785,7 +10794,7 @@ function resultOf(raw, kindIds) {
|
|
|
10785
10794
|
return { id, title: text(raw.title), kind, author: text(raw.author), score: numberOrNull(raw.score), blurb: text(raw.blurb).replace(/\s+/g, " "), episodes: countOrNull(raw.episode_count), ...factsOf(raw) };
|
|
10786
10795
|
}
|
|
10787
10796
|
function parseSearch(document2, kinds) {
|
|
10788
|
-
if (!Array.isArray(document2?.results)) throw
|
|
10797
|
+
if (!Array.isArray(document2?.results)) throw codedError("source_failed", "the search answer has no results list");
|
|
10789
10798
|
const kindIds = new Set(kinds.map((kind) => kind.id));
|
|
10790
10799
|
return document2.results.map((raw) => resultOf(raw, kindIds)).filter((result) => result !== null);
|
|
10791
10800
|
}
|
|
@@ -10801,7 +10810,7 @@ function labelOf(value) {
|
|
|
10801
10810
|
function parseTrending(document2, kinds, kind) {
|
|
10802
10811
|
const kindIds = new Set(kinds.map((entry) => entry.id));
|
|
10803
10812
|
const raw = Array.isArray(document2?.lists) ? document2.lists : Array.isArray(document2?.results) ? [{ id: "trending", results: document2.results }] : null;
|
|
10804
|
-
if (raw === null) throw
|
|
10813
|
+
if (raw === null) throw codedError("source_failed", "the trending answer has no lists");
|
|
10805
10814
|
const seen = /* @__PURE__ */ new Set();
|
|
10806
10815
|
return raw.slice(0, MAX_LISTS).flatMap((list, index) => {
|
|
10807
10816
|
const results = Array.isArray(list?.results) ? list.results.map((item) => resultOf(item, kindIds)).filter((result) => result !== null && result.kind === kind) : [];
|
|
@@ -10816,7 +10825,7 @@ function nextOffset(document2, offset = 0) {
|
|
|
10816
10825
|
}
|
|
10817
10826
|
function parseInfo(document2) {
|
|
10818
10827
|
const id = text(document2?.id);
|
|
10819
|
-
if (!ID.test(id)) throw
|
|
10828
|
+
if (!ID.test(id)) throw codedError("source_failed", "the source returned no work");
|
|
10820
10829
|
const listed2 = Array.isArray(document2.episodes) ? document2.episodes.length : 0;
|
|
10821
10830
|
const related = (Array.isArray(document2.related) ? document2.related : []).map((raw) => {
|
|
10822
10831
|
const work = resultOf(raw, null);
|
|
@@ -10833,12 +10842,12 @@ var COMMENTS_PAGE = 20;
|
|
|
10833
10842
|
var count = (value) => Number.isInteger(value) && value >= 0 ? value : 0;
|
|
10834
10843
|
function parseDanmaku(lines, number) {
|
|
10835
10844
|
const found = lines.find((line) => line?.episode === number) ?? (lines.length === 1 ? lines[0] : null);
|
|
10836
|
-
if (!Array.isArray(found?.items)) throw
|
|
10845
|
+
if (!Array.isArray(found?.items)) throw codedError("source_failed", "the danmaku answer has no items");
|
|
10837
10846
|
return found.items.map((raw) => ({ time: Number.isFinite(raw?.time) && raw.time >= 0 ? raw.time : null, text: text(raw?.text).replace(/\s+/g, " ").slice(0, MAX_DANMAKU_TEXT), likes: count(raw?.likes) })).filter((item) => item.time !== null && item.text !== "").sort((a, b) => a.time - b.time).slice(0, MAX_DANMAKU);
|
|
10838
10847
|
}
|
|
10839
10848
|
var ISO_TIME = (value) => typeof value === "string" && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : null;
|
|
10840
10849
|
function parseComments(document2) {
|
|
10841
|
-
if (!Array.isArray(document2?.items)) throw
|
|
10850
|
+
if (!Array.isArray(document2?.items)) throw codedError("source_failed", "the comments answer has no items");
|
|
10842
10851
|
const items = document2.items.map((raw) => ({
|
|
10843
10852
|
id: text(raw?.id),
|
|
10844
10853
|
name: text(raw?.user?.name ?? raw?.name),
|
|
@@ -10851,12 +10860,6 @@ function parseComments(document2) {
|
|
|
10851
10860
|
const next = text(document2.next_cursor ?? document2.next);
|
|
10852
10861
|
return { total: countOrNull(document2.total), items, next: next !== "" && next.length <= MAX_CURSOR && items.length > 0 ? next : null };
|
|
10853
10862
|
}
|
|
10854
|
-
function sha256Of(path) {
|
|
10855
|
-
return new Promise((resolve8, reject) => {
|
|
10856
|
-
const hash = createHash("sha256");
|
|
10857
|
-
createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve8(hash.digest("hex")));
|
|
10858
|
-
});
|
|
10859
|
-
}
|
|
10860
10863
|
async function verify(dir, event, label, logger) {
|
|
10861
10864
|
const name2 = typeof event.name === "string" ? event.name : "";
|
|
10862
10865
|
if (name2 === "" || basename2(name2) !== name2 || name2.startsWith(".")) return { ok: false, name: name2 };
|
|
@@ -10893,8 +10896,8 @@ function createCommandSource(definition, { logger, cwd }) {
|
|
|
10893
10896
|
}
|
|
10894
10897
|
async function answer(args) {
|
|
10895
10898
|
const { code, stdout, stderr, oversized } = await run([...command, ...args], { timeoutMs: QUERY_TIMEOUT_MS, cwd: await workDir(), env });
|
|
10896
|
-
if (oversized) throw
|
|
10897
|
-
if (code !== 0) throw
|
|
10899
|
+
if (oversized) throw codedError("source_failed", `${name2()}: the answer is too large`);
|
|
10900
|
+
if (code !== 0) throw codedError("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
|
|
10898
10901
|
return stdout;
|
|
10899
10902
|
}
|
|
10900
10903
|
async function query(args) {
|
|
@@ -10902,12 +10905,12 @@ function createCommandSource(definition, { logger, cwd }) {
|
|
|
10902
10905
|
try {
|
|
10903
10906
|
return JSON.parse(stdout);
|
|
10904
10907
|
} catch {
|
|
10905
|
-
throw
|
|
10908
|
+
throw codedError("source_failed", `${name2()}: the answer is not JSON`);
|
|
10906
10909
|
}
|
|
10907
10910
|
}
|
|
10908
10911
|
const offers = (kind, verb) => kinds.some((entry) => entry.id === kind && entry[verb] === true);
|
|
10909
10912
|
const checkId = (id) => {
|
|
10910
|
-
if (!ID.test(String(id))) throw
|
|
10913
|
+
if (!ID.test(String(id))) throw codedError("invalid", `not a ${name2()} id`);
|
|
10911
10914
|
};
|
|
10912
10915
|
return {
|
|
10913
10916
|
id: sourceId,
|
|
@@ -10917,7 +10920,7 @@ function createCommandSource(definition, { logger, cwd }) {
|
|
|
10917
10920
|
available: () => commandExists(command[0]),
|
|
10918
10921
|
/** @returns {{ results: object[], next: number | null }} `next` is the offset of the following page when the source offers one. */
|
|
10919
10922
|
async search(textQuery, { kind = kinds[0]?.id, limit = SEARCH_LIMIT, offset = 0, filters = {} } = {}) {
|
|
10920
|
-
if (!kindIds.has(kind)) throw
|
|
10923
|
+
if (!kindIds.has(kind)) throw codedError("invalid", `${name2()} has no kind ${kind}`);
|
|
10921
10924
|
const q = String(textQuery ?? "").trim();
|
|
10922
10925
|
if (q === "") return { results: [], next: null };
|
|
10923
10926
|
const paging = offset > 0 ? ["--offset", String(offset)] : [];
|
|
@@ -10926,36 +10929,36 @@ function createCommandSource(definition, { logger, cwd }) {
|
|
|
10926
10929
|
},
|
|
10927
10930
|
/** What the site itself puts forward for a kind that declares `trending`: lists of works, in the site's order. */
|
|
10928
10931
|
async trending(kind, { limit = TRENDING_LIMIT } = {}) {
|
|
10929
|
-
if (!kinds.some((entry) => entry.id === kind && entry.trending === true)) throw
|
|
10932
|
+
if (!kinds.some((entry) => entry.id === kind && entry.trending === true)) throw codedError("invalid", `${name2()} has no trending list for ${kind}`);
|
|
10930
10933
|
return parseTrending(await query(["trending", "--kind", kind, "--limit", String(limit), "--json"]), kinds, kind);
|
|
10931
10934
|
},
|
|
10932
10935
|
async info(id) {
|
|
10933
|
-
if (!ID.test(String(id))) throw
|
|
10936
|
+
if (!ID.test(String(id))) throw codedError("invalid", `not a ${name2()} id`);
|
|
10934
10937
|
return parseInfo(await query(["info", "--json", "--", String(id)]));
|
|
10935
10938
|
},
|
|
10936
10939
|
/** Fetch a cover image into `file` through the command, which keeps its own network policy. Rejects when the command has no `cover` verb or cannot fetch it. */
|
|
10937
10940
|
async cover(url, file) {
|
|
10938
|
-
if (!WEB_URL.test(String(url))) throw
|
|
10941
|
+
if (!WEB_URL.test(String(url))) throw codedError("invalid", "not a cover url");
|
|
10939
10942
|
const { code, stderr } = await run([...command, "cover", "--output", file, "--", String(url)], { timeoutMs: COVER_TIMEOUT_MS, cwd: await workDir(), env });
|
|
10940
|
-
if (code !== 0) throw
|
|
10943
|
+
if (code !== 0) throw codedError("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
|
|
10941
10944
|
},
|
|
10942
10945
|
offers,
|
|
10943
10946
|
/** The danmaku of episode `number` of a work of a kind that declares `danmaku`: `[{ time, text, likes }]`. */
|
|
10944
10947
|
async danmaku(id, number, kind) {
|
|
10945
10948
|
checkId(id);
|
|
10946
|
-
if (!offers(kind, "danmaku") || !Number.isInteger(number) || number < 1) throw
|
|
10949
|
+
if (!offers(kind, "danmaku") || !Number.isInteger(number) || number < 1) throw codedError("invalid", `${name2()} has no danmaku for this`);
|
|
10947
10950
|
const lines = (await answer(["danmaku", "--episodes", String(number), "--json", "--", String(id)])).split("\n").map(parseLine).filter((line) => line !== null);
|
|
10948
10951
|
return parseDanmaku(lines, number);
|
|
10949
10952
|
},
|
|
10950
10953
|
/** A page of the comments on a work of a kind that declares `comments`; `cursor` continues where an earlier page's `next` left off. */
|
|
10951
10954
|
async comments(id, kind, { cursor = "", limit = COMMENTS_PAGE } = {}) {
|
|
10952
10955
|
checkId(id);
|
|
10953
|
-
if (!offers(kind, "comments")) throw
|
|
10956
|
+
if (!offers(kind, "comments")) throw codedError("invalid", `${name2()} has no comments for this`);
|
|
10954
10957
|
const paging = cursor === "" ? [] : ["--cursor", String(cursor).slice(0, MAX_CURSOR)];
|
|
10955
10958
|
return parseComments(await query(["comments", "--limit", String(limit), ...paging, "--json", "--", String(id)]));
|
|
10956
10959
|
},
|
|
10957
10960
|
async download({ id, dir, from: from2 = 1, to = null, quality = "", signal, onEpisode, onStart, onPartial }) {
|
|
10958
|
-
if (!ID.test(String(id))) throw
|
|
10961
|
+
if (!ID.test(String(id))) throw codedError("invalid", `not a ${name2()} id`);
|
|
10959
10962
|
const failed = [];
|
|
10960
10963
|
let result = null;
|
|
10961
10964
|
let checking = Promise.resolve();
|
|
@@ -10994,9 +10997,9 @@ function createCommandSource(definition, { logger, cwd }) {
|
|
|
10994
10997
|
if (signal?.aborted) return { failed };
|
|
10995
10998
|
if (code !== 0 && failed.length === 0) {
|
|
10996
10999
|
logger.warn("%s download %s ended with %s: %s", name2(), id, code, lastLine(stderr));
|
|
10997
|
-
throw
|
|
11000
|
+
throw codedError("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
|
|
10998
11001
|
}
|
|
10999
|
-
if (code === 0 && result === null) throw
|
|
11002
|
+
if (code === 0 && result === null) throw codedError("source_failed", `${name2()}: the download ended without a result`);
|
|
11000
11003
|
return { failed };
|
|
11001
11004
|
},
|
|
11002
11005
|
/**
|
|
@@ -11004,8 +11007,8 @@ function createCommandSource(definition, { logger, cwd }) {
|
|
|
11004
11007
|
* @returns {Promise<{ name: string, bytes: number, sha256: string }>} the file, checked against what the command reported
|
|
11005
11008
|
*/
|
|
11006
11009
|
async downloadFile({ id, format, dir, signal }) {
|
|
11007
|
-
if (!ID.test(String(id))) throw
|
|
11008
|
-
if (!FORMAT.test(String(format))) throw
|
|
11010
|
+
if (!ID.test(String(id))) throw codedError("invalid", `not a ${name2()} id`);
|
|
11011
|
+
if (!FORMAT.test(String(format))) throw codedError("invalid", `not a format: ${format}`);
|
|
11009
11012
|
await mkdir(dir, { recursive: true });
|
|
11010
11013
|
const reported = [];
|
|
11011
11014
|
let result = null;
|
|
@@ -11016,12 +11019,12 @@ function createCommandSource(definition, { logger, cwd }) {
|
|
|
11016
11019
|
};
|
|
11017
11020
|
const argv = [...command, "download", `--id=${String(id)}`, "--format", String(format), "--output", dir, "--json"];
|
|
11018
11021
|
const { code, stderr } = await run(argv, { signal, cwd: await workDir(), env, onStdoutLine: onLine });
|
|
11019
|
-
if (signal?.aborted) throw
|
|
11020
|
-
if (code !== 0) throw
|
|
11021
|
-
if (result === null || reported.length === 0) throw
|
|
11022
|
+
if (signal?.aborted) throw codedError("cancelled", `${name2()}: cancelled`);
|
|
11023
|
+
if (code !== 0) throw codedError("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
|
|
11024
|
+
if (result === null || reported.length === 0) throw codedError("source_failed", `${name2()}: the download ended without a file`);
|
|
11022
11025
|
const event = reported[reported.length - 1];
|
|
11023
11026
|
const file = await verify(dir, event, name2(), logger);
|
|
11024
|
-
if (!file.ok) throw
|
|
11027
|
+
if (!file.ok) throw codedError("source_failed", `${name2()}: the file did not arrive whole`);
|
|
11025
11028
|
return { name: file.name, bytes: event.bytes, sha256: typeof event.sha256 === "string" ? event.sha256 : await sha256Of(join2(dir, file.name)) };
|
|
11026
11029
|
}
|
|
11027
11030
|
};
|
|
@@ -11141,7 +11144,7 @@ async function scanSource(path) {
|
|
|
11141
11144
|
const folder = info.isDirectory() ? path : dirname(path);
|
|
11142
11145
|
const names = await readdir(folder);
|
|
11143
11146
|
const videos = info.isDirectory() ? naturalSort(names.filter(isMedia)) : [basename4(path)];
|
|
11144
|
-
if (videos.length === 0) throw
|
|
11147
|
+
if (videos.length === 0) throw codedError("empty", `no video or audio files in ${path}`);
|
|
11145
11148
|
return videos.map((name2) => ({
|
|
11146
11149
|
title: titleOf2(name2),
|
|
11147
11150
|
path: join3(folder, name2),
|
|
@@ -11209,7 +11212,6 @@ function planVideo(path, info, { fastStart, maxHeight }) {
|
|
|
11209
11212
|
import { randomBytes } from "node:crypto";
|
|
11210
11213
|
import { copyFile, chmod, mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
|
|
11211
11214
|
import { join as join4 } from "node:path";
|
|
11212
|
-
var cookiesError = (code, message) => Object.assign(new Error(message), { code });
|
|
11213
11215
|
var accountView = (account) => account === null ? null : { name: account.name || account.person || "" };
|
|
11214
11216
|
function createCookies(rules = [], io = {}) {
|
|
11215
11217
|
const hostRules = createHostRules(rules, io);
|
|
@@ -11237,7 +11239,7 @@ function createCookies(rules = [], io = {}) {
|
|
|
11237
11239
|
await chmod(copy, 384);
|
|
11238
11240
|
} catch (error) {
|
|
11239
11241
|
await rm2(copy, { force: true });
|
|
11240
|
-
throw
|
|
11242
|
+
throw codedError("cookies_unavailable", `cannot read the cookies of the account ${accountView(account).name}: ${error.code ?? error.message}`);
|
|
11241
11243
|
}
|
|
11242
11244
|
const args = ["--cookies", copy, ...account.userAgent ? ["--user-agent", account.userAgent] : []];
|
|
11243
11245
|
return { args, done: () => rm2(copy, { force: true }) };
|
|
@@ -11749,8 +11751,7 @@ var REASON_TEXT = Object.freeze({
|
|
|
11749
11751
|
proxy_down: "the proxy for this site is not answering",
|
|
11750
11752
|
failed: "the site did not give the video"
|
|
11751
11753
|
});
|
|
11752
|
-
var
|
|
11753
|
-
var failure = (reason) => linkError("source_failed", REASON_TEXT[reason], reason);
|
|
11754
|
+
var failure = (reason) => codedError("source_failed", REASON_TEXT[reason], { reason });
|
|
11754
11755
|
var isWebAddress = (value) => {
|
|
11755
11756
|
try {
|
|
11756
11757
|
return ["http:", "https:"].includes(new URL(value).protocol);
|
|
@@ -11815,7 +11816,7 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
|
|
|
11815
11816
|
return cwd;
|
|
11816
11817
|
}
|
|
11817
11818
|
async function access2(url, person) {
|
|
11818
|
-
if (!isWebAddress(url)) throw
|
|
11819
|
+
if (!isWebAddress(url)) throw codedError("invalid", "not a web address");
|
|
11819
11820
|
let proxy;
|
|
11820
11821
|
try {
|
|
11821
11822
|
proxy = await proxies.route(url);
|
|
@@ -11857,12 +11858,12 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
|
|
|
11857
11858
|
}
|
|
11858
11859
|
async function lookUp(url, args, options) {
|
|
11859
11860
|
const result = await ytdlp(url, ["-J", ...args], options);
|
|
11860
|
-
if (result.oversized) throw
|
|
11861
|
+
if (result.oversized) throw codedError("source_failed", "the page lists too much to read", { reason: "failed" });
|
|
11861
11862
|
if (result.code !== 0) throw await reasonOf(url, result);
|
|
11862
11863
|
try {
|
|
11863
11864
|
return { data: JSON.parse(result.stdout), account: result.account };
|
|
11864
11865
|
} catch {
|
|
11865
|
-
throw
|
|
11866
|
+
throw codedError("source_failed", "yt-dlp answered something that is not JSON", { reason: "failed" });
|
|
11866
11867
|
}
|
|
11867
11868
|
}
|
|
11868
11869
|
async function fetchCaptions(url, { entry, load, work, dir, stem, language, person, signal }) {
|
|
@@ -11909,8 +11910,8 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
|
|
|
11909
11910
|
async info(url, { person = "" } = {}) {
|
|
11910
11911
|
const { data, account } = await lookUp(String(url), ["--flat-playlist"], { person, timeoutMs: INFO_TIMEOUT_MS });
|
|
11911
11912
|
const document2 = infoDocument(data, String(url), maxHeight);
|
|
11912
|
-
if (document2.id.length > MAX_URL) throw
|
|
11913
|
-
if (document2.episodes.length === 0) throw
|
|
11913
|
+
if (document2.id.length > MAX_URL) throw codedError("invalid", "the address is too long");
|
|
11914
|
+
if (document2.episodes.length === 0) throw codedError("empty", "there is no video at this address", { reason: "not_found" });
|
|
11914
11915
|
return { ...parseInfo(document2), qualities: document2.qualities, account: accountView(account) };
|
|
11915
11916
|
},
|
|
11916
11917
|
/** The thumbnail, through the route of its own host or its page's. */
|
|
@@ -12262,6 +12263,14 @@ function resolveRange(header, size) {
|
|
|
12262
12263
|
if (start >= size || end < start) return { kind: "unsatisfiable" };
|
|
12263
12264
|
return { kind: "window", start, end };
|
|
12264
12265
|
}
|
|
12266
|
+
function rangePlan(header, size) {
|
|
12267
|
+
const range = resolveRange(header, size);
|
|
12268
|
+
if (range.kind === "unsatisfiable") return { status: 416, headers: { "content-range": `bytes */${size}` } };
|
|
12269
|
+
const start = range.kind === "window" ? range.start : 0;
|
|
12270
|
+
const end = range.kind === "window" ? range.end : size - 1;
|
|
12271
|
+
const headers = { "content-length": String(size === 0 ? 0 : end - start + 1), ...range.kind === "window" ? { "content-range": `bytes ${start}-${end}/${size}` } : {} };
|
|
12272
|
+
return { status: range.kind === "window" ? 206 : 200, start, end, headers };
|
|
12273
|
+
}
|
|
12265
12274
|
async function sendFile(req, res, path, type = MEDIA_TYPES[extname5(path).toLowerCase()] ?? "application/octet-stream") {
|
|
12266
12275
|
let info;
|
|
12267
12276
|
try {
|
|
@@ -12270,24 +12279,13 @@ async function sendFile(req, res, path, type = MEDIA_TYPES[extname5(path).toLowe
|
|
|
12270
12279
|
return sendText(res, 404, "Not found.");
|
|
12271
12280
|
}
|
|
12272
12281
|
if (!info.isFile()) return sendText(res, 404, "Not found.");
|
|
12273
|
-
const
|
|
12274
|
-
|
|
12275
|
-
|
|
12276
|
-
if (range.kind === "unsatisfiable") {
|
|
12277
|
-
res.writeHead(416, { ...headers, "content-range": `bytes */${size}` }).end();
|
|
12278
|
-
return;
|
|
12279
|
-
}
|
|
12280
|
-
const start = range.kind === "window" ? range.start : 0;
|
|
12281
|
-
const end = range.kind === "window" ? range.end : size - 1;
|
|
12282
|
-
const status = range.kind === "window" ? 206 : 200;
|
|
12283
|
-
if (range.kind === "window") headers["content-range"] = `bytes ${start}-${end}/${size}`;
|
|
12284
|
-
headers["content-length"] = String(size === 0 ? 0 : end - start + 1);
|
|
12285
|
-
res.writeHead(status, headers);
|
|
12286
|
-
if (req.method === "HEAD" || size === 0) {
|
|
12282
|
+
const plan = rangePlan(req.headers.range, info.size);
|
|
12283
|
+
res.writeHead(plan.status, { ...SECURITY_HEADERS, "cache-control": "private, no-store", "accept-ranges": "bytes", "content-type": type, ...plan.headers });
|
|
12284
|
+
if (plan.status === 416 || req.method === "HEAD" || info.size === 0) {
|
|
12287
12285
|
res.end();
|
|
12288
12286
|
return;
|
|
12289
12287
|
}
|
|
12290
|
-
const stream = createReadStream2(path, { start, end });
|
|
12288
|
+
const stream = createReadStream2(path, { start: plan.start, end: plan.end });
|
|
12291
12289
|
stream.on("error", () => res.destroy());
|
|
12292
12290
|
res.on("close", () => stream.destroy());
|
|
12293
12291
|
stream.pipe(res);
|
|
@@ -12323,17 +12321,68 @@ async function readJson(req) {
|
|
|
12323
12321
|
throw Object.assign(new Error("request body is not JSON"), { status: 400 });
|
|
12324
12322
|
}
|
|
12325
12323
|
}
|
|
12324
|
+
var API = Object.freeze([
|
|
12325
|
+
["GET", "rooms", async ({ hub }) => ({ rooms: await hub.listRooms() })],
|
|
12326
|
+
["GET", "rooms/:room/work", ({ hub, params }) => hub.roomWork(params.room)],
|
|
12327
|
+
["GET", "rooms/:room/danmaku/:index", ({ hub, params }) => hub.roomDanmaku(params.room, Number(params.index))],
|
|
12328
|
+
["GET", "rooms/:room/comments", ({ hub, params, query }) => hub.roomComments(params.room, query("cursor"))],
|
|
12329
|
+
["POST", "rooms/:room/quality", async ({ hub, params, body: body2 }) => hub.roomQuality(params.room, String((await body2()).quality ?? ""))],
|
|
12330
|
+
["POST", "rooms/:room/together", ({ hub, params }) => hub.watchTogether(params.room)],
|
|
12331
|
+
["DELETE", "rooms/:room", ({ hub, params }) => hub.closeRoom(params.room)],
|
|
12332
|
+
["GET", "library", ({ hub }) => hub.library()],
|
|
12333
|
+
["GET", "library/episodes", async ({ hub, query }) => ({ episodes: await hub.episodes(query("path")) })],
|
|
12334
|
+
["DELETE", "library", ({ hub, query }) => query("episode") ? hub.removeEpisode(query("path"), query("episode"), query("by") || null) : hub.removeShow(query("path"), query("by") || null)],
|
|
12335
|
+
["POST", "library/rename", async ({ hub, body: body2 }) => {
|
|
12336
|
+
const input = await body2();
|
|
12337
|
+
return hub.renameShow(input.path, input.name, byOf(input));
|
|
12338
|
+
}],
|
|
12339
|
+
["POST", "library/keep", async ({ hub, body: body2 }) => {
|
|
12340
|
+
const input = await body2();
|
|
12341
|
+
return hub.keepShow(input.path, byOf(input));
|
|
12342
|
+
}],
|
|
12343
|
+
["POST", "library/countdown", async ({ hub, body: body2 }) => {
|
|
12344
|
+
const input = await body2();
|
|
12345
|
+
return hub.countdownShow(input.path, byOf(input));
|
|
12346
|
+
}],
|
|
12347
|
+
["POST", "library/retry", async ({ hub, body: body2 }) => hub.retryDownload((await body2()).path)],
|
|
12348
|
+
["POST", "library/pin", async ({ hub, body: body2 }) => {
|
|
12349
|
+
const input = await body2();
|
|
12350
|
+
return hub.pinShow(input.path, input.pinned === true, byOf(input));
|
|
12351
|
+
}],
|
|
12352
|
+
["POST", "library/seen", async ({ hub, body: body2 }) => hub.dismissNews((await body2()).path)],
|
|
12353
|
+
["POST", "library/cancel", async ({ hub, body: body2 }) => hub.cancelDownload((await body2()).path)],
|
|
12354
|
+
["POST", "follow", async ({ hub, body: body2 }) => hub.followWork(pick3(await body2(), ["source", "id", "follow"]))],
|
|
12355
|
+
["GET", "settings", ({ settings }) => settings()],
|
|
12356
|
+
["GET", "locales", ({ localeDir, logger }) => readLocales(localeDir, logger)],
|
|
12357
|
+
["GET", "sources", async ({ hub }) => ({ sources: await hub.sources() })],
|
|
12358
|
+
["GET", "trending", ({ hub, query }) => hub.trending(query("source"), query("kind"))],
|
|
12359
|
+
["GET", "search", ({ hub, query }) => hub.search(query("source"), query("q"), query("kind") || void 0, Math.max(0, Number.parseInt(query("offset"), 10) || 0), parseFilters(query))]
|
|
12360
|
+
].map(([method, path, answer]) => ({ method, segments: path.split("/"), answer })));
|
|
12361
|
+
function matchApi(method, parts) {
|
|
12362
|
+
for (const route of API) {
|
|
12363
|
+
if (route.method !== method || route.segments.length !== parts.length) continue;
|
|
12364
|
+
const params = {};
|
|
12365
|
+
if (route.segments.every((segment, n) => segment.startsWith(":") ? (params[segment.slice(1)] = parts[n]) !== void 0 : segment === parts[n])) return { answer: route.answer, params };
|
|
12366
|
+
}
|
|
12367
|
+
return null;
|
|
12368
|
+
}
|
|
12326
12369
|
var STATUS = Object.freeze({ points: 402, invalid: 400, empty: 400, not_found: 404, unsupported: 501, outside: 403, in_use: 409, exists: 409, no_space: 507, source_failed: 424, unavailable: 503 });
|
|
12370
|
+
var statusOf = (error) => error?.status ?? STATUS[error?.code] ?? 500;
|
|
12327
12371
|
var errorBody = (error) => ({ error: { code: error?.code ?? "error", ...error?.reason ? { reason: error.reason } : {}, ...error?.points ? { points: error.points } : {}, message: error?.message ?? String(error) } });
|
|
12328
12372
|
function createHandler({ connection, service, settings = () => ({ label: "", presence: {} }), localeDir = LOCALE_DIR, logger }) {
|
|
12329
12373
|
return async (req, res) => {
|
|
12330
12374
|
const admitted = admitOwner(connection, req);
|
|
12331
12375
|
if (!admitted.ok) return sendText(res, admitted.status, admitted.status === 401 ? "Sign in to DSH first." : "Forbidden.");
|
|
12332
12376
|
const url = new URL(req.url ?? "/", "http://media-hub.invalid");
|
|
12333
|
-
const parts = url.pathname.slice(ROUTE.length + 1).split("/").map(decodeURIComponent);
|
|
12334
12377
|
const hub = service();
|
|
12335
12378
|
if (hub === void 0) return sendText(res, 503, "The media hub is starting.");
|
|
12336
12379
|
try {
|
|
12380
|
+
let parts;
|
|
12381
|
+
try {
|
|
12382
|
+
parts = url.pathname.slice(ROUTE.length + 1).split("/").map(decodeURIComponent);
|
|
12383
|
+
} catch {
|
|
12384
|
+
return sendText(res, 400, "Bad address.");
|
|
12385
|
+
}
|
|
12337
12386
|
if (parts[0] === "web" && parts.length === 2 && req.method === "GET") {
|
|
12338
12387
|
const file = webFile(parts[1]);
|
|
12339
12388
|
const body2 = file === void 0 ? null : await readFile5(file).catch(() => null);
|
|
@@ -12361,51 +12410,15 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
|
|
|
12361
12410
|
return file === void 0 ? sendText(res, 404, "Not found.") : sendFile(req, res, file, MEDIA_TYPES[".vtt"]);
|
|
12362
12411
|
}
|
|
12363
12412
|
if (parts[0] === "api") {
|
|
12364
|
-
const
|
|
12365
|
-
|
|
12366
|
-
|
|
12367
|
-
|
|
12368
|
-
|
|
12369
|
-
if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "comments") return sendJson(res, 200, await hub.roomComments(parts[2], query("cursor")));
|
|
12370
|
-
if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "quality") return sendJson(res, 200, await hub.roomQuality(parts[2], String((await readJson(req)).quality ?? "")));
|
|
12371
|
-
if (req.method === "DELETE" && parts[1] === "rooms" && parts.length === 3) return sendJson(res, 200, hub.closeRoom(parts[2]));
|
|
12372
|
-
if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "together") return sendJson(res, 200, hub.watchTogether(parts[2]));
|
|
12373
|
-
if (route === "GET library") return sendJson(res, 200, await hub.library());
|
|
12374
|
-
if (route === "GET library/episodes") return sendJson(res, 200, { episodes: await hub.episodes(query("path")) });
|
|
12375
|
-
if (route === "DELETE library") {
|
|
12376
|
-
const by = query("by") || null;
|
|
12377
|
-
return sendJson(res, 200, query("episode") ? await hub.removeEpisode(query("path"), query("episode"), by) : await hub.removeShow(query("path"), by));
|
|
12378
|
-
}
|
|
12379
|
-
if (route === "POST library/rename") {
|
|
12380
|
-
const body2 = await readJson(req);
|
|
12381
|
-
return sendJson(res, 200, await hub.renameShow(body2.path, body2.name, byOf(body2)));
|
|
12382
|
-
}
|
|
12383
|
-
if (route === "POST library/keep") {
|
|
12384
|
-
const body2 = await readJson(req);
|
|
12385
|
-
return sendJson(res, 200, await hub.keepShow(body2.path, byOf(body2)));
|
|
12386
|
-
}
|
|
12387
|
-
if (route === "POST library/countdown") {
|
|
12388
|
-
const body2 = await readJson(req);
|
|
12389
|
-
return sendJson(res, 200, await hub.countdownShow(body2.path, byOf(body2)));
|
|
12390
|
-
}
|
|
12391
|
-
if (route === "POST library/retry") return sendJson(res, 200, await hub.retryDownload((await readJson(req)).path));
|
|
12392
|
-
if (route === "POST library/pin") {
|
|
12393
|
-
const body2 = await readJson(req);
|
|
12394
|
-
return sendJson(res, 200, await hub.pinShow(body2.path, body2.pinned === true, byOf(body2)));
|
|
12395
|
-
}
|
|
12396
|
-
if (route === "POST follow") return sendJson(res, 200, await hub.followWork(pick3(await readJson(req), ["source", "id", "follow"])));
|
|
12397
|
-
if (route === "POST library/seen") return sendJson(res, 200, hub.dismissNews((await readJson(req)).path));
|
|
12398
|
-
if (route === "POST library/cancel") return sendJson(res, 200, await hub.cancelDownload((await readJson(req)).path));
|
|
12399
|
-
if (route === "GET settings") return sendJson(res, 200, settings());
|
|
12400
|
-
if (route === "GET locales") return sendJson(res, 200, await readLocales(localeDir, logger));
|
|
12401
|
-
if (route === "GET sources") return sendJson(res, 200, { sources: await hub.sources() });
|
|
12402
|
-
if (route === "GET trending") return sendJson(res, 200, await hub.trending(query("source"), query("kind")));
|
|
12403
|
-
if (route === "GET search") return sendJson(res, 200, await hub.search(query("source"), query("q"), query("kind") || void 0, Math.max(0, Number.parseInt(query("offset"), 10) || 0), parseFilters(query)));
|
|
12413
|
+
const found = matchApi(req.method, parts.slice(1));
|
|
12414
|
+
if (found !== null) {
|
|
12415
|
+
const query = (name2) => url.searchParams.get(name2) ?? "";
|
|
12416
|
+
return sendJson(res, 200, await found.answer({ hub, params: found.params, query, body: () => readJson(req), settings, localeDir, logger }));
|
|
12417
|
+
}
|
|
12404
12418
|
}
|
|
12405
12419
|
return sendText(res, 404, "Not found.");
|
|
12406
12420
|
} catch (error) {
|
|
12407
|
-
|
|
12408
|
-
if (!res.headersSent) sendJson(res, status, errorBody(error));
|
|
12421
|
+
if (!res.headersSent) sendJson(res, statusOf(error), errorBody(error));
|
|
12409
12422
|
else res.destroy();
|
|
12410
12423
|
}
|
|
12411
12424
|
};
|
|
@@ -12426,9 +12439,48 @@ import { statfs as statfs2, stat as stat10 } from "node:fs/promises";
|
|
|
12426
12439
|
import { join as join17, resolve as resolve6 } from "node:path";
|
|
12427
12440
|
|
|
12428
12441
|
// src/downloads.js
|
|
12429
|
-
import { readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
|
|
12430
12442
|
import { join as join11 } from "node:path";
|
|
12431
12443
|
|
|
12444
|
+
// src/json-file.js
|
|
12445
|
+
import { mkdir as mkdir6, readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
|
|
12446
|
+
import { dirname as dirname5 } from "node:path";
|
|
12447
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12448
|
+
async function readJson2(file, { logger, valid = isObject, now = Date.now }) {
|
|
12449
|
+
let problem;
|
|
12450
|
+
try {
|
|
12451
|
+
const value = JSON.parse(await readFile6(file, "utf8"));
|
|
12452
|
+
if (valid(value)) return { value, damaged: false };
|
|
12453
|
+
problem = "not the expected shape";
|
|
12454
|
+
} catch (error) {
|
|
12455
|
+
if (error.code === "ENOENT") return { value: void 0, damaged: false };
|
|
12456
|
+
problem = error.message;
|
|
12457
|
+
}
|
|
12458
|
+
const aside = `${file}.bad-${now()}`;
|
|
12459
|
+
await rename3(file, aside).then(
|
|
12460
|
+
() => logger.warn("could not read %s (%s); moved it to %s and started empty", file, problem, aside),
|
|
12461
|
+
(error) => logger.warn("could not read %s (%s) nor move it aside: %s", file, problem, error.message)
|
|
12462
|
+
);
|
|
12463
|
+
return { value: void 0, damaged: true };
|
|
12464
|
+
}
|
|
12465
|
+
var serialize = (value) => JSON.stringify(value, null, 1);
|
|
12466
|
+
async function writeWhole(file, body2) {
|
|
12467
|
+
await mkdir6(dirname5(file), { recursive: true });
|
|
12468
|
+
await writeFile3(`${file}.part`, body2);
|
|
12469
|
+
await rename3(`${file}.part`, file);
|
|
12470
|
+
}
|
|
12471
|
+
var writeJson = (file, value) => writeWhole(file, serialize(value));
|
|
12472
|
+
function createJsonSaver(file, logger) {
|
|
12473
|
+
let saving = Promise.resolve();
|
|
12474
|
+
return {
|
|
12475
|
+
save(value) {
|
|
12476
|
+
const body2 = serialize(value);
|
|
12477
|
+
saving = saving.then(() => writeWhole(file, body2)).catch((error) => logger.warn("could not save %s: %s", file, error.message));
|
|
12478
|
+
return saving;
|
|
12479
|
+
},
|
|
12480
|
+
settled: () => saving
|
|
12481
|
+
};
|
|
12482
|
+
}
|
|
12483
|
+
|
|
12432
12484
|
// src/window.js
|
|
12433
12485
|
function windowOf(focus, total, { ahead, behind }) {
|
|
12434
12486
|
return { first: Math.max(1, focus - behind), last: Math.min(total, focus + ahead) };
|
|
@@ -12480,23 +12532,24 @@ function nextOfRun(job, onDisk) {
|
|
|
12480
12532
|
for (let n = job.at ?? from2; n <= to; n++) if (!onDisk.has(n)) return n;
|
|
12481
12533
|
return null;
|
|
12482
12534
|
}
|
|
12483
|
-
var sourceError3 = (code, message) => Object.assign(new Error(message), { code });
|
|
12484
12535
|
function createDownloads({ stateDir, sources, have, hasSpace = async () => true, onFiles, onProgress = () => {
|
|
12485
12536
|
}, onPartial = () => {
|
|
12486
|
-
}, logger, now = Date.now }) {
|
|
12537
|
+
}, logger, stopWaitMs = 1e4, now = Date.now }) {
|
|
12487
12538
|
const file = join11(stateDir, "downloads.json");
|
|
12488
12539
|
const jobs = /* @__PURE__ */ new Map();
|
|
12489
12540
|
let running = null;
|
|
12490
12541
|
let disposed = false;
|
|
12491
|
-
|
|
12542
|
+
const saver = createJsonSaver(file, logger);
|
|
12492
12543
|
let notifying = Promise.resolve();
|
|
12544
|
+
async function letGo(busy) {
|
|
12545
|
+
const end = Date.now() + stopWaitMs;
|
|
12546
|
+
while (busy()) {
|
|
12547
|
+
if (Date.now() > end) return logger.warn("a download did not stop when asked; going on without waiting for it");
|
|
12548
|
+
await new Promise((done) => setTimeout(done, 50));
|
|
12549
|
+
}
|
|
12550
|
+
}
|
|
12493
12551
|
function save() {
|
|
12494
|
-
|
|
12495
|
-
saving = saving.then(async () => {
|
|
12496
|
-
await writeFile3(`${file}.part`, body2);
|
|
12497
|
-
await rename3(`${file}.part`, file);
|
|
12498
|
-
}).catch((error) => logger.warn("could not save downloads: %s", error.message));
|
|
12499
|
-
return saving;
|
|
12552
|
+
return saver.save({ jobs: [...jobs.values()].map(({ controller, current, at, ...job }) => job) });
|
|
12500
12553
|
}
|
|
12501
12554
|
function notify(job) {
|
|
12502
12555
|
notifying = notifying.then(() => onFiles(job)).catch((error) => logger.warn("after a download step: %s", error.message));
|
|
@@ -12528,11 +12581,11 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
|
|
|
12528
12581
|
const { signal } = job.controller;
|
|
12529
12582
|
save();
|
|
12530
12583
|
try {
|
|
12531
|
-
if (source === void 0) throw
|
|
12584
|
+
if (source === void 0) throw codedError("unavailable", `source ${job.source} is not available`);
|
|
12532
12585
|
for (; ; ) {
|
|
12533
12586
|
const range = nextRun(job.want, await have(job.dir));
|
|
12534
12587
|
if (range === null || signal.aborted) break;
|
|
12535
|
-
if (!await hasSpace()) throw
|
|
12588
|
+
if (!await hasSpace()) throw codedError("no_space", "the library disk is almost full; delete something first");
|
|
12536
12589
|
job.current = range;
|
|
12537
12590
|
job.at = range[0];
|
|
12538
12591
|
const result = await source.download({ ...howOf(job.how), id: job.id, dir: job.dir, from: range[0], to: range[1], signal, onStart: (n) => {
|
|
@@ -12542,7 +12595,7 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
|
|
|
12542
12595
|
if (signal.aborted) break;
|
|
12543
12596
|
if (result.failed.length > 0) {
|
|
12544
12597
|
job.failed = result.failed;
|
|
12545
|
-
throw
|
|
12598
|
+
throw codedError("source_failed", `${result.failed.length} episodes could not be downloaded`);
|
|
12546
12599
|
}
|
|
12547
12600
|
}
|
|
12548
12601
|
if (signal.aborted) {
|
|
@@ -12568,12 +12621,7 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
|
|
|
12568
12621
|
}
|
|
12569
12622
|
return {
|
|
12570
12623
|
async load() {
|
|
12571
|
-
|
|
12572
|
-
try {
|
|
12573
|
-
data = JSON.parse(await readFile6(file, "utf8"));
|
|
12574
|
-
} catch (error) {
|
|
12575
|
-
if (error.code !== "ENOENT") logger.warn("could not read %s: %s", file, error.message);
|
|
12576
|
-
}
|
|
12624
|
+
const data = (await readJson2(file, { logger })).value ?? {};
|
|
12577
12625
|
for (const job of data.jobs ?? []) if (Array.isArray(job.want)) jobs.set(job.dir, { ...job, status: job.status === "running" ? "queued" : job.status });
|
|
12578
12626
|
pump();
|
|
12579
12627
|
},
|
|
@@ -12652,13 +12700,13 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
|
|
|
12652
12700
|
jobs.delete(dir);
|
|
12653
12701
|
job.controller?.abort("cancel");
|
|
12654
12702
|
save();
|
|
12655
|
-
|
|
12703
|
+
await letGo(() => running === job);
|
|
12656
12704
|
},
|
|
12657
12705
|
async dispose() {
|
|
12658
12706
|
disposed = true;
|
|
12659
12707
|
running?.controller?.abort("stop");
|
|
12660
|
-
|
|
12661
|
-
await
|
|
12708
|
+
await letGo(() => running !== null);
|
|
12709
|
+
await saver.settled();
|
|
12662
12710
|
}
|
|
12663
12711
|
};
|
|
12664
12712
|
}
|
|
@@ -12675,6 +12723,7 @@ function createCache({ library, downloads, rooms, window: size, logger }) {
|
|
|
12675
12723
|
const out = /* @__PURE__ */ new Map();
|
|
12676
12724
|
for (const path of await library.sourcedShows()) {
|
|
12677
12725
|
const info = await library.cacheInfo(path);
|
|
12726
|
+
if (info === null) continue;
|
|
12678
12727
|
const set2 = /* @__PURE__ */ new Set();
|
|
12679
12728
|
for (const focus of rooms.focusesOf(path)) {
|
|
12680
12729
|
const { first, last } = windowOf(focus, info.total, size);
|
|
@@ -12722,6 +12771,7 @@ function createCache({ library, downloads, rooms, window: size, logger }) {
|
|
|
12722
12771
|
refreshActive: () => serial(async () => {
|
|
12723
12772
|
for (const path of await library.sourcedShows()) {
|
|
12724
12773
|
const info = await library.cacheInfo(path);
|
|
12774
|
+
if (info === null) continue;
|
|
12725
12775
|
if (info.pinned || rooms.focusesOf(path).length > 0) await refreshShow(path);
|
|
12726
12776
|
}
|
|
12727
12777
|
await enforceCap();
|
|
@@ -12751,7 +12801,7 @@ function createCache({ library, downloads, rooms, window: size, logger }) {
|
|
|
12751
12801
|
// src/books.js
|
|
12752
12802
|
import { spawn as spawn4 } from "node:child_process";
|
|
12753
12803
|
import { createHash as createHash4, randomUUID } from "node:crypto";
|
|
12754
|
-
import { mkdir as
|
|
12804
|
+
import { mkdir as mkdir7, readdir as readdir5, rename as rename4, rm as rm6, stat as stat7 } from "node:fs/promises";
|
|
12755
12805
|
import { extname as extname6, join as join12 } from "node:path";
|
|
12756
12806
|
|
|
12757
12807
|
// src/formats.js
|
|
@@ -12779,7 +12829,6 @@ var MAX_ENTRIES = 2e3;
|
|
|
12779
12829
|
var CONVERT_TIMEOUT_MS = 10 * 6e4;
|
|
12780
12830
|
var CONCURRENCY = 2;
|
|
12781
12831
|
var ENTRY = /^[0-9a-f-]{36}$/;
|
|
12782
|
-
var booksError = (code, message) => Object.assign(new Error(message), { code });
|
|
12783
12832
|
var fileKey = (source, id, format) => createHash4("sha256").update(`${source}
|
|
12784
12833
|
${id}
|
|
12785
12834
|
${format}`).digest("hex").slice(0, 24);
|
|
@@ -12787,9 +12836,6 @@ function attachment(name2) {
|
|
|
12787
12836
|
const fallback = name2.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_") || "book";
|
|
12788
12837
|
return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(name2)}`;
|
|
12789
12838
|
}
|
|
12790
|
-
function sha256Of2(path) {
|
|
12791
|
-
return readFile7(path).then((body2) => createHash4("sha256").update(body2).digest("hex"));
|
|
12792
|
-
}
|
|
12793
12839
|
function runConverter(command, input, output) {
|
|
12794
12840
|
return new Promise((resolve8, reject) => {
|
|
12795
12841
|
const child = spawn4(command, [input, output], { stdio: ["ignore", "ignore", "pipe"], detached: true });
|
|
@@ -12810,27 +12856,22 @@ function runConverter(command, input, output) {
|
|
|
12810
12856
|
child.on("close", (code) => {
|
|
12811
12857
|
clearTimeout(timer);
|
|
12812
12858
|
if (code === 0) resolve8();
|
|
12813
|
-
else reject(
|
|
12859
|
+
else reject(codedError("convert_failed", `conversion failed: ${stderr.trim().split("\n").pop() || `exit ${code}`}`));
|
|
12814
12860
|
});
|
|
12815
12861
|
});
|
|
12816
12862
|
}
|
|
12817
12863
|
function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, changed = () => {
|
|
12818
12864
|
}, now = Date.now }) {
|
|
12819
12865
|
let state = { files: {}, shelves: {} };
|
|
12820
|
-
|
|
12866
|
+
const stateFile = join12(dir, STATE_FILE);
|
|
12867
|
+
const saver = createJsonSaver(stateFile, logger);
|
|
12821
12868
|
const running = /* @__PURE__ */ new Map();
|
|
12822
12869
|
const waiting = [];
|
|
12823
12870
|
let active = 0;
|
|
12824
12871
|
let disposed = false;
|
|
12825
12872
|
const save = () => {
|
|
12826
12873
|
changed();
|
|
12827
|
-
|
|
12828
|
-
await mkdir6(dir, { recursive: true });
|
|
12829
|
-
const temporary = join12(dir, `.${STATE_FILE}.${process.pid}.tmp`);
|
|
12830
|
-
await writeFile4(temporary, JSON.stringify(state));
|
|
12831
|
-
await rename4(temporary, join12(dir, STATE_FILE));
|
|
12832
|
-
}).catch((error) => logger.warn("books: could not save the shelves: %s", error.message));
|
|
12833
|
-
return saving;
|
|
12874
|
+
return saver.save(state);
|
|
12834
12875
|
};
|
|
12835
12876
|
const shelf = (person) => state.shelves[person] ??= [];
|
|
12836
12877
|
const holders = (key) => Object.values(state.shelves).some((entries) => entries.some((entry) => entry.file === key));
|
|
@@ -12872,7 +12913,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12872
12913
|
const native = (work.formats ?? []).some((entry) => entry.format === format) || (work.formats ?? []).length === 0;
|
|
12873
12914
|
const scratch = join12(dir, "tmp", key);
|
|
12874
12915
|
await rm6(scratch, { recursive: true, force: true });
|
|
12875
|
-
await
|
|
12916
|
+
await mkdir7(scratch, { recursive: true });
|
|
12876
12917
|
try {
|
|
12877
12918
|
let name2;
|
|
12878
12919
|
let converted = false;
|
|
@@ -12880,7 +12921,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12880
12921
|
name2 = (await source.downloadFile({ id, format, dir: scratch, signal })).name;
|
|
12881
12922
|
} else {
|
|
12882
12923
|
const base = convertBase(work.formats);
|
|
12883
|
-
if (base === null || !await converter.available()) throw
|
|
12924
|
+
if (base === null || !await converter.available()) throw codedError("unsupported", `${work.title || id} is not offered as ${format}`);
|
|
12884
12925
|
const downloaded = (await source.downloadFile({ id, format: base, dir: scratch, signal })).name;
|
|
12885
12926
|
name2 = `${downloaded.slice(0, downloaded.length - extname6(downloaded).length)}.${format}`;
|
|
12886
12927
|
await runConverter(converter.command, join12(scratch, downloaded), join12(scratch, name2));
|
|
@@ -12889,10 +12930,10 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12889
12930
|
}
|
|
12890
12931
|
const target = join12(dir, "files", key);
|
|
12891
12932
|
await rm6(target, { recursive: true, force: true });
|
|
12892
|
-
await
|
|
12933
|
+
await mkdir7(join12(dir, "files"), { recursive: true });
|
|
12893
12934
|
await rename4(scratch, target);
|
|
12894
12935
|
const path = join12(target, name2);
|
|
12895
|
-
return { name: name2, bytes: (await stat7(path)).size, sha256: await
|
|
12936
|
+
return { name: name2, bytes: (await stat7(path)).size, sha256: await sha256Of(path), converted, title: work.title, author: work.author, cover: work.cover };
|
|
12896
12937
|
} finally {
|
|
12897
12938
|
await rm6(scratch, { recursive: true, force: true });
|
|
12898
12939
|
}
|
|
@@ -12913,7 +12954,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12913
12954
|
entry.cover ||= got.cover ?? null;
|
|
12914
12955
|
}
|
|
12915
12956
|
}
|
|
12916
|
-
return enforceCap();
|
|
12957
|
+
return enforceCap().catch((error) => logger.warn("books: could not keep the shelves under the cap: %s", error.message));
|
|
12917
12958
|
}, (error) => {
|
|
12918
12959
|
if (disposed) return;
|
|
12919
12960
|
logger.warn("books: %s:%s as %s failed: %s", request.source, request.id, request.format, error.message);
|
|
@@ -12934,12 +12975,8 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12934
12975
|
}
|
|
12935
12976
|
return {
|
|
12936
12977
|
async load() {
|
|
12937
|
-
|
|
12938
|
-
|
|
12939
|
-
if (loaded && typeof loaded.files === "object" && typeof loaded.shelves === "object") state = loaded;
|
|
12940
|
-
} catch (error) {
|
|
12941
|
-
if (error.code !== "ENOENT") logger.warn("books: could not read the shelves: %s", error.message);
|
|
12942
|
-
}
|
|
12978
|
+
const { value } = await readJson2(stateFile, { logger, valid: (loaded) => typeof loaded?.files === "object" && loaded.files !== null && typeof loaded.shelves === "object" && loaded.shelves !== null });
|
|
12979
|
+
if (value !== void 0) state = value;
|
|
12943
12980
|
for (const [key, file] of Object.entries(state.files)) {
|
|
12944
12981
|
if (file.state === "fetching") start(key, file);
|
|
12945
12982
|
else if (file.state === "ready" && !await stat7(join12(dir, "files", key, file.name ?? "")).then((info) => info.isFile(), () => false)) state.files[key] = { ...file, state: "removed", name: null };
|
|
@@ -12947,10 +12984,17 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12947
12984
|
await rm6(join12(dir, "tmp"), { recursive: true, force: true });
|
|
12948
12985
|
await this.sweep();
|
|
12949
12986
|
},
|
|
12950
|
-
/**
|
|
12987
|
+
/**
|
|
12988
|
+
* A folder under files/ that no record names and that is newer than the saved shelves is a fetch a crash cut off
|
|
12989
|
+
* before its save: deleted. An older one stays: its record was lost with a damaged shelves file, set aside to restore.
|
|
12990
|
+
*/
|
|
12951
12991
|
async sweep() {
|
|
12992
|
+
const savedAt = await stat7(stateFile).then((info) => info.mtimeMs, () => null);
|
|
12993
|
+
if (savedAt === null) return;
|
|
12952
12994
|
for (const name2 of await readdir5(join12(dir, "files")).catch(() => [])) {
|
|
12953
|
-
if (state.files[name2]
|
|
12995
|
+
if (state.files[name2] !== void 0) continue;
|
|
12996
|
+
const folder = join12(dir, "files", name2);
|
|
12997
|
+
if (await stat7(folder).then((info) => info.mtimeMs > savedAt, () => false)) await rm6(folder, { recursive: true, force: true });
|
|
12954
12998
|
}
|
|
12955
12999
|
},
|
|
12956
13000
|
async list(person) {
|
|
@@ -12968,14 +13012,14 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12968
13012
|
*/
|
|
12969
13013
|
async add(person, { source: sourceId, id, format, title = "", author = "", by = "" }) {
|
|
12970
13014
|
const source = sources.get(sourceId);
|
|
12971
|
-
if (source === void 0 || typeof source.downloadFile !== "function") throw
|
|
12972
|
-
if (typeof id !== "string" || !/^[^\s\0]{1,200}$/.test(id)) throw
|
|
12973
|
-
if (typeof format !== "string" || !/^[a-z0-9]{1,8}$/.test(format)) throw
|
|
13015
|
+
if (source === void 0 || typeof source.downloadFile !== "function") throw codedError("not_found", `no source ${sourceId}`);
|
|
13016
|
+
if (typeof id !== "string" || !/^[^\s\0]{1,200}$/.test(id)) throw codedError("invalid", "not a work id");
|
|
13017
|
+
if (typeof format !== "string" || !/^[a-z0-9]{1,8}$/.test(format)) throw codedError("invalid", "not a format");
|
|
12974
13018
|
const key = fileKey(sourceId, id, format);
|
|
12975
13019
|
const entries = shelf(person);
|
|
12976
13020
|
let entry = entries.find((one) => one.file === key);
|
|
12977
13021
|
if (entry === void 0) {
|
|
12978
|
-
if (entries.length >= MAX_ENTRIES) throw
|
|
13022
|
+
if (entries.length >= MAX_ENTRIES) throw codedError("invalid", "this shelf is full; delete some books first");
|
|
12979
13023
|
entry = { entry: randomUUID(), file: key, source: sourceId, id, format, title: String(title).slice(0, 300), author: String(author).slice(0, 200), cover: null, addedAt: new Date(now()).toISOString(), by: String(by).slice(0, 80) };
|
|
12980
13024
|
entries.push(entry);
|
|
12981
13025
|
}
|
|
@@ -12988,7 +13032,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12988
13032
|
/** Fetch an entry's file again (it failed, or was removed to save space). */
|
|
12989
13033
|
async retry(person, entryId) {
|
|
12990
13034
|
const entry = shelf(person).find((one) => one.entry === entryId);
|
|
12991
|
-
if (entry === void 0) throw
|
|
13035
|
+
if (entry === void 0) throw codedError("not_found", "not on this shelf");
|
|
12992
13036
|
if (state.files[entry.file]?.state !== "ready") start(entry.file, entry);
|
|
12993
13037
|
await save();
|
|
12994
13038
|
return describe(entry);
|
|
@@ -12996,7 +13040,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
12996
13040
|
async remove(person, entryId) {
|
|
12997
13041
|
const entries = shelf(person);
|
|
12998
13042
|
const index = entries.findIndex((one) => one.entry === entryId);
|
|
12999
|
-
if (index === -1) throw
|
|
13043
|
+
if (index === -1) throw codedError("not_found", "not on this shelf");
|
|
13000
13044
|
const [entry] = entries.splice(index, 1);
|
|
13001
13045
|
if (!holders(entry.file)) {
|
|
13002
13046
|
running.get(entry.file)?.abort();
|
|
@@ -13022,15 +13066,36 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
|
|
|
13022
13066
|
disposed = true;
|
|
13023
13067
|
waiting.length = 0;
|
|
13024
13068
|
for (const controller of running.values()) controller.abort();
|
|
13025
|
-
await
|
|
13069
|
+
await saver.settled();
|
|
13026
13070
|
}
|
|
13027
13071
|
};
|
|
13028
13072
|
}
|
|
13029
13073
|
|
|
13030
13074
|
// src/covers.js
|
|
13031
13075
|
import { createHash as createHash5 } from "node:crypto";
|
|
13032
|
-
import { mkdir as
|
|
13076
|
+
import { mkdir as mkdir8, open as open3, readdir as readdir6, rename as rename5, rm as rm7, stat as stat8, utimes } from "node:fs/promises";
|
|
13033
13077
|
import { join as join13 } from "node:path";
|
|
13078
|
+
|
|
13079
|
+
// src/limit.js
|
|
13080
|
+
function createLimiter(concurrency) {
|
|
13081
|
+
const waiting = [];
|
|
13082
|
+
let running = 0;
|
|
13083
|
+
const pump = () => {
|
|
13084
|
+
while (running < concurrency && waiting.length > 0) {
|
|
13085
|
+
running += 1;
|
|
13086
|
+
waiting.shift()().finally(() => {
|
|
13087
|
+
running -= 1;
|
|
13088
|
+
pump();
|
|
13089
|
+
});
|
|
13090
|
+
}
|
|
13091
|
+
};
|
|
13092
|
+
return (job) => new Promise((resolve8, reject) => {
|
|
13093
|
+
waiting.push(() => job().then(resolve8, reject));
|
|
13094
|
+
pump();
|
|
13095
|
+
});
|
|
13096
|
+
}
|
|
13097
|
+
|
|
13098
|
+
// src/covers.js
|
|
13034
13099
|
var KEY = /^[0-9a-f]{32}$/;
|
|
13035
13100
|
var FAILED_FOR_MS = 5 * 6e4;
|
|
13036
13101
|
var MAX_REMEMBERED = 5e3;
|
|
@@ -13062,8 +13127,6 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
|
|
|
13062
13127
|
const known2 = /* @__PURE__ */ new Map();
|
|
13063
13128
|
const inFlight = /* @__PURE__ */ new Map();
|
|
13064
13129
|
const failed = /* @__PURE__ */ new Map();
|
|
13065
|
-
const waiting = [];
|
|
13066
|
-
let running = 0;
|
|
13067
13130
|
const makers = {
|
|
13068
13131
|
async source({ sourceId, url, page }, file) {
|
|
13069
13132
|
const source = sourceOf(sourceId);
|
|
@@ -13078,19 +13141,7 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
|
|
|
13078
13141
|
if (known2.size > MAX_REMEMBERED) known2.delete(known2.keys().next().value);
|
|
13079
13142
|
return `covers/${key}`;
|
|
13080
13143
|
};
|
|
13081
|
-
const
|
|
13082
|
-
while (running < concurrency && waiting.length > 0) {
|
|
13083
|
-
running += 1;
|
|
13084
|
-
waiting.shift()().finally(() => {
|
|
13085
|
-
running -= 1;
|
|
13086
|
-
pump();
|
|
13087
|
-
});
|
|
13088
|
-
}
|
|
13089
|
-
};
|
|
13090
|
-
const queued = (job) => new Promise((resolve8, reject) => {
|
|
13091
|
-
waiting.push(() => job().then(resolve8, reject));
|
|
13092
|
-
pump();
|
|
13093
|
-
});
|
|
13144
|
+
const queued = createLimiter(concurrency);
|
|
13094
13145
|
async function trim() {
|
|
13095
13146
|
if (!(capBytes > 0)) return;
|
|
13096
13147
|
const files = [];
|
|
@@ -13107,7 +13158,7 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
|
|
|
13107
13158
|
}
|
|
13108
13159
|
}
|
|
13109
13160
|
async function make(key, entry) {
|
|
13110
|
-
await
|
|
13161
|
+
await mkdir8(dir, { recursive: true });
|
|
13111
13162
|
const partial = join13(dir, `.${key}.part`);
|
|
13112
13163
|
try {
|
|
13113
13164
|
await makers[entry.by](entry, partial);
|
|
@@ -13192,8 +13243,8 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
|
|
|
13192
13243
|
|
|
13193
13244
|
// src/hub.js
|
|
13194
13245
|
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
13195
|
-
import { mkdir as
|
|
13196
|
-
import { dirname as
|
|
13246
|
+
import { mkdir as mkdir9 } from "node:fs/promises";
|
|
13247
|
+
import { dirname as dirname6, isAbsolute as isAbsolute3, join as join14, resolve as resolve4 } from "node:path";
|
|
13197
13248
|
|
|
13198
13249
|
// src/sync.js
|
|
13199
13250
|
var DRIFT = Object.freeze({
|
|
@@ -13416,7 +13467,6 @@ var MAX_NAME = 40;
|
|
|
13416
13467
|
var localItem = (episode) => ({ title: episode.title, kind: "file", status: "preparing", sourcePath: episode.path, sourceSubtitles: episode.subtitles });
|
|
13417
13468
|
var slotItem = (entry, status) => ({ title: entry.title, kind: "file", slot: entry.n, status: entry.path === null ? status : "preparing", sourcePath: entry.path, sourceSubtitles: entry.subtitles ?? [] });
|
|
13418
13469
|
var itemKey = (item) => item.slot ?? item.sourcePath;
|
|
13419
|
-
var serviceError = (code, message) => Object.assign(new Error(message), { code });
|
|
13420
13470
|
var isTogether = (room) => room.together !== false;
|
|
13421
13471
|
var cleanText = (value, max) => typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, max) : "";
|
|
13422
13472
|
function createRoomService(options) {
|
|
@@ -13461,15 +13511,10 @@ function createRoomService(options) {
|
|
|
13461
13511
|
const sweepTimer = setInterval(() => sweep(), SWEEP_MS);
|
|
13462
13512
|
const progressTimer = setInterval(() => progress(), PROGRESS_MS);
|
|
13463
13513
|
async function load() {
|
|
13464
|
-
await
|
|
13465
|
-
for (const root of libraryRoots) await
|
|
13514
|
+
await mkdir9(stateDir, { recursive: true });
|
|
13515
|
+
for (const root of libraryRoots) await mkdir9(root, { recursive: true }).catch(() => {
|
|
13466
13516
|
});
|
|
13467
|
-
|
|
13468
|
-
try {
|
|
13469
|
-
data = JSON.parse(await readFile8(file, "utf8"));
|
|
13470
|
-
} catch (error) {
|
|
13471
|
-
if (error.code !== "ENOENT") logger.warn("could not read %s: %s", file, error.message);
|
|
13472
|
-
}
|
|
13517
|
+
const data = (await readJson2(file, { logger })).value ?? {};
|
|
13473
13518
|
for (const { holds, ...room } of data.rooms ?? []) rooms.set(room.id, { ...hold({ gate: null, gates: 0, startedAt: null, ...room }, now()), cooldown: {}, nextReady: null, emptySince: room.emptySince ?? (room.opened ? now() : null) });
|
|
13474
13519
|
sweep();
|
|
13475
13520
|
for (const room of [...rooms.values()]) await reopen(room);
|
|
@@ -13483,9 +13528,7 @@ function createRoomService(options) {
|
|
|
13483
13528
|
}, SAVE_DELAY_MS);
|
|
13484
13529
|
}
|
|
13485
13530
|
async function flush() {
|
|
13486
|
-
|
|
13487
|
-
await writeFile5(`${file}.part`, body2);
|
|
13488
|
-
await rename6(`${file}.part`, file);
|
|
13531
|
+
await writeJson(file, { rooms: [...rooms.values()] });
|
|
13489
13532
|
}
|
|
13490
13533
|
function commit(room) {
|
|
13491
13534
|
rooms.set(room.id, { ...room, touchedAt: now() });
|
|
@@ -13623,7 +13666,12 @@ function createRoomService(options) {
|
|
|
13623
13666
|
} catch {
|
|
13624
13667
|
return send(peer, { t: "error", message: "not JSON" });
|
|
13625
13668
|
}
|
|
13626
|
-
|
|
13669
|
+
if (typeof message !== "object" || message === null) return send(peer, { t: "error", message: "not an object" });
|
|
13670
|
+
try {
|
|
13671
|
+
handle(peer, roomId, message);
|
|
13672
|
+
} catch (error) {
|
|
13673
|
+
logger.warn("room %s: a message failed: %s", roomId, error.message);
|
|
13674
|
+
}
|
|
13627
13675
|
});
|
|
13628
13676
|
ws.on("close", () => {
|
|
13629
13677
|
clearInterval(ping);
|
|
@@ -13707,7 +13755,7 @@ function createRoomService(options) {
|
|
|
13707
13755
|
return { ...room, items: room.items.map((entry, n) => n === room.index ? { ...entry, status: "preparing", error: null } : entry) };
|
|
13708
13756
|
}
|
|
13709
13757
|
async function reopen(room) {
|
|
13710
|
-
const unfinished = async (item) => item.status === "ready" && item.kind === "hls" && typeof item.file === "string" && item.file.startsWith(`${cacheDir}/`) && await finishedPlaylist(
|
|
13758
|
+
const unfinished = async (item) => item.status === "ready" && item.kind === "hls" && typeof item.file === "string" && item.file.startsWith(`${cacheDir}/`) && await finishedPlaylist(dirname6(item.file)) === null;
|
|
13711
13759
|
const items = [];
|
|
13712
13760
|
for (const item of room.items) {
|
|
13713
13761
|
if (!await unfinished(item)) items.push(item);
|
|
@@ -13765,10 +13813,10 @@ function createRoomService(options) {
|
|
|
13765
13813
|
});
|
|
13766
13814
|
}
|
|
13767
13815
|
async function localItems(path, fromPanel) {
|
|
13768
|
-
if (typeof path !== "string" || !isAbsolute3(path)) throw
|
|
13816
|
+
if (typeof path !== "string" || !isAbsolute3(path)) throw codedError("invalid", "path must be an absolute path");
|
|
13769
13817
|
const target = resolve4(path);
|
|
13770
13818
|
if (fromPanel && !libraryRoots.some((root) => target === root || target.startsWith(`${root}/`))) {
|
|
13771
|
-
throw
|
|
13819
|
+
throw codedError("outside", "the panel can only open files from the library folders");
|
|
13772
13820
|
}
|
|
13773
13821
|
const entries = await options.directory?.(target);
|
|
13774
13822
|
if (entries) return entries.map((entry) => slotItem(entry, "remote"));
|
|
@@ -13776,7 +13824,7 @@ function createRoomService(options) {
|
|
|
13776
13824
|
try {
|
|
13777
13825
|
episodes = await scanSource(target);
|
|
13778
13826
|
} catch (error) {
|
|
13779
|
-
if (error.code === "ENOENT") throw
|
|
13827
|
+
if (error.code === "ENOENT") throw codedError("not_found", `${path} does not exist`);
|
|
13780
13828
|
throw error;
|
|
13781
13829
|
}
|
|
13782
13830
|
return episodes.map(localItem);
|
|
@@ -13813,7 +13861,7 @@ function createRoomService(options) {
|
|
|
13813
13861
|
* @param {{ path: string, title?: string, by?: string, fromPanel?: boolean, together?: boolean, start?: { index: number, position: number } | null }} input - `together`: open to others from the start; else one person watches until they share it
|
|
13814
13862
|
*/
|
|
13815
13863
|
async createRoom(input) {
|
|
13816
|
-
if (!delivery.available) throw
|
|
13864
|
+
if (!delivery.available) throw codedError("unsupported", delivery.reason);
|
|
13817
13865
|
const items = await localItems(input.path, input.fromPanel === true);
|
|
13818
13866
|
const id = randomBytes2(9).toString("base64url");
|
|
13819
13867
|
const title = cleanText(input.title, 120) || (items.length === 1 ? items[0].title : input.path.split("/").filter(Boolean).pop());
|
|
@@ -13855,12 +13903,12 @@ function createRoomService(options) {
|
|
|
13855
13903
|
/** Open a room someone watches alone to others, as it is: same episode, same position. */
|
|
13856
13904
|
watchTogether(id) {
|
|
13857
13905
|
const room = rooms.get(id);
|
|
13858
|
-
if (room === void 0) throw
|
|
13906
|
+
if (room === void 0) throw codedError("not_found", "no such room");
|
|
13859
13907
|
if (!isTogether(room)) commit({ ...room, together: true });
|
|
13860
13908
|
return { room: summary(rooms.get(id)) };
|
|
13861
13909
|
},
|
|
13862
13910
|
closeRoom(id) {
|
|
13863
|
-
if (!close(id)) throw
|
|
13911
|
+
if (!close(id)) throw codedError("not_found", "no such room");
|
|
13864
13912
|
return { closed: id };
|
|
13865
13913
|
},
|
|
13866
13914
|
sweep,
|
|
@@ -13941,7 +13989,7 @@ function createRoomService(options) {
|
|
|
13941
13989
|
}
|
|
13942
13990
|
|
|
13943
13991
|
// src/watchlog.js
|
|
13944
|
-
import { appendFile, readFile as
|
|
13992
|
+
import { appendFile, readFile as readFile7 } from "node:fs/promises";
|
|
13945
13993
|
var LOG_NAME = "watch-log.jsonl";
|
|
13946
13994
|
var isWatching = (type) => /^(?:room|viewer|episode)\./.test(type) || type === "position";
|
|
13947
13995
|
function isNearEnd(position, duration) {
|
|
@@ -13960,7 +14008,7 @@ function createWatchLog({ file, now = Date.now, logger }) {
|
|
|
13960
14008
|
await tail;
|
|
13961
14009
|
let text3 = "";
|
|
13962
14010
|
try {
|
|
13963
|
-
text3 = await
|
|
14011
|
+
text3 = await readFile7(file, "utf8");
|
|
13964
14012
|
} catch (error) {
|
|
13965
14013
|
if (error.code !== "ENOENT") throw error;
|
|
13966
14014
|
}
|
|
@@ -14070,8 +14118,8 @@ function createJournal({ log, library, now = Date.now }) {
|
|
|
14070
14118
|
}
|
|
14071
14119
|
|
|
14072
14120
|
// src/shows.js
|
|
14073
|
-
import { mkdir as
|
|
14074
|
-
import { basename as basename5, dirname as
|
|
14121
|
+
import { mkdir as mkdir10, readFile as readFile8, readdir as readdir7, rename as rename6, rm as rm8, stat as stat9, statfs, writeFile as writeFile4 } from "node:fs/promises";
|
|
14122
|
+
import { basename as basename5, dirname as dirname7, extname as extname7, join as join15, resolve as resolve5 } from "node:path";
|
|
14075
14123
|
|
|
14076
14124
|
// src/presence.js
|
|
14077
14125
|
var RATINGS = Object.freeze(["loved", "fine", "not-for-me", "unfinished"]);
|
|
@@ -14085,7 +14133,6 @@ var MAX_PROMPT_CHARS = 2e3;
|
|
|
14085
14133
|
var PICKS_LIMIT = 8;
|
|
14086
14134
|
var PICKS_TIMEOUT_MS = 6e4;
|
|
14087
14135
|
var MAX_WHY_CHARS = 280;
|
|
14088
|
-
var badInput = (message) => Object.assign(new Error(message), { code: "invalid_arguments" });
|
|
14089
14136
|
function pendingRatings({ shows, events, person, now, days = RATE_WITHIN_DAYS, limit = MAX_PENDING }) {
|
|
14090
14137
|
const since = now - days * 864e5;
|
|
14091
14138
|
const rated = new Set(events.filter((event) => event.type === "rating" && event.person === person).map((event) => event.show));
|
|
@@ -14101,8 +14148,8 @@ function pendingRatings({ shows, events, person, now, days = RATE_WITHIN_DAYS, l
|
|
|
14101
14148
|
return [...asks.values()].filter((ask) => ask.why === "finished" || !present.has(ask.show)).sort((a, b) => b.at - a.at).slice(0, limit);
|
|
14102
14149
|
}
|
|
14103
14150
|
function ratingLine({ show, title, rating }, person) {
|
|
14104
|
-
if (!RATINGS.includes(rating)) throw
|
|
14105
|
-
if (typeof show !== "string" || show === "") throw
|
|
14151
|
+
if (!RATINGS.includes(rating)) throw codedError("invalid_arguments", `rating must be one of ${RATINGS.join(", ")}`);
|
|
14152
|
+
if (typeof show !== "string" || show === "") throw codedError("invalid_arguments", "rating needs the show");
|
|
14106
14153
|
return { show, title: typeof title === "string" ? title.slice(0, 200) : "", rating, person: person.key, by: person.name };
|
|
14107
14154
|
}
|
|
14108
14155
|
var textOrPerLanguage = (value, max) => {
|
|
@@ -14117,22 +14164,22 @@ function parseAnnotation({ recap, steps } = {}) {
|
|
|
14117
14164
|
const out = {};
|
|
14118
14165
|
if (recap === null) out.recap = null;
|
|
14119
14166
|
else if (recap !== void 0) {
|
|
14120
|
-
if (typeof recap?.text !== "string" || recap.text.trim() === "") throw
|
|
14121
|
-
if (!Number.isInteger(recap.upTo) || recap.upTo < 1) throw
|
|
14167
|
+
if (typeof recap?.text !== "string" || recap.text.trim() === "") throw codedError("invalid_arguments", "recap needs text");
|
|
14168
|
+
if (!Number.isInteger(recap.upTo) || recap.upTo < 1) throw codedError("invalid_arguments", "recap needs upTo, the last episode it covers (1 or more)");
|
|
14122
14169
|
out.recap = { text: recap.text.trim().slice(0, MAX_RECAP_CHARS), upTo: recap.upTo };
|
|
14123
14170
|
}
|
|
14124
14171
|
if (steps === null) out.steps = null;
|
|
14125
14172
|
else if (steps !== void 0) {
|
|
14126
|
-
if (!Array.isArray(steps) || steps.length > MAX_STEPS) throw
|
|
14173
|
+
if (!Array.isArray(steps) || steps.length > MAX_STEPS) throw codedError("invalid_arguments", `steps is a list of at most ${MAX_STEPS}`);
|
|
14127
14174
|
out.steps = steps.map((step, n) => {
|
|
14128
14175
|
const id = step?.id ?? `step-${n + 1}`;
|
|
14129
|
-
if (typeof id !== "string" || !STEP_ID.test(id)) throw
|
|
14176
|
+
if (typeof id !== "string" || !STEP_ID.test(id)) throw codedError("invalid_arguments", "a step id is lowercase letters, digits, - and _");
|
|
14130
14177
|
const label = textOrPerLanguage(step?.label, MAX_LABEL_CHARS);
|
|
14131
|
-
if (label === null) throw
|
|
14178
|
+
if (label === null) throw codedError("invalid_arguments", "a step needs a label that says the step");
|
|
14132
14179
|
const prompt = textOrPerLanguage(step?.prompt, MAX_PROMPT_CHARS);
|
|
14133
14180
|
return { kind: "step", id, label, ...prompt === null ? {} : { payload: { prompt } } };
|
|
14134
14181
|
});
|
|
14135
|
-
if (new Set(out.steps.map((step) => step.id)).size !== out.steps.length) throw
|
|
14182
|
+
if (new Set(out.steps.map((step) => step.id)).size !== out.steps.length) throw codedError("invalid_arguments", "step ids repeat");
|
|
14136
14183
|
if (out.steps.length === 0) out.steps = null;
|
|
14137
14184
|
}
|
|
14138
14185
|
return out;
|
|
@@ -14142,9 +14189,9 @@ function parsePicks(document2, hasSource, limit = PICKS_LIMIT) {
|
|
|
14142
14189
|
if (!Array.isArray(document2?.picks)) throw new Error("the recommender answered without a picks list");
|
|
14143
14190
|
const out = [];
|
|
14144
14191
|
const seen = /* @__PURE__ */ new Set();
|
|
14145
|
-
for (const
|
|
14146
|
-
const raw =
|
|
14147
|
-
const why = typeof
|
|
14192
|
+
for (const pick4 of document2.picks) {
|
|
14193
|
+
const raw = pick4?.work;
|
|
14194
|
+
const why = typeof pick4?.why === "string" ? pick4.why.trim().slice(0, MAX_WHY_CHARS) : "";
|
|
14148
14195
|
if (typeof raw?.source !== "string" || !hasSource(raw.source) || why === "") continue;
|
|
14149
14196
|
const work = resultOf(raw, null);
|
|
14150
14197
|
if (work === null || work.title === "") continue;
|
|
@@ -14169,10 +14216,9 @@ var STOP_DIFF_S = 30;
|
|
|
14169
14216
|
var REFINISH_MS = 36e5;
|
|
14170
14217
|
var MAX_NAME2 = 120;
|
|
14171
14218
|
var SUMS = "SHA256SUMS.txt";
|
|
14172
|
-
var libraryError = (code, message) => Object.assign(new Error(message), { code });
|
|
14173
14219
|
function cleanName(value) {
|
|
14174
14220
|
const name2 = String(value ?? "").replace(/[\u0000-\u001f\u007f/\\]/g, "").trim().slice(0, MAX_NAME2);
|
|
14175
|
-
if (name2 === "" || name2.startsWith(".")) throw
|
|
14221
|
+
if (name2 === "" || name2.startsWith(".")) throw codedError("invalid", "give a name");
|
|
14176
14222
|
return name2;
|
|
14177
14223
|
}
|
|
14178
14224
|
function groupSeasons(shows) {
|
|
@@ -14201,26 +14247,17 @@ function createLibrary(options) {
|
|
|
14201
14247
|
const metaFile = join15(stateDir, "shows.json");
|
|
14202
14248
|
const cacheDir = join15(stateDir, "cache");
|
|
14203
14249
|
let meta = {};
|
|
14204
|
-
|
|
14250
|
+
const saver = createJsonSaver(metaFile, logger);
|
|
14205
14251
|
const listeners = /* @__PURE__ */ new Set();
|
|
14206
14252
|
const changed = (show) => {
|
|
14207
14253
|
for (const listener of listeners) listener(show);
|
|
14208
14254
|
};
|
|
14209
14255
|
async function load() {
|
|
14210
|
-
|
|
14211
|
-
meta = JSON.parse(await readFile10(metaFile, "utf8")).shows ?? {};
|
|
14212
|
-
} catch (error) {
|
|
14213
|
-
if (error.code !== "ENOENT") logger.warn("could not read %s: %s", metaFile, error.message);
|
|
14214
|
-
}
|
|
14256
|
+
meta = (await readJson2(metaFile, { logger })).value?.shows ?? {};
|
|
14215
14257
|
}
|
|
14216
14258
|
function save() {
|
|
14217
14259
|
options.changed?.();
|
|
14218
|
-
|
|
14219
|
-
saving = saving.then(async () => {
|
|
14220
|
-
await writeFile6(`${metaFile}.part`, body2);
|
|
14221
|
-
await rename7(`${metaFile}.part`, metaFile);
|
|
14222
|
-
}).catch((error) => logger.warn("could not save %s: %s", metaFile, error.message));
|
|
14223
|
-
return saving;
|
|
14260
|
+
return saver.save({ shows: meta });
|
|
14224
14261
|
}
|
|
14225
14262
|
const record = (path) => meta[path] ?? {};
|
|
14226
14263
|
function update(path, patch) {
|
|
@@ -14230,16 +14267,17 @@ function createLibrary(options) {
|
|
|
14230
14267
|
function showPath(path) {
|
|
14231
14268
|
if (typeof path !== "string") return null;
|
|
14232
14269
|
const target = resolve5(path);
|
|
14233
|
-
return roots.includes(
|
|
14270
|
+
return roots.includes(dirname7(target)) && !basename5(target).startsWith(".") ? target : null;
|
|
14234
14271
|
}
|
|
14272
|
+
const sourcedPaths = () => Object.keys(meta).filter((path) => isSourced(meta[path]) && showPath(path) === path);
|
|
14235
14273
|
function requireShow(path) {
|
|
14236
14274
|
const target = showPath(path);
|
|
14237
|
-
if (target === null) throw
|
|
14275
|
+
if (target === null) throw codedError("not_found", "not a show in the library");
|
|
14238
14276
|
return target;
|
|
14239
14277
|
}
|
|
14240
14278
|
function showOf(episodePath) {
|
|
14241
14279
|
if (typeof episodePath !== "string") return null;
|
|
14242
|
-
return showPath(episodePath) ?? showPath(
|
|
14280
|
+
return showPath(episodePath) ?? showPath(dirname7(episodePath));
|
|
14243
14281
|
}
|
|
14244
14282
|
async function episodeFiles(path) {
|
|
14245
14283
|
const info = await stat9(path).catch(() => null);
|
|
@@ -14270,13 +14308,14 @@ function createLibrary(options) {
|
|
|
14270
14308
|
}
|
|
14271
14309
|
async function forgetSum(show, file) {
|
|
14272
14310
|
const sums = join15(show, SUMS);
|
|
14273
|
-
const text3 = await
|
|
14274
|
-
if (text3 !== null) await
|
|
14311
|
+
const text3 = await readFile8(sums, "utf8").catch(() => null);
|
|
14312
|
+
if (text3 !== null) await writeFile4(sums, text3.split("\n").filter((line) => !line.endsWith(` ${file}`) && !line.endsWith(` *${file}`)).join("\n"));
|
|
14275
14313
|
}
|
|
14276
14314
|
const note = (type, path, fields = {}) => options.record?.(type, { show: path, title: basename5(path), ...fields });
|
|
14315
|
+
const autoDeletes = (path) => options.autoDeleteDays > 0 && dirname7(path) === roots[0];
|
|
14277
14316
|
function deletesAt(path) {
|
|
14278
14317
|
const { countdownFrom, keep } = record(path);
|
|
14279
|
-
if (!countdownFrom || keep || !(
|
|
14318
|
+
if (!countdownFrom || keep || !autoDeletes(path)) return null;
|
|
14280
14319
|
return countdownFrom + options.autoDeleteDays * DAY_MS;
|
|
14281
14320
|
}
|
|
14282
14321
|
function watchOf(episodePath) {
|
|
@@ -14356,6 +14395,7 @@ function createLibrary(options) {
|
|
|
14356
14395
|
newSeason: entry.newSeason ?? null,
|
|
14357
14396
|
newEpisodes: entry.newEpisodes ?? null,
|
|
14358
14397
|
group: entry.group ?? null,
|
|
14398
|
+
autoDeletes: autoDeletes(path),
|
|
14359
14399
|
deletesAt: deletesAt(path),
|
|
14360
14400
|
resume: resume2,
|
|
14361
14401
|
finished,
|
|
@@ -14372,7 +14412,7 @@ function createLibrary(options) {
|
|
|
14372
14412
|
return {
|
|
14373
14413
|
load,
|
|
14374
14414
|
/** Resolves once the notes written so far are on disk. */
|
|
14375
|
-
flush: () =>
|
|
14415
|
+
flush: () => saver.settled(),
|
|
14376
14416
|
showPath,
|
|
14377
14417
|
showOf,
|
|
14378
14418
|
resumeFrom: async (path) => resumeFrom(path, slotsOf(record(path), await episodeFiles(path) ?? [])),
|
|
@@ -14429,7 +14469,7 @@ function createLibrary(options) {
|
|
|
14429
14469
|
},
|
|
14430
14470
|
/** Paths of the shows that came from a source. */
|
|
14431
14471
|
async sourcedShows() {
|
|
14432
|
-
return
|
|
14472
|
+
return sourcedPaths();
|
|
14433
14473
|
},
|
|
14434
14474
|
/** Forget that these episodes were deleted by hand. */
|
|
14435
14475
|
async unskip(path, numbers) {
|
|
@@ -14459,9 +14499,9 @@ function createLibrary(options) {
|
|
|
14459
14499
|
/** Every cached episode of the shows the cap counts (sourced, not pinned), with its bytes (the prepared copy included) and when it was last watched or fetched. */
|
|
14460
14500
|
async cacheEntries() {
|
|
14461
14501
|
const out = [];
|
|
14462
|
-
for (const path of
|
|
14502
|
+
for (const path of sourcedPaths()) {
|
|
14463
14503
|
const entry = meta[path];
|
|
14464
|
-
if (
|
|
14504
|
+
if (entry.pinned === true) continue;
|
|
14465
14505
|
for (const file of await episodeFiles(path) ?? []) {
|
|
14466
14506
|
const n = episodeNumber(file.name);
|
|
14467
14507
|
if (n === null) continue;
|
|
@@ -14487,7 +14527,7 @@ function createLibrary(options) {
|
|
|
14487
14527
|
/** Keep a show's every episode on disk (or go back to the rolling cache). */
|
|
14488
14528
|
async pin(path, pinned, { by = null } = {}) {
|
|
14489
14529
|
const target = requireShow(path);
|
|
14490
|
-
if (!isSourced(record(target))) throw
|
|
14530
|
+
if (!isSourced(record(target))) throw codedError("invalid", "only a show from a source can be kept offline");
|
|
14491
14531
|
update(target, { pinned });
|
|
14492
14532
|
note(pinned ? "library.pinned" : "library.unpinned", target, { by });
|
|
14493
14533
|
return { path: target, pinned };
|
|
@@ -14526,7 +14566,7 @@ function createLibrary(options) {
|
|
|
14526
14566
|
setQuality(path, quality) {
|
|
14527
14567
|
const target = requireShow(path);
|
|
14528
14568
|
const entry = record(target);
|
|
14529
|
-
if (!isSourced(entry)) throw
|
|
14569
|
+
if (!isSourced(entry)) throw codedError("invalid", "this show has no source to fetch from");
|
|
14530
14570
|
update(target, { source: { ...entry.source, quality } });
|
|
14531
14571
|
},
|
|
14532
14572
|
/** The saved (offline fallback) copy of a show's work, or null. */
|
|
@@ -14542,12 +14582,12 @@ function createLibrary(options) {
|
|
|
14542
14582
|
},
|
|
14543
14583
|
/** Note a show coming from a source, before its files arrive. */
|
|
14544
14584
|
async adopt(path, source, { pinned = false } = {}) {
|
|
14545
|
-
await
|
|
14585
|
+
await mkdir10(path, { recursive: true });
|
|
14546
14586
|
update(path, { source, addedAt: record(path).addedAt ?? now(), ...pinned ? { pinned: true } : {} });
|
|
14547
14587
|
},
|
|
14548
14588
|
async remove(path, { by = null, reason = "by hand" } = {}) {
|
|
14549
14589
|
const target = requireShow(path);
|
|
14550
|
-
if (inUse(target)) throw
|
|
14590
|
+
if (inUse(target)) throw codedError("in_use", "a room is playing this show; close the room first");
|
|
14551
14591
|
await forget(target);
|
|
14552
14592
|
await rm8(target, { recursive: true, force: true });
|
|
14553
14593
|
delete meta[target];
|
|
@@ -14558,9 +14598,9 @@ function createLibrary(options) {
|
|
|
14558
14598
|
async removeEpisode(path, name2, { by = null } = {}) {
|
|
14559
14599
|
const target = requireShow(path);
|
|
14560
14600
|
if ((await stat9(target)).isFile()) return this.remove(target, { by });
|
|
14561
|
-
if (inUse(target)) throw
|
|
14601
|
+
if (inUse(target)) throw codedError("in_use", "a room is playing this show; close the room first");
|
|
14562
14602
|
const file = cleanName(name2);
|
|
14563
|
-
if (!isMedia(file)) throw
|
|
14603
|
+
if (!isMedia(file)) throw codedError("invalid", "not an episode");
|
|
14564
14604
|
await deleteEpisode(target, file);
|
|
14565
14605
|
note("library.episodeDeleted", target, { episode: titleOf(file), by });
|
|
14566
14606
|
const entry = record(target);
|
|
@@ -14571,14 +14611,14 @@ function createLibrary(options) {
|
|
|
14571
14611
|
},
|
|
14572
14612
|
async rename(path, name2, { by = null } = {}) {
|
|
14573
14613
|
const target = requireShow(path);
|
|
14574
|
-
if (inUse(target)) throw
|
|
14575
|
-
if (download(target)?.active) throw
|
|
14614
|
+
if (inUse(target)) throw codedError("in_use", "a room is playing this show; close the room first");
|
|
14615
|
+
if (download(target)?.active) throw codedError("in_use", "this show is still downloading");
|
|
14576
14616
|
const isFile = (await stat9(target)).isFile();
|
|
14577
14617
|
const clean = cleanName(name2);
|
|
14578
|
-
const next = join15(
|
|
14618
|
+
const next = join15(dirname7(target), isFile && extname7(clean) === "" ? `${clean}${extname7(target)}` : clean);
|
|
14579
14619
|
if (next === target) return { path: target };
|
|
14580
|
-
if (await stat9(next).then(() => true, () => false)) throw
|
|
14581
|
-
await
|
|
14620
|
+
if (await stat9(next).then(() => true, () => false)) throw codedError("exists", "a show with that name is already in the library");
|
|
14621
|
+
await rename6(target, next);
|
|
14582
14622
|
if (meta[target] !== void 0) {
|
|
14583
14623
|
meta[next] = meta[target];
|
|
14584
14624
|
delete meta[target];
|
|
@@ -14597,7 +14637,8 @@ function createLibrary(options) {
|
|
|
14597
14637
|
/** Start the countdown now (or restart it): deleted `autoDeleteDays` from now unless kept. */
|
|
14598
14638
|
async countdown(path, { by = null } = {}) {
|
|
14599
14639
|
const target = requireShow(path);
|
|
14600
|
-
if (!(options.autoDeleteDays > 0)) throw
|
|
14640
|
+
if (!(options.autoDeleteDays > 0)) throw codedError("invalid", "automatic deleting is off");
|
|
14641
|
+
if (!autoDeletes(target)) throw codedError("invalid", "shows outside the hub's own library are never deleted on their own");
|
|
14601
14642
|
const restart = deletesAt(target) !== null;
|
|
14602
14643
|
update(target, { keep: false, countdownFrom: now() });
|
|
14603
14644
|
note(restart ? "library.countdownRestarted" : "library.countdownStarted", target, { by, deletesAt: new Date(deletesAt(target)).toISOString() });
|
|
@@ -14626,15 +14667,16 @@ function createLibrary(options) {
|
|
|
14626
14667
|
const entry = record(show);
|
|
14627
14668
|
const finished = new Set(entry.finished ?? []);
|
|
14628
14669
|
finished.add(basename5(episodePath));
|
|
14629
|
-
const
|
|
14630
|
-
const
|
|
14670
|
+
const files = await episodeFiles(show) ?? [];
|
|
14671
|
+
const names = files.map((file) => file.name);
|
|
14672
|
+
const keys = slotsOf(entry, files).map((slot) => slot.key);
|
|
14631
14673
|
const done = new Set([...finished].map((name2) => keyOf(entry, name2)));
|
|
14632
14674
|
const complete = isSourced(entry) || names.length >= (entry.source?.episodes ?? names.length);
|
|
14633
14675
|
const lastDone = complete && keys.length > 0 && done.has(keys[keys.length - 1]);
|
|
14634
14676
|
const allDone = complete && keys.every((key) => done.has(key));
|
|
14635
14677
|
const newFinish = (lastDone || allDone) && (!entry.watchedAt || now() - entry.watchedAt > REFINISH_MS);
|
|
14636
14678
|
update(show, { finished: [...finished], ...newFinish ? { watchedAt: now(), countdownFrom: now() } : {} });
|
|
14637
|
-
if (newFinish && !entry.keep &&
|
|
14679
|
+
if (newFinish && !entry.keep && autoDeletes(show)) note("library.countdownStarted", show, { by: null, reason: "watched to the end", deletesAt: new Date(deletesAt(show)).toISOString() });
|
|
14638
14680
|
changed(show);
|
|
14639
14681
|
},
|
|
14640
14682
|
/** Delete watched shows whose time has come, unless kept, open in a room or downloading. */
|
|
@@ -14655,7 +14697,7 @@ function createLibrary(options) {
|
|
|
14655
14697
|
}
|
|
14656
14698
|
|
|
14657
14699
|
// src/remarks.js
|
|
14658
|
-
import {
|
|
14700
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
14659
14701
|
import { join as join16 } from "node:path";
|
|
14660
14702
|
var HOUR_MS = 36e5;
|
|
14661
14703
|
var DAY_MS2 = 24 * HOUR_MS;
|
|
@@ -14664,16 +14706,14 @@ function createRemarks({ source, logger, now = Date.now, danmakuMaxAgeMs = DAY_M
|
|
|
14664
14706
|
const flying = /* @__PURE__ */ new Map();
|
|
14665
14707
|
async function read(file) {
|
|
14666
14708
|
try {
|
|
14667
|
-
const copy = JSON.parse(await
|
|
14709
|
+
const copy = JSON.parse(await readFile9(file, "utf8"));
|
|
14668
14710
|
return Number.isFinite(copy?.at) ? copy : null;
|
|
14669
14711
|
} catch {
|
|
14670
14712
|
return null;
|
|
14671
14713
|
}
|
|
14672
14714
|
}
|
|
14673
14715
|
async function keep(file, value) {
|
|
14674
|
-
await
|
|
14675
|
-
await writeFile7(`${file}.part`, JSON.stringify(value));
|
|
14676
|
-
await rename8(`${file}.part`, file);
|
|
14716
|
+
await writeJson(file, value);
|
|
14677
14717
|
}
|
|
14678
14718
|
function fetchInto(file, ask) {
|
|
14679
14719
|
if (!flying.has(file)) {
|
|
@@ -14906,45 +14946,26 @@ function createChanges({ intervalMs = 300 } = {}) {
|
|
|
14906
14946
|
}
|
|
14907
14947
|
|
|
14908
14948
|
// src/copies.js
|
|
14909
|
-
import { mkdir as mkdir11, readFile as readFile12, rename as rename9, writeFile as writeFile8 } from "node:fs/promises";
|
|
14910
|
-
import { dirname as dirname7 } from "node:path";
|
|
14911
14949
|
var DAY_MS4 = 864e5;
|
|
14912
14950
|
var HOUR_MS2 = 36e5;
|
|
14913
14951
|
function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOUR_MS2, parallel = 4, now = Date.now }) {
|
|
14914
14952
|
const copies = /* @__PURE__ */ new Map();
|
|
14915
14953
|
const flying = /* @__PURE__ */ new Map();
|
|
14916
14954
|
const failedAt = /* @__PURE__ */ new Map();
|
|
14917
|
-
const
|
|
14918
|
-
|
|
14919
|
-
|
|
14920
|
-
const loaded = readFile12(file, "utf8").then((text3) => {
|
|
14921
|
-
for (const [key, copy] of Object.entries(JSON.parse(text3))) copies.set(key, copy);
|
|
14922
|
-
}).catch((error) => {
|
|
14923
|
-
if (error.code !== "ENOENT") logger.warn("the saved copies of Discover could not be read: %s", error.message);
|
|
14955
|
+
const saver = createJsonSaver(file, logger);
|
|
14956
|
+
const loaded = readJson2(file, { logger }).then(({ value }) => {
|
|
14957
|
+
for (const [key, copy] of Object.entries(value ?? {})) copies.set(key, copy);
|
|
14924
14958
|
});
|
|
14925
14959
|
function save() {
|
|
14926
|
-
|
|
14927
|
-
await mkdir11(dirname7(file), { recursive: true });
|
|
14928
|
-
await writeFile8(`${file}.part`, JSON.stringify(Object.fromEntries(copies)));
|
|
14929
|
-
await rename9(`${file}.part`, file);
|
|
14930
|
-
}).catch((error) => logger.warn("the copies of Discover could not be saved: %s", error.message));
|
|
14931
|
-
return saving;
|
|
14932
|
-
}
|
|
14933
|
-
function pump() {
|
|
14934
|
-
while (running < parallel && waiting.length > 0) {
|
|
14935
|
-
running += 1;
|
|
14936
|
-
waiting.shift()().finally(() => {
|
|
14937
|
-
running -= 1;
|
|
14938
|
-
pump();
|
|
14939
|
-
});
|
|
14940
|
-
}
|
|
14960
|
+
return saver.save(Object.fromEntries(copies));
|
|
14941
14961
|
}
|
|
14962
|
+
const limit = createLimiter(parallel);
|
|
14942
14963
|
function ask(key, produce) {
|
|
14943
14964
|
let settled;
|
|
14944
14965
|
flying.set(key, new Promise((resolve8) => {
|
|
14945
14966
|
settled = resolve8;
|
|
14946
14967
|
}));
|
|
14947
|
-
|
|
14968
|
+
limit(async () => {
|
|
14948
14969
|
try {
|
|
14949
14970
|
copies.set(key, { at: now(), value: await produce() });
|
|
14950
14971
|
failedAt.delete(key);
|
|
@@ -14959,7 +14980,6 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOU
|
|
|
14959
14980
|
settled();
|
|
14960
14981
|
}
|
|
14961
14982
|
});
|
|
14962
|
-
pump();
|
|
14963
14983
|
}
|
|
14964
14984
|
return {
|
|
14965
14985
|
/**
|
|
@@ -14989,12 +15009,11 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOU
|
|
|
14989
15009
|
}
|
|
14990
15010
|
|
|
14991
15011
|
// src/discover.js
|
|
14992
|
-
var notFound = (message) => Object.assign(new Error(message), { code: "not_found" });
|
|
14993
15012
|
function createDiscover({ copies, sources, covers, recommender }) {
|
|
14994
15013
|
async function sourcesFor(sourceId, kind, ability) {
|
|
14995
15014
|
if (sourceId !== ALL_SOURCES) {
|
|
14996
15015
|
const one = sources.get(sourceId);
|
|
14997
|
-
if (one === void 0) throw
|
|
15016
|
+
if (one === void 0) throw codedError("not_found", `no source ${String(sourceId)}`);
|
|
14998
15017
|
return [one];
|
|
14999
15018
|
}
|
|
15000
15019
|
const found = [];
|
|
@@ -15038,7 +15057,7 @@ function createDiscover({ copies, sources, covers, recommender }) {
|
|
|
15038
15057
|
}
|
|
15039
15058
|
return recommend(recommender, { person, language, candidates });
|
|
15040
15059
|
});
|
|
15041
|
-
return { picks: (copy.value ?? []).map((
|
|
15060
|
+
return { picks: (copy.value ?? []).map((pick4) => ({ ...pick4, work: withCovers(sources.get(pick4.work.source), pick4.work) })), loading: copy.loading };
|
|
15042
15061
|
}
|
|
15043
15062
|
};
|
|
15044
15063
|
}
|
|
@@ -15049,17 +15068,7 @@ var HOUR_MS3 = 36e5;
|
|
|
15049
15068
|
function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS5, retryMs = HOUR_MS3, parallel = 2, now = Date.now, logger }) {
|
|
15050
15069
|
const flying = /* @__PURE__ */ new Set();
|
|
15051
15070
|
const failedAt = /* @__PURE__ */ new Map();
|
|
15052
|
-
const
|
|
15053
|
-
let running = 0;
|
|
15054
|
-
function pump() {
|
|
15055
|
-
while (running < parallel && waiting.length > 0) {
|
|
15056
|
-
running += 1;
|
|
15057
|
-
waiting.shift()().finally(() => {
|
|
15058
|
-
running -= 1;
|
|
15059
|
-
pump();
|
|
15060
|
-
});
|
|
15061
|
-
}
|
|
15062
|
-
}
|
|
15071
|
+
const limit = createLimiter(parallel);
|
|
15063
15072
|
return function touch(path, entry) {
|
|
15064
15073
|
const sourceId = entry.source?.source;
|
|
15065
15074
|
const found = sourceId ? source(sourceId) : void 0;
|
|
@@ -15068,7 +15077,7 @@ function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS5, retryMs = HOUR_MS
|
|
|
15068
15077
|
${entry.source.id}`;
|
|
15069
15078
|
if (flying.has(key) || now() - (failedAt.get(key) ?? -Infinity) < retryMs) return;
|
|
15070
15079
|
flying.add(key);
|
|
15071
|
-
|
|
15080
|
+
limit(async () => {
|
|
15072
15081
|
try {
|
|
15073
15082
|
keep(path, snapshotOf(await found.info(entry.source.id, { person: entry.source.person }), now()));
|
|
15074
15083
|
failedAt.delete(key);
|
|
@@ -15079,7 +15088,6 @@ ${entry.source.id}`;
|
|
|
15079
15088
|
flying.delete(key);
|
|
15080
15089
|
}
|
|
15081
15090
|
});
|
|
15082
|
-
pump();
|
|
15083
15091
|
};
|
|
15084
15092
|
}
|
|
15085
15093
|
|
|
@@ -15087,7 +15095,6 @@ ${entry.source.id}`;
|
|
|
15087
15095
|
var HOUR_MS4 = 36e5;
|
|
15088
15096
|
var MIN_FREE_BYTES = 1e9;
|
|
15089
15097
|
var NO_CONVERTER = Object.freeze({ command: "", available: async () => false });
|
|
15090
|
-
var hubError = (code, message) => Object.assign(new Error(message), { code });
|
|
15091
15098
|
function createMediaHub(options) {
|
|
15092
15099
|
const { stateDir, libraryRoots, logger, now = Date.now } = options;
|
|
15093
15100
|
const sources = new Map(options.sources.map((source2) => [source2.id, source2]));
|
|
@@ -15158,14 +15165,13 @@ function createMediaHub(options) {
|
|
|
15158
15165
|
recommender: { command: options.recommender?.command ?? [], env: options.recommender?.env ?? {}, cwd: stateDir, hasSource: (id) => sources.has(id) }
|
|
15159
15166
|
});
|
|
15160
15167
|
const sweepTimer = setInterval(() => {
|
|
15161
|
-
library.sweep().catch(() =>
|
|
15162
|
-
});
|
|
15168
|
+
library.sweep().catch((error) => logger.warn("library sweep: %s", error.message));
|
|
15163
15169
|
cache.enforce().catch(() => {
|
|
15164
15170
|
});
|
|
15165
15171
|
}, HOUR_MS4);
|
|
15166
15172
|
function roomShow(id) {
|
|
15167
15173
|
const room = rooms.listRooms().find((entry) => entry.id === id);
|
|
15168
|
-
if (room === void 0) throw
|
|
15174
|
+
if (room === void 0) throw codedError("not_found", "no such room");
|
|
15169
15175
|
return room.show;
|
|
15170
15176
|
}
|
|
15171
15177
|
async function onFiles(job) {
|
|
@@ -15190,7 +15196,7 @@ function createMediaHub(options) {
|
|
|
15190
15196
|
}
|
|
15191
15197
|
const followStart = (info, at = now()) => ({ since: at, seen: seenAtStart(info.id, info), checkedAt: at, nextAt: nextCheckAt(at, (options.follow?.random ?? Math.random)()) });
|
|
15192
15198
|
async function adoptEmpty(sourceId, item) {
|
|
15193
|
-
if (!(item.episodes > 0)) throw
|
|
15199
|
+
if (!(item.episodes > 0)) throw codedError("empty", `${item.title || item.id} has no episodes yet`);
|
|
15194
15200
|
const dir = await folderFor(sourceId, item);
|
|
15195
15201
|
await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title });
|
|
15196
15202
|
library.setWork(dir, snapshotOf(item, now()));
|
|
@@ -15222,7 +15228,7 @@ function createMediaHub(options) {
|
|
|
15222
15228
|
const withCovers = (show) => show.work && show.source?.source ? { ...show, work: covers.decorate(show.source.source, show.work) } : show;
|
|
15223
15229
|
function source(id) {
|
|
15224
15230
|
const found = sources.get(id);
|
|
15225
|
-
if (found === void 0) throw
|
|
15231
|
+
if (found === void 0) throw codedError("not_found", `no source ${String(id)}`);
|
|
15226
15232
|
return found;
|
|
15227
15233
|
}
|
|
15228
15234
|
async function isNewSeries(sourceId, item) {
|
|
@@ -15247,7 +15253,7 @@ ${work.id}`).digest("hex").slice(0, 8);
|
|
|
15247
15253
|
const owner = shows.find((show) => show.path === path);
|
|
15248
15254
|
if (!exists2 || owner?.source?.source === sourceId && owner.source.id === item.id) return path;
|
|
15249
15255
|
}
|
|
15250
|
-
throw
|
|
15256
|
+
throw codedError("exists", `${cleanName(item.title)} is already in the library`);
|
|
15251
15257
|
}
|
|
15252
15258
|
return {
|
|
15253
15259
|
async load() {
|
|
@@ -15255,8 +15261,9 @@ ${work.id}`).digest("hex").slice(0, 8);
|
|
|
15255
15261
|
await books.load();
|
|
15256
15262
|
await rooms.load();
|
|
15257
15263
|
await downloads.load();
|
|
15258
|
-
await library.sweep();
|
|
15259
|
-
await cache.refreshActive()
|
|
15264
|
+
await library.sweep().catch((error) => logger.warn("library sweep: %s", error.message));
|
|
15265
|
+
await cache.refreshActive().catch(() => {
|
|
15266
|
+
});
|
|
15260
15267
|
follows.start();
|
|
15261
15268
|
},
|
|
15262
15269
|
// ---------------------------------------------------------- rooms
|
|
@@ -15317,7 +15324,7 @@ ${work.id}`).digest("hex").slice(0, 8);
|
|
|
15317
15324
|
},
|
|
15318
15325
|
async startStep(path, id, person) {
|
|
15319
15326
|
const show = library.showPath(path);
|
|
15320
|
-
if (show === null || !library.stepStarted(show, id)) throw
|
|
15327
|
+
if (show === null || !library.stepStarted(show, id)) throw codedError("not_found", "no such step");
|
|
15321
15328
|
await log.append("step.started", { show, title: library.workOf(show)?.title ?? "", step: id, person: person.key, by: person.name });
|
|
15322
15329
|
return { ok: true };
|
|
15323
15330
|
},
|
|
@@ -15362,7 +15369,7 @@ ${work.id}`).digest("hex").slice(0, 8);
|
|
|
15362
15369
|
async roomQuality(id, quality) {
|
|
15363
15370
|
const show = roomShow(id);
|
|
15364
15371
|
const offered = show === null ? [] : library.workOf(show)?.qualities ?? [];
|
|
15365
|
-
if (!isQuality(quality) || !offered.includes(quality)) throw
|
|
15372
|
+
if (!isQuality(quality) || !offered.includes(quality)) throw codedError("invalid", "the show is not offered in this quality");
|
|
15366
15373
|
await cache.requality(show, quality);
|
|
15367
15374
|
return { quality };
|
|
15368
15375
|
},
|
|
@@ -15394,7 +15401,7 @@ ${work.id}`).digest("hex").slice(0, 8);
|
|
|
15394
15401
|
}
|
|
15395
15402
|
const answers = await Promise.allSettled(candidates.map((one) => ask(one)));
|
|
15396
15403
|
const failed = answers.flatMap((answer, index) => answer.status === "rejected" ? [{ source: candidates[index].id, message: answer.reason?.message ?? String(answer.reason) }] : []);
|
|
15397
|
-
if (candidates.length > 0 && failed.length === candidates.length) throw
|
|
15404
|
+
if (candidates.length > 0 && failed.length === candidates.length) throw codedError("source_failed", failed.map((entry) => entry.message).join("; "));
|
|
15398
15405
|
return { results: interleave(answers.map((answer) => answer.status === "fulfilled" ? answer.value.results : [])), next: null, failed };
|
|
15399
15406
|
},
|
|
15400
15407
|
/** A work's details; `person` and `language` say who asks (their account for its site) and in which language (subtitles). */
|
|
@@ -15410,12 +15417,12 @@ ${work.id}`).digest("hex").slice(0, 8);
|
|
|
15410
15417
|
*/
|
|
15411
15418
|
async fetch({ source: sourceId, id, watch = false, together = false, all = false, quality = "", by = "", person = "", language = "" }) {
|
|
15412
15419
|
const item = await source(sourceId).info(id, { person, language });
|
|
15413
|
-
if (!(item.episodes > 0)) throw
|
|
15420
|
+
if (!(item.episodes > 0)) throw codedError("empty", `${item.title || id} has no episodes`);
|
|
15414
15421
|
const dir = await folderFor(sourceId, item);
|
|
15415
15422
|
const subject = `${sourceId}:${item.id}`;
|
|
15416
15423
|
const isNew = points.enabled && await isNewSeries(sourceId, item);
|
|
15417
15424
|
const disk = await statfs2(libraryRoots[0]).catch(() => null);
|
|
15418
|
-
if (disk !== null && disk.bavail * disk.bsize < MIN_FREE_BYTES) throw
|
|
15425
|
+
if (disk !== null && disk.bavail * disk.bsize < MIN_FREE_BYTES) throw codedError("no_space", "the library disk is almost full; delete something first");
|
|
15419
15426
|
const tickets = await points.pay(person, points.wants({ isNew, starts: watch }), { subject });
|
|
15420
15427
|
const how = { ...isQuality(quality) ? { quality } : {}, person, language };
|
|
15421
15428
|
await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title, ...how }, { pinned: all });
|
|
@@ -15461,7 +15468,7 @@ ${work.id}`).digest("hex").slice(0, 8);
|
|
|
15461
15468
|
/** Start a show's download again after it failed. */
|
|
15462
15469
|
async retryDownload(path) {
|
|
15463
15470
|
const show = library.showPath(path);
|
|
15464
|
-
if (show === null || downloads.job(show) === void 0) throw
|
|
15471
|
+
if (show === null || downloads.job(show) === void 0) throw codedError("not_found", "no download for this show");
|
|
15465
15472
|
downloads.retry(show);
|
|
15466
15473
|
await cache.refresh(show, { retry: true });
|
|
15467
15474
|
return { download: downloads.state(show) };
|
|
@@ -15508,9 +15515,8 @@ ${identity.id}`).digest("hex").slice(0, 20);
|
|
|
15508
15515
|
|
|
15509
15516
|
// src/person-routes.js
|
|
15510
15517
|
var PERSON_PATH = "/api/media-hub";
|
|
15511
|
-
var
|
|
15512
|
-
var
|
|
15513
|
-
var failure2 = (error) => json(error?.status ?? STATUS[error?.code] ?? 500, errorBody(error));
|
|
15518
|
+
var json = (status, body2) => new Response(JSON.stringify(body2), { status, headers: { ...SECURITY_HEADERS, "content-type": "application/json; charset=utf-8" } });
|
|
15519
|
+
var failure2 = (error) => json(statusOf(error), errorBody(error));
|
|
15514
15520
|
async function body(request) {
|
|
15515
15521
|
try {
|
|
15516
15522
|
const value = await request.json();
|
|
@@ -15519,7 +15525,6 @@ async function body(request) {
|
|
|
15519
15525
|
throw Object.assign(new Error("request body is not JSON"), { status: 400 });
|
|
15520
15526
|
}
|
|
15521
15527
|
}
|
|
15522
|
-
var pick4 = (value, keys) => Object.fromEntries(keys.filter((key) => value?.[key] !== void 0).map((key) => [key, value[key]]));
|
|
15523
15528
|
var text2 = (value) => typeof value === "string" ? value : "";
|
|
15524
15529
|
function createPersonRoutes({ hub, identity }) {
|
|
15525
15530
|
const handle = (fn) => async (request) => {
|
|
@@ -15545,7 +15550,7 @@ function createPersonRoutes({ hub, identity }) {
|
|
|
15545
15550
|
requestBody: "buffered",
|
|
15546
15551
|
fetch: handle(async (request, current, person) => {
|
|
15547
15552
|
const input = await body(request);
|
|
15548
|
-
return current.fetch({ ...
|
|
15553
|
+
return current.fetch({ ...pick3(input, ["source", "id", "watch", "together", "all", "quality", "by"]), language: text2(input.language), person: person.id });
|
|
15549
15554
|
})
|
|
15550
15555
|
},
|
|
15551
15556
|
{
|
|
@@ -15554,7 +15559,7 @@ function createPersonRoutes({ hub, identity }) {
|
|
|
15554
15559
|
requestBody: "buffered",
|
|
15555
15560
|
fetch: handle(async (request, current, person) => {
|
|
15556
15561
|
const input = await body(request);
|
|
15557
|
-
return current.createRoom({ ...
|
|
15562
|
+
return current.createRoom({ ...pick3(input, ["path", "title", "by", "start"]), fromPanel: true, person: person.id });
|
|
15558
15563
|
})
|
|
15559
15564
|
},
|
|
15560
15565
|
{
|
|
@@ -15625,7 +15630,7 @@ function createEventsRoute({ hub }) {
|
|
|
15625
15630
|
stop();
|
|
15626
15631
|
}
|
|
15627
15632
|
});
|
|
15628
|
-
return new Response(stream, { status: 200, headers: { ...
|
|
15633
|
+
return new Response(stream, { status: 200, headers: { ...SECURITY_HEADERS, "content-type": "text/event-stream; charset=utf-8", "cache-control": "private, no-cache, no-transform", "x-accel-buffering": "no" } });
|
|
15629
15634
|
}
|
|
15630
15635
|
};
|
|
15631
15636
|
}
|
|
@@ -15638,15 +15643,10 @@ var SHELF_PATH = "/api/media-hub/shelf";
|
|
|
15638
15643
|
async function fileResponse(request, { path, name: name2, type }) {
|
|
15639
15644
|
const info = await stat11(path).catch(() => null);
|
|
15640
15645
|
if (info === null || !info.isFile()) return json(404, { error: { code: "not_found", message: "the file is gone" } });
|
|
15641
|
-
const
|
|
15642
|
-
const headers = { ...
|
|
15643
|
-
|
|
15644
|
-
|
|
15645
|
-
const end = range.kind === "window" ? range.end : info.size - 1;
|
|
15646
|
-
headers["content-length"] = String(info.size === 0 ? 0 : end - start + 1);
|
|
15647
|
-
if (range.kind === "window") headers["content-range"] = `bytes ${start}-${end}/${info.size}`;
|
|
15648
|
-
const stream = request.method === "HEAD" || info.size === 0 ? null : Readable2.toWeb(createReadStream3(path, { start, end }));
|
|
15649
|
-
return new Response(stream, { status: range.kind === "window" ? 206 : 200, headers });
|
|
15646
|
+
const plan = rangePlan(request.headers.get("range"), info.size);
|
|
15647
|
+
const headers = { ...SECURITY_HEADERS, "content-type": type, "content-disposition": attachment(name2), "accept-ranges": "bytes", ...plan.headers };
|
|
15648
|
+
const stream = plan.status === 416 || request.method === "HEAD" || info.size === 0 ? null : Readable2.toWeb(createReadStream3(path, { start: plan.start, end: plan.end }));
|
|
15649
|
+
return new Response(stream, { status: plan.status, headers });
|
|
15650
15650
|
}
|
|
15651
15651
|
function createShelfRoutes({ books, identity }) {
|
|
15652
15652
|
const handle = (fn) => async (request) => {
|
|
@@ -15723,8 +15723,7 @@ function apply(ctx, config) {
|
|
|
15723
15723
|
return service.pruneCache(config.cacheDays);
|
|
15724
15724
|
}).catch((error) => logger.warn("could not start rooms: %s", error.message));
|
|
15725
15725
|
const prune = setInterval(() => {
|
|
15726
|
-
service.pruneCache(config.cacheDays).catch(() =>
|
|
15727
|
-
});
|
|
15726
|
+
service.pruneCache(config.cacheDays).catch((error) => logger.warn("pruning the cache: %s", error.message));
|
|
15728
15727
|
}, DAY_MS6);
|
|
15729
15728
|
const identity = () => ctx.get("requestIdentity");
|
|
15730
15729
|
const fetchRoutes = [
|