@astrofoundry/trendarr 0.12.0 → 0.14.0
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/README.md +6 -3
- package/dist/cli.js +130 -15
- package/dist/clients/chaptarr.js +30 -0
- package/dist/clients/prowlarr.js +78 -0
- package/dist/commands/books.js +346 -11
- package/dist/commands/init.js +8 -1
- package/dist/config.js +1 -0
- package/dist/format.js +33 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ TMDB weekly trending in the terminal — IMDb ratings via OMDb, Radarr/Sonarr li
|
|
|
8
8
|
pnpm add -g @astrofoundry/trendarr
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
Node 24+. Run `trendarr init` once — prompts for TMDB API Read Access Token (themoviedb.org/settings/api), OMDb, Radarr, Sonarr, and SABnzbd credentials, validates each live, and saves to `~/.trendarr/config.json` (mode 600). Books are optional: init then also asks for Chaptarr and
|
|
11
|
+
Node 24+. Run `trendarr init` once — prompts for TMDB API Read Access Token (themoviedb.org/settings/api), OMDb, Radarr, Sonarr, and SABnzbd credentials, validates each live, and saves to `~/.trendarr/config.json` (mode 600). Books are optional: init then also asks for Chaptarr, Audiobookshelf, and Prowlarr. No environment variables.
|
|
12
12
|
|
|
13
13
|
## Commands
|
|
14
14
|
|
|
@@ -21,8 +21,11 @@ trendarr add-series <imdbIds...> [--json]
|
|
|
21
21
|
trendarr sabnzbd status|pause|resume|unpause [--json]
|
|
22
22
|
trendarr books search <query> [--max-entries 10] [--json]
|
|
23
23
|
trendarr books add <bookId> --format audiobook|ebook [--json]
|
|
24
|
-
trendarr books
|
|
24
|
+
trendarr books narrators <bookId> [--max-entries 5] [--json]
|
|
25
|
+
trendarr books releases <bookId> --format audiobook|ebook [--edition <id>] [--max-entries 10] [--json]
|
|
25
26
|
trendarr books grab <chaptarrId> <guid> <indexerId> [--json]
|
|
27
|
+
trendarr books push <chaptarrId> <infoHash> [--json]
|
|
28
|
+
trendarr books best <bookId> --format audiobook|ebook [--edition <id>] [--json]
|
|
26
29
|
trendarr books ready <chaptarrId> [--json]
|
|
27
30
|
trendarr books send <chaptarrId> <device> [--json]
|
|
28
31
|
trendarr books ebooks [--json]
|
|
@@ -31,7 +34,7 @@ trendarr books send-item <itemId> <device> [--json]
|
|
|
31
34
|
|
|
32
35
|
`trendarr <command> --help` shows parameters and output shapes. Movies below the IMDb min-rating (default 6.5) are dropped from trending; unrated movies are kept; `--min-rating 0` disables the filter. `recommend` ranks the titles TMDB recommends for your Radarr and Sonarr library by how many library titles lead to them, and keeps released titles not in the library with IMDb 7.0+ and 5,000 votes (movies) or 2,000 (series).
|
|
33
36
|
|
|
34
|
-
`books` works with Chaptarr, which keeps an audiobook and an ebook entry per work. `add` lets Chaptarr pick the release and waits up to 2 minutes to report whether it grabbed one; `releases` then `grab` let you pick one yourself (narrator, size, format). `ready` tells whether a book has its file and, for an ebook, whether Audiobookshelf has it. `send` emails an ebook to a Kindle through Audiobookshelf's e-reader devices. `ebooks` lists every ebook in Audiobookshelf, newest first, and `send-item` emails one of them by its item id.
|
|
37
|
+
`books` works with Chaptarr, which keeps an audiobook and an ebook entry per work. `add` lets Chaptarr pick the release and waits up to 2 minutes to report whether it grabbed one; `releases` then `grab` let you pick one yourself (narrator, size, format). `narrators` lists an audiobook's narrations, most rated first; `--edition` on `releases` and `best` monitors the one you pick first. Audiobook releases come best first: the narrator's surname in the name, then M4B, then the bitrate estimated from the edition's length. Chaptarr refuses some public trackers (its indexer test finds no book in their recent list), so with Prowlarr configured, audiobook releases also include the torrents of Prowlarr indexers Chaptarr lacks; `push` sends one to Chaptarr, which checks it like an RSS release and files it under the monitored book its name matches. `best` grabs or pushes the first of them without a Chaptarr rejection, or leaves the book wanted. `ready` tells whether a book has its file and, for an ebook, whether Audiobookshelf has it. `send` emails an ebook to a Kindle through Audiobookshelf's e-reader devices. `ebooks` lists every ebook in Audiobookshelf, newest first, and `send-item` emails one of them by its item id.
|
|
35
38
|
|
|
36
39
|
## Development
|
|
37
40
|
|
package/dist/cli.js
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
3
|
import { Command, InvalidArgumentError } from 'commander';
|
|
4
4
|
import { addMovies, addSeries, hasFailure } from './commands/add.js';
|
|
5
|
-
import { addBook, bookReady, bookReleases, grabRelease, listEbooks, searchBooks, sendBook, sendItem } from './commands/books.js';
|
|
5
|
+
import { addBook, bestBook, bookNarrators, bookReady, bookReleases, grabRelease, pushRelease, listEbooks, searchBooks, sendBook, sendItem, } from './commands/books.js';
|
|
6
6
|
import { runInit } from './commands/init.js';
|
|
7
7
|
import { runSabnzbd } from './commands/sabnzbd.js';
|
|
8
8
|
import { CANDIDATE_LIMIT, getRecommendations } from './commands/recommend.js';
|
|
9
9
|
import { getSearch } from './commands/search.js';
|
|
10
10
|
import { getTrending } from './commands/trending.js';
|
|
11
11
|
import { ConfigError, loadConfig } from './config.js';
|
|
12
|
-
import { renderAddTable, renderBookAdd, renderBookGrab, renderBookReady, renderBookSearchTable, renderBookSend, renderEbookList, renderItemSend, renderReleasesTable, renderRecommendTable, renderSabStatus, renderSearchDiscord, renderSearchTable, renderTrendingDiscord, renderTrendingTable, toJson, } from './format.js';
|
|
12
|
+
import { renderAddTable, renderBookAdd, renderBookBest, renderBookGrab, renderBookReady, renderBookSearchTable, renderBookSend, renderEbookList, renderItemSend, renderNarrators, renderReleasesTable, renderRecommendTable, renderSabStatus, renderSearchDiscord, renderSearchTable, renderTrendingDiscord, renderTrendingTable, toJson, } from './format.js';
|
|
13
13
|
import { describeError } from './http.js';
|
|
14
14
|
const pkg = createRequire(import.meta.url)('../package.json');
|
|
15
15
|
const program = new Command();
|
|
@@ -35,6 +35,11 @@ function parseFormat(value) {
|
|
|
35
35
|
return value;
|
|
36
36
|
throw new InvalidArgumentError("must be 'audiobook' or 'ebook'");
|
|
37
37
|
}
|
|
38
|
+
function parseInfoHash(value) {
|
|
39
|
+
if (/^[A-Fa-f0-9]{40}$/.test(value))
|
|
40
|
+
return value.toUpperCase();
|
|
41
|
+
throw new InvalidArgumentError('not a torrent info hash (40 hex characters)');
|
|
42
|
+
}
|
|
38
43
|
function parseBookId(value) {
|
|
39
44
|
if (/^[a-z]{2,10}:[\w:-]{1,40}$/.test(value))
|
|
40
45
|
return value;
|
|
@@ -320,15 +325,19 @@ const books = program
|
|
|
320
325
|
.command('books')
|
|
321
326
|
.description('audiobooks and ebooks: Chaptarr search and adds, Audiobookshelf Send to Kindle')
|
|
322
327
|
.addHelpText('after', `
|
|
323
|
-
Needs the optional "chaptarr" section of the config (and "audiobookshelf" for send and the Kindle list
|
|
328
|
+
Needs the optional "chaptarr" section of the config (and "audiobookshelf" for send and the Kindle list,
|
|
329
|
+
"prowlarr" for push and for audiobook releases from indexers Chaptarr refuses).
|
|
324
330
|
Chaptarr keeps one book per format: an audiobook id and an ebook id for the same work. The book id
|
|
325
331
|
used by add and releases is Chaptarr's foreign book id (e.g. gr:3060926), from books search.
|
|
326
332
|
|
|
327
333
|
Actions:
|
|
328
334
|
search <query> Find works, with each format's state and the Kindle devices.
|
|
329
335
|
add <bookId> --format <f> Monitor one format and let Chaptarr pick and download a release.
|
|
330
|
-
|
|
336
|
+
narrators <bookId> List the audiobook narrations, most rated first.
|
|
337
|
+
releases <bookId> --format <f> List the releases you can pick from, best first for audiobooks.
|
|
331
338
|
grab <chaptarrId> <guid> <indexerId> Download one release from that list.
|
|
339
|
+
push <chaptarrId> <infoHash> Download one Prowlarr release from that list through Chaptarr.
|
|
340
|
+
best <bookId> --format <f> Download the first release of that list Chaptarr accepts.
|
|
332
341
|
ready <chaptarrId> Whether the book has a file and, for an ebook, is in Audiobookshelf.
|
|
333
342
|
send <chaptarrId> <device> Email the ebook to a Kindle through Audiobookshelf.
|
|
334
343
|
ebooks List every ebook in Audiobookshelf, newest first, with the Kindles.
|
|
@@ -397,29 +406,73 @@ Examples:
|
|
|
397
406
|
fail(err);
|
|
398
407
|
}
|
|
399
408
|
});
|
|
409
|
+
books
|
|
410
|
+
.command('narrators')
|
|
411
|
+
.description('list the narrations of an audiobook to pick from')
|
|
412
|
+
.argument('<bookId>', 'foreign book id from books search, e.g. gr:3060926', parseBookId)
|
|
413
|
+
.option('--max-entries <n>', 'narrations', parsePositiveInt)
|
|
414
|
+
.option('--json', 'output JSON')
|
|
415
|
+
.addHelpText('after', `
|
|
416
|
+
Behavior: adds the audiobook unmonitored when Chaptarr does not have it, then groups its editions by
|
|
417
|
+
narrator. Each group shows its most rated edition; groups are ordered by votes. Changes no edition.
|
|
418
|
+
|
|
419
|
+
Parameters:
|
|
420
|
+
--max-entries <n> Narrations (positive integer). Default: 5.
|
|
421
|
+
|
|
422
|
+
Output (--json): { foreign_book_id, book_id, title, narrators: NarratorChoice[] }
|
|
423
|
+
NarratorChoice: { edition_id, narrators, year, duration_seconds, rating, votes, language, chosen }
|
|
424
|
+
edition_id goes to books releases --edition or books best --edition; chosen marks the narration of
|
|
425
|
+
the monitored edition.
|
|
426
|
+
|
|
427
|
+
Examples:
|
|
428
|
+
trendarr books narrators hc:139773 --json`)
|
|
429
|
+
.action(async (bookId, opts) => {
|
|
430
|
+
try {
|
|
431
|
+
const { output, warnings } = await bookNarrators(loadConfig(), bookId, opts);
|
|
432
|
+
printWarnings(warnings);
|
|
433
|
+
process.stdout.write(`${opts.json === true ? toJson(output) : renderNarrators(output)}\n`);
|
|
434
|
+
}
|
|
435
|
+
catch (err) {
|
|
436
|
+
fail(err);
|
|
437
|
+
}
|
|
438
|
+
});
|
|
400
439
|
books
|
|
401
440
|
.command('releases')
|
|
402
441
|
.description('list the releases of one format to pick from')
|
|
403
442
|
.argument('<bookId>', 'foreign book id from books search, e.g. gr:3060926', parseBookId)
|
|
404
443
|
.requiredOption('--format <format>', "'audiobook' or 'ebook'", parseFormat)
|
|
444
|
+
.option('--edition <id>', 'edition_id from books narrators to monitor first', parsePositiveInt)
|
|
405
445
|
.option('--max-entries <n>', 'releases', parsePositiveInt)
|
|
406
446
|
.option('--json', 'output JSON')
|
|
407
447
|
.addHelpText('after', `
|
|
408
|
-
Behavior: adds the book unmonitored when Chaptarr does not have it,
|
|
409
|
-
to the plain one as books add does, then runs Chaptarr's
|
|
410
|
-
search (can take a minute). Releases in a format the profile does not want, and
|
|
411
|
-
enough seeders, are left out.
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
448
|
+
Behavior: adds the book unmonitored when Chaptarr does not have it, monitors --edition when given,
|
|
449
|
+
switches a suffixed edition title to the plain one as books add does, then runs Chaptarr's
|
|
450
|
+
interactive search (can take a minute). Releases in a format the profile does not want, and
|
|
451
|
+
torrents without enough seeders, are left out. Ebook releases keep Chaptarr's order. Audiobook
|
|
452
|
+
releases come best first: the monitored narrator's surname in the name, then M4B over MP3 and FLAC
|
|
453
|
+
over other formats, then the higher estimated bitrate, then Chaptarr's order. Grab one within
|
|
454
|
+
30 minutes, while Chaptarr still caches the search.
|
|
455
|
+
With "prowlarr" configured, audiobooks also get the torrent releases of Prowlarr indexers that
|
|
456
|
+
Chaptarr does not have (Chaptarr refuses some public trackers), searched by title in category 3030.
|
|
457
|
+
Their quality comes from the name, they carry no rejections, and books push downloads them.
|
|
458
|
+
|
|
459
|
+
Output (--json): { foreign_book_id, format, book_id, title, narrators, duration_seconds,
|
|
460
|
+
releases: BookRelease[] }
|
|
461
|
+
BookRelease: { rank, source, title, size, quality, protocol, indexer, seeders, age_days, guid,
|
|
462
|
+
indexer_id, rejections, narrator_match, kbps } — source is chaptarr or prowlarr; for prowlarr, guid
|
|
463
|
+
is the info hash for books push; size in bytes; rejections are Chaptarr's reasons it would not
|
|
464
|
+
pick it by itself; kbps is size divided by the edition's length (null without a length or for
|
|
465
|
+
ebooks), so a release holding several books shows too high a value.
|
|
417
466
|
|
|
418
467
|
Examples:
|
|
419
|
-
trendarr books releases gr:3060926 --format audiobook --max-entries 5
|
|
468
|
+
trendarr books releases gr:3060926 --format audiobook --max-entries 5
|
|
469
|
+
trendarr books releases hc:139773 --format audiobook --edition 203`)
|
|
420
470
|
.action(async (bookId, opts) => {
|
|
421
471
|
try {
|
|
422
|
-
const { output, warnings } = await bookReleases(loadConfig(), bookId, opts.format,
|
|
472
|
+
const { output, warnings } = await bookReleases(loadConfig(), bookId, opts.format, {
|
|
473
|
+
maxEntries: opts.maxEntries,
|
|
474
|
+
editionId: opts.edition,
|
|
475
|
+
});
|
|
423
476
|
printWarnings(warnings);
|
|
424
477
|
process.stdout.write(`${opts.json === true ? toJson(output) : renderReleasesTable(output)}\n`);
|
|
425
478
|
}
|
|
@@ -454,6 +507,68 @@ Examples:
|
|
|
454
507
|
fail(err);
|
|
455
508
|
}
|
|
456
509
|
});
|
|
510
|
+
books
|
|
511
|
+
.command('push')
|
|
512
|
+
.description('download one Prowlarr release from books releases through Chaptarr')
|
|
513
|
+
.argument('<chaptarrId>', 'book_id from books releases', parsePositiveInt)
|
|
514
|
+
.argument('<infoHash>', 'guid of a release whose source is prowlarr', parseInfoHash)
|
|
515
|
+
.option('--json', 'output JSON')
|
|
516
|
+
.addHelpText('after', `
|
|
517
|
+
Behavior: monitors the book, searches Prowlarr again as books releases does, and pushes the release
|
|
518
|
+
with that info hash to Chaptarr, which checks it like an RSS release and sends it to the torrent
|
|
519
|
+
client when it accepts it. Chaptarr files it under the monitored book it matches by name.
|
|
520
|
+
|
|
521
|
+
Output (--json): { book_id, title, status, detail, sabnzbd_paused }
|
|
522
|
+
status is grabbed, rejected (detail: Chaptarr's reasons), or error. sabnzbd_paused is null.
|
|
523
|
+
Exit code 1 unless grabbed.
|
|
524
|
+
|
|
525
|
+
Examples:
|
|
526
|
+
trendarr books push 3 458459567D82D08F32407044A4ABD00AEE9D0D84`)
|
|
527
|
+
.action(async (chaptarrId, infoHash, opts) => {
|
|
528
|
+
try {
|
|
529
|
+
const { output, warnings } = await pushRelease(loadConfig(), chaptarrId, infoHash);
|
|
530
|
+
printWarnings(warnings);
|
|
531
|
+
process.stdout.write(`${opts.json === true ? toJson(output) : renderBookGrab(output)}\n`);
|
|
532
|
+
if (output.status !== 'grabbed')
|
|
533
|
+
process.exitCode = 1;
|
|
534
|
+
}
|
|
535
|
+
catch (err) {
|
|
536
|
+
fail(err);
|
|
537
|
+
}
|
|
538
|
+
});
|
|
539
|
+
books
|
|
540
|
+
.command('best')
|
|
541
|
+
.description('download the best release Chaptarr accepts')
|
|
542
|
+
.argument('<bookId>', 'foreign book id from books search, e.g. gr:3060926', parseBookId)
|
|
543
|
+
.requiredOption('--format <format>', "'audiobook' or 'ebook'", parseFormat)
|
|
544
|
+
.option('--edition <id>', 'edition_id from books narrators to monitor first', parsePositiveInt)
|
|
545
|
+
.option('--json', 'output JSON')
|
|
546
|
+
.addHelpText('after', `
|
|
547
|
+
Behavior: does what books releases does, then monitors the book and grabs the first release in that
|
|
548
|
+
order without rejections; a Prowlarr release is pushed as books push does, and when Chaptarr
|
|
549
|
+
refuses it the next one is tried. When none is taken, the book stays monitored and Chaptarr keeps
|
|
550
|
+
looking. A format that already has a file reports already_exists; one in the download queue
|
|
551
|
+
reports downloading without a grab.
|
|
552
|
+
|
|
553
|
+
Output (--json): { foreign_book_id, format, book_id, title, status, detail, release, sabnzbd_paused }
|
|
554
|
+
status is one of: downloading | nothing_found | already_exists | not_found | error.
|
|
555
|
+
release: { title, quality, kbps, narrator_match } of the grabbed release, else null.
|
|
556
|
+
Exit code 1 on not_found or error.
|
|
557
|
+
|
|
558
|
+
Examples:
|
|
559
|
+
trendarr books best hc:139773 --format audiobook --edition 203`)
|
|
560
|
+
.action(async (bookId, opts) => {
|
|
561
|
+
try {
|
|
562
|
+
const { output, warnings } = await bestBook(loadConfig(), bookId, opts.format, { editionId: opts.edition });
|
|
563
|
+
printWarnings(warnings);
|
|
564
|
+
process.stdout.write(`${opts.json === true ? toJson(output) : renderBookBest(output)}\n`);
|
|
565
|
+
if (output.status === 'not_found' || output.status === 'error')
|
|
566
|
+
process.exitCode = 1;
|
|
567
|
+
}
|
|
568
|
+
catch (err) {
|
|
569
|
+
fail(err);
|
|
570
|
+
}
|
|
571
|
+
});
|
|
457
572
|
books
|
|
458
573
|
.command('ready')
|
|
459
574
|
.description('report whether a book has its file and, for an ebook, whether Audiobookshelf has it')
|
package/dist/clients/chaptarr.js
CHANGED
|
@@ -50,6 +50,9 @@ const editionSchema = z.object({
|
|
|
50
50
|
language: z.string().nullish(),
|
|
51
51
|
monitored: z.boolean(),
|
|
52
52
|
narrators: z.array(z.object({ name: z.string() })).nullish(),
|
|
53
|
+
ratings: z.object({ value: z.number().nullish(), votes: z.number().nullish() }).nullish(),
|
|
54
|
+
durationSeconds: z.number().nullish(),
|
|
55
|
+
releaseDate: z.string().nullish(),
|
|
53
56
|
});
|
|
54
57
|
const rawSchema = z.record(z.string(), z.unknown());
|
|
55
58
|
const commandSchema = z.object({ id: z.number(), status: z.string(), queued: z.string() });
|
|
@@ -57,6 +60,12 @@ const historySchema = z.object({
|
|
|
57
60
|
records: z.array(z.object({ bookId: z.number().nullish(), eventType: z.string(), date: z.string() })),
|
|
58
61
|
});
|
|
59
62
|
const queueSchema = z.object({ records: z.array(z.object({ bookId: z.number().nullish() })) });
|
|
63
|
+
const indexerNamesSchema = z.array(z.object({ name: z.string() }));
|
|
64
|
+
const pushSchema = z.object({
|
|
65
|
+
approved: z.boolean(),
|
|
66
|
+
rejections: z.array(rejectionSchema).nullish(),
|
|
67
|
+
bookId: z.number().nullish(),
|
|
68
|
+
});
|
|
60
69
|
const downloadClientsSchema = z.array(z.object({
|
|
61
70
|
implementation: z.string(),
|
|
62
71
|
enable: z.boolean(),
|
|
@@ -208,6 +217,10 @@ export class ChaptarrClient {
|
|
|
208
217
|
language: e.language ?? null,
|
|
209
218
|
monitored: e.monitored,
|
|
210
219
|
narrators: (e.narrators ?? []).map((n) => n.name),
|
|
220
|
+
rating: e.ratings?.value ?? null,
|
|
221
|
+
votes: e.ratings?.votes ?? null,
|
|
222
|
+
durationSeconds: e.durationSeconds != null && e.durationSeconds > 0 ? e.durationSeconds : null,
|
|
223
|
+
releaseDate: e.releaseDate ?? null,
|
|
211
224
|
}));
|
|
212
225
|
}
|
|
213
226
|
async monitorEdition(bookId, editionId) {
|
|
@@ -229,6 +242,23 @@ export class ChaptarrClient {
|
|
|
229
242
|
async grab(guid, indexerId) {
|
|
230
243
|
await this.request('/api/v1/release', { method: 'POST', body: { guid, indexerId }, timeoutMs: LOOKUP_TIMEOUT_MS });
|
|
231
244
|
}
|
|
245
|
+
async indexerNames() {
|
|
246
|
+
return indexerNamesSchema.parse(await this.request('/api/v1/indexer')).map((i) => i.name);
|
|
247
|
+
}
|
|
248
|
+
async push(release) {
|
|
249
|
+
const body = {
|
|
250
|
+
title: release.title,
|
|
251
|
+
downloadUrl: release.magnet,
|
|
252
|
+
magnetUrl: release.magnet,
|
|
253
|
+
protocol: 'torrent',
|
|
254
|
+
publishDate: release.publishDate,
|
|
255
|
+
size: release.size ?? 0,
|
|
256
|
+
indexer: release.indexer,
|
|
257
|
+
seeders: release.seeders,
|
|
258
|
+
};
|
|
259
|
+
const pushed = pushSchema.parse(await this.request('/api/v1/release/push', { method: 'POST', body, timeoutMs: LOOKUP_TIMEOUT_MS }));
|
|
260
|
+
return { approved: pushed.approved, rejections: pushed.rejections ?? [], bookId: pushed.bookId ?? null };
|
|
261
|
+
}
|
|
232
262
|
async book(bookId) {
|
|
233
263
|
return bookSchema.parse(await this.request(`/api/v1/book/${bookId}`));
|
|
234
264
|
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { fetchJson } from '../http.js';
|
|
3
|
+
const SEARCH_TIMEOUT_MS = 150_000;
|
|
4
|
+
const statusSchema = z.object({ appName: z.string(), version: z.string() });
|
|
5
|
+
const categorySchema = z.object({ id: z.number(), subCategories: z.array(z.object({ id: z.number() })).nullish() });
|
|
6
|
+
const indexerSchema = z.object({
|
|
7
|
+
id: z.number(),
|
|
8
|
+
name: z.string(),
|
|
9
|
+
enable: z.boolean(),
|
|
10
|
+
protocol: z.string(),
|
|
11
|
+
capabilities: z.object({ categories: z.array(categorySchema).nullish() }).nullish(),
|
|
12
|
+
});
|
|
13
|
+
const releaseSchema = z.object({
|
|
14
|
+
guid: z.string(),
|
|
15
|
+
infoHash: z.string().nullish(),
|
|
16
|
+
title: z.string(),
|
|
17
|
+
size: z.number().nullish(),
|
|
18
|
+
indexerId: z.number(),
|
|
19
|
+
indexer: z.string().nullish(),
|
|
20
|
+
seeders: z.number().nullish(),
|
|
21
|
+
publishDate: z.string().nullish(),
|
|
22
|
+
protocol: z.string().nullish(),
|
|
23
|
+
});
|
|
24
|
+
export class ProwlarrClient {
|
|
25
|
+
baseUrl;
|
|
26
|
+
apiKey;
|
|
27
|
+
constructor(baseUrl, apiKey) {
|
|
28
|
+
this.baseUrl = baseUrl;
|
|
29
|
+
this.apiKey = apiKey;
|
|
30
|
+
}
|
|
31
|
+
request(path, opts = {}) {
|
|
32
|
+
return fetchJson(`${this.baseUrl}${path}`, { ...opts, headers: { 'X-Api-Key': this.apiKey } });
|
|
33
|
+
}
|
|
34
|
+
async systemStatus() {
|
|
35
|
+
return statusSchema.parse(await this.request('/api/v1/system/status'));
|
|
36
|
+
}
|
|
37
|
+
async indexers() {
|
|
38
|
+
return z
|
|
39
|
+
.array(indexerSchema)
|
|
40
|
+
.parse(await this.request('/api/v1/indexer'))
|
|
41
|
+
.map((i) => ({
|
|
42
|
+
id: i.id,
|
|
43
|
+
name: i.name,
|
|
44
|
+
enable: i.enable,
|
|
45
|
+
protocol: i.protocol,
|
|
46
|
+
categories: (i.capabilities?.categories ?? []).flatMap((c) => [c.id, ...(c.subCategories ?? []).map((s) => s.id)]),
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
async search(query, categories, indexerIds) {
|
|
50
|
+
const params = new URLSearchParams({ query, type: 'search', limit: '100' });
|
|
51
|
+
for (const c of categories)
|
|
52
|
+
params.append('categories', String(c));
|
|
53
|
+
for (const i of indexerIds)
|
|
54
|
+
params.append('indexerIds', String(i));
|
|
55
|
+
const value = await this.request(`/api/v1/search?${params.toString()}`, { timeoutMs: SEARCH_TIMEOUT_MS });
|
|
56
|
+
if (!Array.isArray(value))
|
|
57
|
+
return [];
|
|
58
|
+
return value.flatMap((item) => {
|
|
59
|
+
const parsed = releaseSchema.safeParse(item);
|
|
60
|
+
if (!parsed.success)
|
|
61
|
+
return [];
|
|
62
|
+
const r = parsed.data;
|
|
63
|
+
return [
|
|
64
|
+
{
|
|
65
|
+
guid: r.guid,
|
|
66
|
+
infoHash: r.infoHash ?? null,
|
|
67
|
+
title: r.title,
|
|
68
|
+
size: r.size ?? null,
|
|
69
|
+
indexerId: r.indexerId,
|
|
70
|
+
indexer: r.indexer ?? null,
|
|
71
|
+
seeders: r.seeders ?? null,
|
|
72
|
+
publishDate: r.publishDate ?? null,
|
|
73
|
+
protocol: r.protocol ?? null,
|
|
74
|
+
},
|
|
75
|
+
];
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
package/dist/commands/books.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { dirname } from 'node:path';
|
|
2
2
|
import { AudiobookshelfClient } from '../clients/audiobookshelf.js';
|
|
3
3
|
import { ChaptarrClient, } from '../clients/chaptarr.js';
|
|
4
|
+
import { ProwlarrClient } from '../clients/prowlarr.js';
|
|
4
5
|
import { SabnzbdClient } from '../clients/sabnzbd.js';
|
|
5
6
|
import { ConfigError } from '../config.js';
|
|
6
7
|
import { HttpError, describeError } from '../http.js';
|
|
@@ -9,6 +10,11 @@ const DAY_MS = 86_400_000;
|
|
|
9
10
|
const UNWANTED_REJECTION = /not wanted in profile|not enough seeders/i;
|
|
10
11
|
const SAB_FORCE_PRIORITY = 2;
|
|
11
12
|
const RUNNING_COMMAND = new Set(['queued', 'started']);
|
|
13
|
+
const NARRATOR_CHOICES = 5;
|
|
14
|
+
const AUDIO_FORMAT_RANK = { M4B: 3, FLAC: 2, MP3: 2 };
|
|
15
|
+
const AUDIOBOOK_CATEGORY = 3030;
|
|
16
|
+
const INFO_HASH = /^[A-F0-9]{40}$/;
|
|
17
|
+
const PROWLARR_SUFFIX = ' (Prowlarr)';
|
|
12
18
|
const SEARCH_TIMING = { waitMs: 120_000, pollMs: 3_000 };
|
|
13
19
|
function chaptarr(config) {
|
|
14
20
|
if (config.chaptarr === undefined)
|
|
@@ -36,11 +42,19 @@ function formatState(books) {
|
|
|
36
42
|
narrator: book?.narrator && book.narrator.length > 0 ? book.narrator : null,
|
|
37
43
|
};
|
|
38
44
|
}
|
|
45
|
+
function validationMessages(body) {
|
|
46
|
+
if (!Array.isArray(body))
|
|
47
|
+
return [];
|
|
48
|
+
return body.flatMap((b) => typeof b === 'object' && b !== null && 'errorMessage' in b && typeof b.errorMessage === 'string' ? [b.errorMessage] : []);
|
|
49
|
+
}
|
|
39
50
|
function httpDetail(err) {
|
|
40
51
|
if (err instanceof HttpError) {
|
|
41
52
|
const body = err.body;
|
|
42
53
|
if (typeof body === 'string' && body.length > 0)
|
|
43
54
|
return body.slice(0, 300);
|
|
55
|
+
const messages = validationMessages(body);
|
|
56
|
+
if (messages.length > 0)
|
|
57
|
+
return messages.join('; ').slice(0, 300);
|
|
44
58
|
if (typeof body === 'object' && body !== null && 'message' in body && typeof body.message === 'string') {
|
|
45
59
|
return body.message.slice(0, 300);
|
|
46
60
|
}
|
|
@@ -95,13 +109,84 @@ export function plainEdition(editions) {
|
|
|
95
109
|
current.title.startsWith(`${e.title} (`));
|
|
96
110
|
return plain.sort((a, b) => a.title.length - b.title.length)[0] ?? null;
|
|
97
111
|
}
|
|
112
|
+
function monitoring(editions, editionId) {
|
|
113
|
+
return editions.map((e) => ({ ...e, monitored: e.id === editionId }));
|
|
114
|
+
}
|
|
98
115
|
async function ensureBook(client, lookup, format, opts) {
|
|
99
116
|
const local = preferred(lookup[format]);
|
|
100
117
|
const id = local?.id ?? (await client.addBook(lookup, format, await client.formatDefaults(), opts));
|
|
101
|
-
|
|
102
|
-
|
|
118
|
+
let editions = await client.editions(id);
|
|
119
|
+
const chosen = opts.editionId === undefined ? undefined : editions.find((e) => e.id === opts.editionId);
|
|
120
|
+
if (opts.editionId !== undefined && chosen === undefined) {
|
|
121
|
+
throw new Error(`edition ${opts.editionId} is not an edition of ${lookup.title}`);
|
|
122
|
+
}
|
|
123
|
+
if (chosen !== undefined && !chosen.monitored) {
|
|
124
|
+
await client.monitorEdition(id, chosen.id);
|
|
125
|
+
editions = monitoring(editions, chosen.id);
|
|
126
|
+
}
|
|
127
|
+
const plain = plainEdition(editions);
|
|
128
|
+
if (plain !== null) {
|
|
103
129
|
await client.monitorEdition(id, plain.id);
|
|
104
|
-
|
|
130
|
+
editions = monitoring(editions, plain.id);
|
|
131
|
+
}
|
|
132
|
+
return { id, editions };
|
|
133
|
+
}
|
|
134
|
+
function narratorKey(narrators) {
|
|
135
|
+
return narrators
|
|
136
|
+
.map((n) => n.toLowerCase())
|
|
137
|
+
.sort()
|
|
138
|
+
.join('|');
|
|
139
|
+
}
|
|
140
|
+
function releaseYear(date) {
|
|
141
|
+
if (date === null)
|
|
142
|
+
return null;
|
|
143
|
+
const time = Date.parse(date);
|
|
144
|
+
return Number.isNaN(time) ? null : new Date(time).getUTCFullYear();
|
|
145
|
+
}
|
|
146
|
+
function editionOrder(a, b) {
|
|
147
|
+
return ((b.votes ?? 0) - (a.votes ?? 0) ||
|
|
148
|
+
Number(b.durationSeconds !== null) - Number(a.durationSeconds !== null) ||
|
|
149
|
+
(b.releaseDate ?? '').localeCompare(a.releaseDate ?? ''));
|
|
150
|
+
}
|
|
151
|
+
export function narratorChoices(editions, limit = NARRATOR_CHOICES) {
|
|
152
|
+
const current = editions.find((e) => e.monitored);
|
|
153
|
+
const currentKey = current === undefined ? null : narratorKey(current.narrators);
|
|
154
|
+
const groups = new Map();
|
|
155
|
+
for (const e of editions) {
|
|
156
|
+
if (e.narrators.length === 0)
|
|
157
|
+
continue;
|
|
158
|
+
const key = narratorKey(e.narrators);
|
|
159
|
+
groups.set(key, [...(groups.get(key) ?? []), e]);
|
|
160
|
+
}
|
|
161
|
+
return [...groups.entries()]
|
|
162
|
+
.flatMap(([key, group]) => {
|
|
163
|
+
const best = [...group].sort(editionOrder)[0];
|
|
164
|
+
const duration = group.find((e) => e.durationSeconds !== null)?.durationSeconds ?? null;
|
|
165
|
+
return best === undefined ? [] : [{ key, best, duration }];
|
|
166
|
+
})
|
|
167
|
+
.sort((a, b) => editionOrder(a.best, b.best))
|
|
168
|
+
.slice(0, limit)
|
|
169
|
+
.map(({ key, best, duration }) => ({
|
|
170
|
+
edition_id: best.id,
|
|
171
|
+
narrators: best.narrators,
|
|
172
|
+
year: releaseYear(best.releaseDate),
|
|
173
|
+
duration_seconds: best.durationSeconds ?? duration,
|
|
174
|
+
rating: best.rating,
|
|
175
|
+
votes: best.votes,
|
|
176
|
+
language: best.language,
|
|
177
|
+
chosen: key === currentKey,
|
|
178
|
+
}));
|
|
179
|
+
}
|
|
180
|
+
function narrationOf(editions) {
|
|
181
|
+
const current = editions.find((e) => e.monitored);
|
|
182
|
+
if (current === undefined)
|
|
183
|
+
return { narrators: [], seconds: null };
|
|
184
|
+
const key = narratorKey(current.narrators);
|
|
185
|
+
const seconds = current.durationSeconds ??
|
|
186
|
+
editions.find((e) => e.durationSeconds !== null && current.narrators.length > 0 && narratorKey(e.narrators) === key)
|
|
187
|
+
?.durationSeconds ??
|
|
188
|
+
null;
|
|
189
|
+
return { narrators: current.narrators, seconds };
|
|
105
190
|
}
|
|
106
191
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
107
192
|
async function searchOutcome(client, bookId, timing) {
|
|
@@ -153,7 +238,7 @@ export async function addBook(config, foreignBookId, format, timing = SEARCH_TIM
|
|
|
153
238
|
result = { book_id: local.id, title: lookup.title, status: 'downloading', detail: null };
|
|
154
239
|
}
|
|
155
240
|
else {
|
|
156
|
-
const id = await ensureBook(client, lookup, format, { monitored: true, search: false });
|
|
241
|
+
const { id } = await ensureBook(client, lookup, format, { monitored: true, search: false });
|
|
157
242
|
await client.setMonitored([id], true);
|
|
158
243
|
const title = (await client.book(id)).title;
|
|
159
244
|
result = { book_id: id, title, ...(await searchOutcome(client, id, timing)) };
|
|
@@ -171,12 +256,117 @@ function ageDays(publishDate, now) {
|
|
|
171
256
|
const time = Date.parse(publishDate);
|
|
172
257
|
return Number.isNaN(time) ? null : Math.max(0, Math.floor((now - time) / DAY_MS));
|
|
173
258
|
}
|
|
174
|
-
|
|
175
|
-
return
|
|
259
|
+
function words(text) {
|
|
260
|
+
return text
|
|
261
|
+
.normalize('NFKD')
|
|
262
|
+
.replace(/\p{M}/gu, '')
|
|
263
|
+
.toLowerCase()
|
|
264
|
+
.split(/[^a-z0-9]+/)
|
|
265
|
+
.filter((w) => w.length > 0);
|
|
266
|
+
}
|
|
267
|
+
export function narratorMatch(title, narrators) {
|
|
268
|
+
const inTitle = new Set(words(title));
|
|
269
|
+
return narrators.some((name) => {
|
|
270
|
+
const surname = words(name).at(-1);
|
|
271
|
+
return surname !== undefined && surname.length >= 3 && inTitle.has(surname);
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
export function estimateKbps(size, seconds) {
|
|
275
|
+
if (size === null || seconds === null || seconds <= 0)
|
|
276
|
+
return null;
|
|
277
|
+
return Math.round((size * 8) / seconds / 1000);
|
|
278
|
+
}
|
|
279
|
+
export function fromChaptarr(releases) {
|
|
280
|
+
return releases.map((r) => ({ ...r, source: 'chaptarr', magnet: null }));
|
|
281
|
+
}
|
|
282
|
+
function titleQuality(title) {
|
|
283
|
+
const inTitle = new Set(words(title));
|
|
284
|
+
return ['M4B', 'FLAC', 'MP3'].find((q) => inTitle.has(q.toLowerCase())) ?? null;
|
|
285
|
+
}
|
|
286
|
+
export function searchTitle(title) {
|
|
287
|
+
return title.split(':')[0]?.replace(/\s*\([^)]*\)\s*$/, '').trim() ?? title;
|
|
288
|
+
}
|
|
289
|
+
export function fromProwlarr(releases, title) {
|
|
290
|
+
const needed = words(searchTitle(title)).filter((w) => w.length >= 3);
|
|
291
|
+
return releases.flatMap((r) => {
|
|
292
|
+
const hash = r.infoHash?.toUpperCase() ?? '';
|
|
293
|
+
const inTitle = new Set(words(r.title));
|
|
294
|
+
if (!INFO_HASH.test(hash) || (r.seeders ?? 0) <= 0 || !needed.every((w) => inTitle.has(w)))
|
|
295
|
+
return [];
|
|
296
|
+
const magnet = r.guid.startsWith('magnet:') ? r.guid : `magnet:?xt=urn:btih:${hash}&dn=${encodeURIComponent(r.title)}`;
|
|
297
|
+
return [
|
|
298
|
+
{
|
|
299
|
+
guid: hash,
|
|
300
|
+
indexerId: r.indexerId,
|
|
301
|
+
title: r.title,
|
|
302
|
+
size: r.size,
|
|
303
|
+
indexer: r.indexer,
|
|
304
|
+
protocol: r.protocol,
|
|
305
|
+
seeders: r.seeders,
|
|
306
|
+
publishDate: r.publishDate,
|
|
307
|
+
quality: titleQuality(r.title),
|
|
308
|
+
rejections: [],
|
|
309
|
+
source: 'prowlarr',
|
|
310
|
+
magnet,
|
|
311
|
+
},
|
|
312
|
+
];
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
async function prowlarrReleases(config, client, title) {
|
|
316
|
+
if (config.prowlarr === undefined)
|
|
317
|
+
return [];
|
|
318
|
+
const prowlarr = new ProwlarrClient(config.prowlarr.url, config.prowlarr.apiKey);
|
|
319
|
+
const synced = new Set(await client.indexerNames());
|
|
320
|
+
const ids = (await prowlarr.indexers())
|
|
321
|
+
.filter((i) => i.enable &&
|
|
322
|
+
i.protocol === 'torrent' &&
|
|
323
|
+
i.categories.includes(AUDIOBOOK_CATEGORY) &&
|
|
324
|
+
!synced.has(`${i.name}${PROWLARR_SUFFIX}`))
|
|
325
|
+
.map((i) => i.id);
|
|
326
|
+
if (ids.length === 0)
|
|
327
|
+
return [];
|
|
328
|
+
return fromProwlarr(await prowlarr.search(searchTitle(title), [AUDIOBOOK_CATEGORY], ids), title);
|
|
329
|
+
}
|
|
330
|
+
async function extraReleases(config, client, title, format, warnings) {
|
|
331
|
+
if (format !== 'audiobook')
|
|
332
|
+
return [];
|
|
333
|
+
try {
|
|
334
|
+
return await prowlarrReleases(config, client, title);
|
|
335
|
+
}
|
|
336
|
+
catch (err) {
|
|
337
|
+
warnings.push(`Prowlarr search failed — Chaptarr's releases only (${describeError(err)})`);
|
|
338
|
+
return [];
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function pushOf(c, magnet, now) {
|
|
342
|
+
return {
|
|
343
|
+
title: c.title,
|
|
344
|
+
magnet,
|
|
345
|
+
size: c.size,
|
|
346
|
+
publishDate: c.publishDate ?? new Date(now).toISOString(),
|
|
347
|
+
indexer: c.indexer,
|
|
348
|
+
seeders: c.seeders,
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
export function selectReleases(releases, limit, now = Date.now(), narration = null) {
|
|
352
|
+
const wanted = releases
|
|
176
353
|
.filter((r) => !r.rejections.some((reason) => UNWANTED_REJECTION.test(reason)))
|
|
177
|
-
.
|
|
178
|
-
|
|
354
|
+
.map((r, order) => ({
|
|
355
|
+
r,
|
|
356
|
+
order,
|
|
357
|
+
narrator_match: narration !== null && narratorMatch(r.title, narration.narrators),
|
|
358
|
+
kbps: narration === null ? null : estimateKbps(r.size, narration.seconds),
|
|
359
|
+
format: r.quality === null ? 0 : (AUDIO_FORMAT_RANK[r.quality] ?? 1),
|
|
360
|
+
}));
|
|
361
|
+
const ranked = narration === null
|
|
362
|
+
? wanted
|
|
363
|
+
: [...wanted].sort((a, b) => Number(b.narrator_match) - Number(a.narrator_match) ||
|
|
364
|
+
b.format - a.format ||
|
|
365
|
+
(b.kbps ?? -1) - (a.kbps ?? -1) ||
|
|
366
|
+
a.order - b.order);
|
|
367
|
+
return ranked.slice(0, limit).map(({ r, narrator_match, kbps }, i) => ({
|
|
179
368
|
rank: i + 1,
|
|
369
|
+
source: r.source,
|
|
180
370
|
title: r.title,
|
|
181
371
|
size: r.size,
|
|
182
372
|
quality: r.quality,
|
|
@@ -187,6 +377,8 @@ export function selectReleases(releases, limit, now = Date.now()) {
|
|
|
187
377
|
guid: r.guid,
|
|
188
378
|
indexer_id: r.indexerId,
|
|
189
379
|
rejections: r.rejections,
|
|
380
|
+
narrator_match,
|
|
381
|
+
kbps,
|
|
190
382
|
}));
|
|
191
383
|
}
|
|
192
384
|
export async function bookReleases(config, foreignBookId, format, opts) {
|
|
@@ -194,14 +386,157 @@ export async function bookReleases(config, foreignBookId, format, opts) {
|
|
|
194
386
|
const lookup = await findFormat(client, foreignBookId, format);
|
|
195
387
|
if (lookup === null)
|
|
196
388
|
throw new Error(`no book ${foreignBookId} in Chaptarr's lookup`);
|
|
197
|
-
const id = await ensureBook(client, lookup, format, {
|
|
389
|
+
const { id, editions } = await ensureBook(client, lookup, format, {
|
|
390
|
+
monitored: false,
|
|
391
|
+
search: false,
|
|
392
|
+
editionId: opts.editionId,
|
|
393
|
+
});
|
|
198
394
|
const title = (await client.book(id)).title;
|
|
199
|
-
const
|
|
395
|
+
const narration = format === 'audiobook' ? narrationOf(editions) : null;
|
|
396
|
+
const limit = opts.maxEntries ?? config.defaults.maxEntries;
|
|
397
|
+
const warnings = [];
|
|
398
|
+
const [found, extra] = await Promise.all([
|
|
399
|
+
client.releases(id),
|
|
400
|
+
extraReleases(config, client, title, format, warnings),
|
|
401
|
+
]);
|
|
402
|
+
const releases = selectReleases([...fromChaptarr(found), ...extra], limit, Date.now(), narration);
|
|
200
403
|
return {
|
|
201
|
-
output: {
|
|
404
|
+
output: {
|
|
405
|
+
foreign_book_id: foreignBookId,
|
|
406
|
+
format,
|
|
407
|
+
book_id: id,
|
|
408
|
+
title,
|
|
409
|
+
narrators: narration?.narrators ?? [],
|
|
410
|
+
duration_seconds: narration?.seconds ?? null,
|
|
411
|
+
releases,
|
|
412
|
+
},
|
|
413
|
+
warnings,
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
export async function bookNarrators(config, foreignBookId, opts) {
|
|
417
|
+
const client = chaptarr(config);
|
|
418
|
+
const lookup = await findFormat(client, foreignBookId, 'audiobook');
|
|
419
|
+
if (lookup === null)
|
|
420
|
+
throw new Error(`no book ${foreignBookId} in Chaptarr's lookup`);
|
|
421
|
+
const { id, editions } = await ensureBook(client, lookup, 'audiobook', { monitored: false, search: false });
|
|
422
|
+
const title = (await client.book(id)).title;
|
|
423
|
+
return {
|
|
424
|
+
output: {
|
|
425
|
+
foreign_book_id: foreignBookId,
|
|
426
|
+
book_id: id,
|
|
427
|
+
title,
|
|
428
|
+
narrators: narratorChoices(editions, opts.maxEntries ?? NARRATOR_CHOICES),
|
|
429
|
+
},
|
|
202
430
|
warnings: [],
|
|
203
431
|
};
|
|
204
432
|
}
|
|
433
|
+
export async function bestBook(config, foreignBookId, format, opts) {
|
|
434
|
+
const client = chaptarr(config);
|
|
435
|
+
const warnings = [];
|
|
436
|
+
const base = { foreign_book_id: foreignBookId, format };
|
|
437
|
+
let result;
|
|
438
|
+
try {
|
|
439
|
+
const lookup = await findFormat(client, foreignBookId, format);
|
|
440
|
+
const local = lookup === null ? null : preferred(lookup[format]);
|
|
441
|
+
if (lookup === null) {
|
|
442
|
+
result = { book_id: null, title: null, status: 'not_found', detail: null, release: null };
|
|
443
|
+
}
|
|
444
|
+
else if (local?.hasFiles === true) {
|
|
445
|
+
result = { book_id: local.id, title: lookup.title, status: 'already_exists', detail: null, release: null };
|
|
446
|
+
}
|
|
447
|
+
else if (local !== null && (await client.queuedBookIds()).has(local.id)) {
|
|
448
|
+
result = { book_id: local.id, title: lookup.title, status: 'downloading', detail: null, release: null };
|
|
449
|
+
}
|
|
450
|
+
else {
|
|
451
|
+
const { id, editions } = await ensureBook(client, lookup, format, {
|
|
452
|
+
monitored: false,
|
|
453
|
+
search: false,
|
|
454
|
+
editionId: opts.editionId,
|
|
455
|
+
});
|
|
456
|
+
const title = (await client.book(id)).title;
|
|
457
|
+
const narration = format === 'audiobook' ? narrationOf(editions) : null;
|
|
458
|
+
const [found, extra] = await Promise.all([
|
|
459
|
+
client.releases(id),
|
|
460
|
+
extraReleases(config, client, title, format, warnings),
|
|
461
|
+
]);
|
|
462
|
+
const candidates = [...fromChaptarr(found), ...extra];
|
|
463
|
+
await client.setMonitored([id], true);
|
|
464
|
+
const now = Date.now();
|
|
465
|
+
const taken = await takeFirst(client, candidates, selectReleases(candidates, candidates.length, now, narration), now);
|
|
466
|
+
if (taken === null) {
|
|
467
|
+
result = { book_id: id, title, status: 'nothing_found', detail: null, release: null };
|
|
468
|
+
}
|
|
469
|
+
else {
|
|
470
|
+
const release = {
|
|
471
|
+
title: taken.pick.title,
|
|
472
|
+
quality: taken.pick.quality,
|
|
473
|
+
kbps: taken.pick.kbps,
|
|
474
|
+
narrator_match: taken.pick.narrator_match,
|
|
475
|
+
};
|
|
476
|
+
result = { book_id: id, title, status: 'downloading', detail: filedUnder(taken.bookId, id), release };
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
catch (err) {
|
|
481
|
+
result = { book_id: null, title: null, status: 'error', detail: httpDetail(err), release: null };
|
|
482
|
+
}
|
|
483
|
+
const sabnzbd_paused = await sabPausedFor(config, client, format, warnings);
|
|
484
|
+
return { output: { ...base, ...result, sabnzbd_paused }, warnings };
|
|
485
|
+
}
|
|
486
|
+
function filedUnder(filed, bookId) {
|
|
487
|
+
return filed !== null && filed !== bookId ? `Chaptarr filed it under its book ${filed}` : null;
|
|
488
|
+
}
|
|
489
|
+
async function takeFirst(client, candidates, ranked, now) {
|
|
490
|
+
for (const pick of ranked.filter((r) => r.rejections.length === 0)) {
|
|
491
|
+
if (pick.source === 'chaptarr') {
|
|
492
|
+
await client.grab(pick.guid, pick.indexer_id);
|
|
493
|
+
return { pick, bookId: null };
|
|
494
|
+
}
|
|
495
|
+
const candidate = candidates.find((c) => c.source === 'prowlarr' && c.guid === pick.guid);
|
|
496
|
+
if (candidate?.magnet == null)
|
|
497
|
+
continue;
|
|
498
|
+
try {
|
|
499
|
+
const pushed = await client.push(pushOf(candidate, candidate.magnet, now));
|
|
500
|
+
if (pushed.approved)
|
|
501
|
+
return { pick, bookId: pushed.bookId };
|
|
502
|
+
}
|
|
503
|
+
catch (err) {
|
|
504
|
+
if (!(err instanceof HttpError && err.status === 400))
|
|
505
|
+
throw err;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return null;
|
|
509
|
+
}
|
|
510
|
+
export async function pushRelease(config, bookId, infoHash) {
|
|
511
|
+
const client = chaptarr(config);
|
|
512
|
+
if (config.prowlarr === undefined)
|
|
513
|
+
throw new ConfigError("Prowlarr is not configured — run 'trendarr init'.");
|
|
514
|
+
let title = null;
|
|
515
|
+
let result;
|
|
516
|
+
try {
|
|
517
|
+
const book = await client.book(bookId);
|
|
518
|
+
title = book.title;
|
|
519
|
+
await client.setMonitored([bookId], true);
|
|
520
|
+
const hash = infoHash.toUpperCase();
|
|
521
|
+
const candidate = (await prowlarrReleases(config, client, book.title)).find((c) => c.guid === hash);
|
|
522
|
+
if (candidate?.magnet == null) {
|
|
523
|
+
result = { status: 'error', detail: "the release is no longer in Prowlarr's results" };
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
const pushed = await client.push(pushOf(candidate, candidate.magnet, Date.now()));
|
|
527
|
+
result = pushed.approved
|
|
528
|
+
? { status: 'grabbed', detail: filedUnder(pushed.bookId, bookId) }
|
|
529
|
+
: { status: 'rejected', detail: pushed.rejections.join('; ') || null };
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
catch (err) {
|
|
533
|
+
result =
|
|
534
|
+
err instanceof HttpError && err.status === 400
|
|
535
|
+
? { status: 'rejected', detail: `Chaptarr cannot read the release name (${httpDetail(err)})` }
|
|
536
|
+
: { status: 'error', detail: httpDetail(err) };
|
|
537
|
+
}
|
|
538
|
+
return { output: { book_id: bookId, title, ...result, sabnzbd_paused: null }, warnings: [] };
|
|
539
|
+
}
|
|
205
540
|
export async function grabRelease(config, bookId, guid, indexerId) {
|
|
206
541
|
const client = chaptarr(config);
|
|
207
542
|
const warnings = [];
|
package/dist/commands/init.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { cancel, confirm, intro, isCancel, log, outro, select, spinner, text } from '@clack/prompts';
|
|
2
2
|
import { AudiobookshelfClient } from '../clients/audiobookshelf.js';
|
|
3
3
|
import { ChaptarrClient } from '../clients/chaptarr.js';
|
|
4
|
+
import { ProwlarrClient } from '../clients/prowlarr.js';
|
|
4
5
|
import { OmdbClient } from '../clients/omdb.js';
|
|
5
6
|
import { RadarrClient } from '../clients/radarr.js';
|
|
6
7
|
import { SonarrClient } from '../clients/sonarr.js';
|
|
@@ -167,7 +168,13 @@ export async function runInit() {
|
|
|
167
168
|
const ok = await validated('Audiobookshelf', () => new AudiobookshelfClient(url, apiKey).ereaderDevices());
|
|
168
169
|
return ok === null ? null : { url, apiKey };
|
|
169
170
|
});
|
|
170
|
-
|
|
171
|
+
const prowlarr = await askUntilValid(async () => {
|
|
172
|
+
const url = (await ask('Prowlarr URL for indexers Chaptarr refuses (e.g. http://localhost:9696)', prior.prowlarr?.url)).replace(/\/+$/, '');
|
|
173
|
+
const apiKey = await ask('Prowlarr API key (Settings > General > Security)', prior.prowlarr?.apiKey);
|
|
174
|
+
const ok = await validated('Prowlarr', () => new ProwlarrClient(url, apiKey).systemStatus());
|
|
175
|
+
return ok === null ? null : { url, apiKey };
|
|
176
|
+
});
|
|
177
|
+
books = { chaptarr, audiobookshelf, prowlarr };
|
|
171
178
|
}
|
|
172
179
|
const config = {
|
|
173
180
|
tmdb,
|
package/dist/config.js
CHANGED
|
@@ -18,6 +18,7 @@ export const configSchema = z.object({
|
|
|
18
18
|
defaults: z.object({ maxEntries: z.number().int().positive() }),
|
|
19
19
|
chaptarr: serviceSchema.optional(),
|
|
20
20
|
audiobookshelf: serviceSchema.optional(),
|
|
21
|
+
prowlarr: serviceSchema.optional(),
|
|
21
22
|
});
|
|
22
23
|
export class ConfigError extends Error {
|
|
23
24
|
constructor(message) {
|
package/dist/format.js
CHANGED
|
@@ -126,17 +126,45 @@ export function renderBookAdd(output) {
|
|
|
126
126
|
function megabytes(size) {
|
|
127
127
|
return size === null ? '-' : `${Math.round(size / 1_048_576)} MB`;
|
|
128
128
|
}
|
|
129
|
+
function hours(seconds) {
|
|
130
|
+
if (seconds === null)
|
|
131
|
+
return '-';
|
|
132
|
+
const minutes = Math.round(seconds / 60);
|
|
133
|
+
return `${Math.floor(minutes / 60)} h ${String(minutes % 60).padStart(2, '0')}`;
|
|
134
|
+
}
|
|
129
135
|
export function renderReleasesTable(output) {
|
|
130
|
-
const
|
|
136
|
+
const narration = output.narrators.length > 0 ? ` · ${output.narrators.join(', ')} · ${hours(output.duration_seconds)}` : '';
|
|
137
|
+
const title = `${output.title} [${output.format}] book ${output.book_id}${narration}`;
|
|
131
138
|
if (output.releases.length === 0)
|
|
132
139
|
return `${title}\nNo releases.`;
|
|
133
|
-
const header = `${cell('#', 3)} ${cell('RELEASE', 60)} ${cell('SIZE', 9)} ${cell('QUALITY', 13)} ${cell('SEEDS', 5)} AGE`;
|
|
134
|
-
const rows = output.releases.map((r) => `${cell(String(r.rank), 3)} ${cell(r.title
|
|
135
|
-
|
|
140
|
+
const header = `${cell('#', 3)} ${cell('RELEASE', 60)} ${cell('SIZE', 9)} ${cell('QUALITY', 13)} ${cell('KBPS', 5)} ${cell('SEEDS', 5)} AGE`;
|
|
141
|
+
const rows = output.releases.map((r) => `${cell(String(r.rank), 3)} ${cell(`${r.narrator_match ? '* ' : ''}${r.source === 'prowlarr' ? '^ ' : ''}${r.title}`, 60)} ${cell(megabytes(r.size), 9)} ${cell(dash(r.quality), 13)} ${cell(dash(r.kbps), 5)} ${cell(r.protocol === 'usenet' ? 'nzb' : dash(r.seeders), 5)} ${r.age_days === null ? '-' : `${r.age_days}d`}`);
|
|
142
|
+
const notes = [
|
|
143
|
+
output.releases.some((r) => r.narrator_match) ? '* names the narrator' : null,
|
|
144
|
+
output.releases.some((r) => r.source === 'prowlarr') ? '^ from Prowlarr: books push <book_id> <guid>' : null,
|
|
145
|
+
].filter((n) => n !== null);
|
|
146
|
+
return [title, pc.bold(header), ...rows, ...notes].join('\n');
|
|
147
|
+
}
|
|
148
|
+
export function renderNarrators(output) {
|
|
149
|
+
const title = `${output.title} [audiobook] book ${output.book_id}`;
|
|
150
|
+
if (output.narrators.length === 0)
|
|
151
|
+
return `${title}\nNo narrator known.`;
|
|
152
|
+
const header = `${cell('EDITION', 8)} ${cell('NARRATORS', 40)} ${cell('YEAR', 4)} ${cell('LENGTH', 8)} ${cell('RATING', 6)} VOTES`;
|
|
153
|
+
const rows = output.narrators.map((n) => `${cell(String(n.edition_id), 8)} ${cell(`${n.chosen ? '* ' : ''}${n.narrators.join(', ')}`, 40)} ${cell(dash(n.year), 4)} ${cell(hours(n.duration_seconds), 8)} ${cell(n.rating === null ? '-' : n.rating.toFixed(2), 6)} ${dash(n.votes)}`);
|
|
154
|
+
return [title, pc.bold(header), ...rows, '* monitored now'].join('\n');
|
|
155
|
+
}
|
|
156
|
+
export function renderBookBest(output) {
|
|
157
|
+
const detail = output.detail === null ? '' : ` (${output.detail})`;
|
|
158
|
+
const line = `${output.title ?? output.foreign_book_id} [${output.format}] ${statusColor(output.status, ['downloading'])}${detail}`;
|
|
159
|
+
const release = output.release === null
|
|
160
|
+
? []
|
|
161
|
+
: [`Release: ${output.release.title} (${dash(output.release.quality)}, ${dash(output.release.kbps)} kbps)`];
|
|
162
|
+
return [line, ...release, '', sabLine(output.sabnzbd_paused)].join('\n');
|
|
136
163
|
}
|
|
137
164
|
export function renderBookGrab(output) {
|
|
138
165
|
const detail = output.detail === null ? '' : ` (${output.detail})`;
|
|
139
|
-
|
|
166
|
+
const line = `${output.title ?? `book ${output.book_id}`} ${statusColor(output.status, ['grabbed'])}${detail}`;
|
|
167
|
+
return output.sabnzbd_paused === null ? line : [line, '', sabLine(output.sabnzbd_paused)].join('\n');
|
|
140
168
|
}
|
|
141
169
|
export function renderBookSend(output) {
|
|
142
170
|
const detail = output.detail === null ? '' : ` (${output.detail})`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astrofoundry/trendarr",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "TMDB trending → OMDb ratings → Radarr/Sonarr adds → SABnzbd control, from the terminal",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "tsc -p tsconfig.build.json && chmod +x dist/cli.js",
|