@astrofoundry/trendarr 0.13.0 → 0.15.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 +4 -2
- package/dist/cli.js +71 -6
- package/dist/clients/audiobookshelf.js +8 -1
- package/dist/clients/chaptarr.js +23 -0
- package/dist/clients/prowlarr.js +78 -0
- package/dist/commands/books.js +182 -11
- package/dist/commands/init.js +8 -1
- package/dist/config.js +1 -0
- package/dist/format.js +15 -4
- 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
|
|
|
@@ -24,16 +24,18 @@ trendarr books add <bookId> --format audiobook|ebook [--json]
|
|
|
24
24
|
trendarr books narrators <bookId> [--max-entries 5] [--json]
|
|
25
25
|
trendarr books releases <bookId> --format audiobook|ebook [--edition <id>] [--max-entries 10] [--json]
|
|
26
26
|
trendarr books grab <chaptarrId> <guid> <indexerId> [--json]
|
|
27
|
+
trendarr books push <chaptarrId> <infoHash> [--json]
|
|
27
28
|
trendarr books best <bookId> --format audiobook|ebook [--edition <id>] [--json]
|
|
28
29
|
trendarr books ready <chaptarrId> [--json]
|
|
29
30
|
trendarr books send <chaptarrId> <device> [--json]
|
|
30
31
|
trendarr books ebooks [--json]
|
|
32
|
+
trendarr books audiobooks [--json]
|
|
31
33
|
trendarr books send-item <itemId> <device> [--json]
|
|
32
34
|
```
|
|
33
35
|
|
|
34
36
|
`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).
|
|
35
37
|
|
|
36
|
-
`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. `best` grabs 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.
|
|
38
|
+
`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. `audiobooks` lists every audiobook in Audiobookshelf, newest first, with narrator and length.
|
|
37
39
|
|
|
38
40
|
## Development
|
|
39
41
|
|
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, bestBook, bookNarrators, bookReady, bookReleases, grabRelease, listEbooks, searchBooks, sendBook, sendItem, } from './commands/books.js';
|
|
5
|
+
import { addBook, bestBook, bookNarrators, bookReady, bookReleases, grabRelease, pushRelease, listAudiobooks, 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, renderBookBest, renderBookGrab, renderBookReady, renderBookSearchTable, renderBookSend, renderEbookList, renderItemSend, renderNarrators, renderReleasesTable, renderRecommendTable, renderSabStatus, renderSearchDiscord, renderSearchTable, renderTrendingDiscord, renderTrendingTable, toJson, } from './format.js';
|
|
12
|
+
import { renderAddTable, renderBookAdd, renderBookBest, renderAudiobookList, 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,7 +325,8 @@ 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
|
|
|
@@ -330,10 +336,12 @@ Actions:
|
|
|
330
336
|
narrators <bookId> List the audiobook narrations, most rated first.
|
|
331
337
|
releases <bookId> --format <f> List the releases you can pick from, best first for audiobooks.
|
|
332
338
|
grab <chaptarrId> <guid> <indexerId> Download one release from that list.
|
|
339
|
+
push <chaptarrId> <infoHash> Download one Prowlarr release from that list through Chaptarr.
|
|
333
340
|
best <bookId> --format <f> Download the first release of that list Chaptarr accepts.
|
|
334
341
|
ready <chaptarrId> Whether the book has a file and, for an ebook, is in Audiobookshelf.
|
|
335
342
|
send <chaptarrId> <device> Email the ebook to a Kindle through Audiobookshelf.
|
|
336
343
|
ebooks List every ebook in Audiobookshelf, newest first, with the Kindles.
|
|
344
|
+
audiobooks List every audiobook in Audiobookshelf, newest first.
|
|
337
345
|
send-item <itemId> <device> Email one Audiobookshelf ebook item to a Kindle.`);
|
|
338
346
|
books
|
|
339
347
|
.command('search')
|
|
@@ -445,11 +453,15 @@ Behavior: adds the book unmonitored when Chaptarr does not have it, monitors --e
|
|
|
445
453
|
releases come best first: the monitored narrator's surname in the name, then M4B over MP3 and FLAC
|
|
446
454
|
over other formats, then the higher estimated bitrate, then Chaptarr's order. Grab one within
|
|
447
455
|
30 minutes, while Chaptarr still caches the search.
|
|
456
|
+
With "prowlarr" configured, audiobooks also get the torrent releases of Prowlarr indexers that
|
|
457
|
+
Chaptarr does not have (Chaptarr refuses some public trackers), searched by title in category 3030.
|
|
458
|
+
Their quality comes from the name, they carry no rejections, and books push downloads them.
|
|
448
459
|
|
|
449
460
|
Output (--json): { foreign_book_id, format, book_id, title, narrators, duration_seconds,
|
|
450
461
|
releases: BookRelease[] }
|
|
451
|
-
BookRelease: { rank, title, size, quality, protocol, indexer, seeders, age_days, guid,
|
|
452
|
-
rejections, narrator_match, kbps } —
|
|
462
|
+
BookRelease: { rank, source, title, size, quality, protocol, indexer, seeders, age_days, guid,
|
|
463
|
+
indexer_id, rejections, narrator_match, kbps } — source is chaptarr or prowlarr; for prowlarr, guid
|
|
464
|
+
is the info hash for books push; size in bytes; rejections are Chaptarr's reasons it would not
|
|
453
465
|
pick it by itself; kbps is size divided by the edition's length (null without a length or for
|
|
454
466
|
ebooks), so a release holding several books shows too high a value.
|
|
455
467
|
|
|
@@ -496,6 +508,35 @@ Examples:
|
|
|
496
508
|
fail(err);
|
|
497
509
|
}
|
|
498
510
|
});
|
|
511
|
+
books
|
|
512
|
+
.command('push')
|
|
513
|
+
.description('download one Prowlarr release from books releases through Chaptarr')
|
|
514
|
+
.argument('<chaptarrId>', 'book_id from books releases', parsePositiveInt)
|
|
515
|
+
.argument('<infoHash>', 'guid of a release whose source is prowlarr', parseInfoHash)
|
|
516
|
+
.option('--json', 'output JSON')
|
|
517
|
+
.addHelpText('after', `
|
|
518
|
+
Behavior: monitors the book, searches Prowlarr again as books releases does, and pushes the release
|
|
519
|
+
with that info hash to Chaptarr, which checks it like an RSS release and sends it to the torrent
|
|
520
|
+
client when it accepts it. Chaptarr files it under the monitored book it matches by name.
|
|
521
|
+
|
|
522
|
+
Output (--json): { book_id, title, status, detail, sabnzbd_paused }
|
|
523
|
+
status is grabbed, rejected (detail: Chaptarr's reasons), or error. sabnzbd_paused is null.
|
|
524
|
+
Exit code 1 unless grabbed.
|
|
525
|
+
|
|
526
|
+
Examples:
|
|
527
|
+
trendarr books push 3 458459567D82D08F32407044A4ABD00AEE9D0D84`)
|
|
528
|
+
.action(async (chaptarrId, infoHash, opts) => {
|
|
529
|
+
try {
|
|
530
|
+
const { output, warnings } = await pushRelease(loadConfig(), chaptarrId, infoHash);
|
|
531
|
+
printWarnings(warnings);
|
|
532
|
+
process.stdout.write(`${opts.json === true ? toJson(output) : renderBookGrab(output)}\n`);
|
|
533
|
+
if (output.status !== 'grabbed')
|
|
534
|
+
process.exitCode = 1;
|
|
535
|
+
}
|
|
536
|
+
catch (err) {
|
|
537
|
+
fail(err);
|
|
538
|
+
}
|
|
539
|
+
});
|
|
499
540
|
books
|
|
500
541
|
.command('best')
|
|
501
542
|
.description('download the best release Chaptarr accepts')
|
|
@@ -505,7 +546,8 @@ books
|
|
|
505
546
|
.option('--json', 'output JSON')
|
|
506
547
|
.addHelpText('after', `
|
|
507
548
|
Behavior: does what books releases does, then monitors the book and grabs the first release in that
|
|
508
|
-
order without rejections
|
|
549
|
+
order without rejections; a Prowlarr release is pushed as books push does, and when Chaptarr
|
|
550
|
+
refuses it the next one is tried. When none is taken, the book stays monitored and Chaptarr keeps
|
|
509
551
|
looking. A format that already has a file reports already_exists; one in the download queue
|
|
510
552
|
reports downloading without a grab.
|
|
511
553
|
|
|
@@ -605,6 +647,29 @@ Examples:
|
|
|
605
647
|
fail(err);
|
|
606
648
|
}
|
|
607
649
|
});
|
|
650
|
+
books
|
|
651
|
+
.command('audiobooks')
|
|
652
|
+
.description('list every audiobook in Audiobookshelf, newest first')
|
|
653
|
+
.option('--json', 'output JSON')
|
|
654
|
+
.addHelpText('after', `
|
|
655
|
+
Behavior: reads the items with audio files of every Audiobookshelf book library, including
|
|
656
|
+
audiobooks Chaptarr does not manage. Changes nothing.
|
|
657
|
+
|
|
658
|
+
Output (--json): { "audiobooks": AudiobookItem[] }
|
|
659
|
+
AudiobookItem: { item_id, title, author, narrator, duration_seconds, added_at }
|
|
660
|
+
|
|
661
|
+
Examples:
|
|
662
|
+
trendarr books audiobooks --json`)
|
|
663
|
+
.action(async (opts) => {
|
|
664
|
+
try {
|
|
665
|
+
const { output, warnings } = await listAudiobooks(loadConfig());
|
|
666
|
+
printWarnings(warnings);
|
|
667
|
+
process.stdout.write(`${opts.json === true ? toJson(output) : renderAudiobookList(output)}\n`);
|
|
668
|
+
}
|
|
669
|
+
catch (err) {
|
|
670
|
+
fail(err);
|
|
671
|
+
}
|
|
672
|
+
});
|
|
608
673
|
books
|
|
609
674
|
.command('send-item')
|
|
610
675
|
.description('email one Audiobookshelf ebook item to a Kindle')
|
|
@@ -12,7 +12,11 @@ const itemsSchema = z.object({
|
|
|
12
12
|
media: z
|
|
13
13
|
.object({
|
|
14
14
|
ebookFormat: z.string().nullish(),
|
|
15
|
-
|
|
15
|
+
numAudioFiles: z.number().nullish(),
|
|
16
|
+
duration: z.number().nullish(),
|
|
17
|
+
metadata: z
|
|
18
|
+
.object({ title: z.string().nullish(), authorName: z.string().nullish(), narratorName: z.string().nullish() })
|
|
19
|
+
.nullish(),
|
|
16
20
|
})
|
|
17
21
|
.nullish(),
|
|
18
22
|
})),
|
|
@@ -40,8 +44,11 @@ export class AudiobookshelfClient {
|
|
|
40
44
|
id: i.id,
|
|
41
45
|
path: i.path,
|
|
42
46
|
ebookFormat: i.media?.ebookFormat ?? null,
|
|
47
|
+
audioFiles: i.media?.numAudioFiles ?? 0,
|
|
48
|
+
durationSeconds: i.media?.duration != null && i.media.duration > 0 ? i.media.duration : null,
|
|
43
49
|
title: i.media?.metadata?.title ?? null,
|
|
44
50
|
author: i.media?.metadata?.authorName ?? null,
|
|
51
|
+
narrator: i.media?.metadata?.narratorName || null,
|
|
45
52
|
addedAt: i.addedAt ?? null,
|
|
46
53
|
}));
|
|
47
54
|
}
|
package/dist/clients/chaptarr.js
CHANGED
|
@@ -60,6 +60,12 @@ const historySchema = z.object({
|
|
|
60
60
|
records: z.array(z.object({ bookId: z.number().nullish(), eventType: z.string(), date: z.string() })),
|
|
61
61
|
});
|
|
62
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
|
+
});
|
|
63
69
|
const downloadClientsSchema = z.array(z.object({
|
|
64
70
|
implementation: z.string(),
|
|
65
71
|
enable: z.boolean(),
|
|
@@ -236,6 +242,23 @@ export class ChaptarrClient {
|
|
|
236
242
|
async grab(guid, indexerId) {
|
|
237
243
|
await this.request('/api/v1/release', { method: 'POST', body: { guid, indexerId }, timeoutMs: LOOKUP_TIMEOUT_MS });
|
|
238
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
|
+
}
|
|
239
262
|
async book(bookId) {
|
|
240
263
|
return bookSchema.parse(await this.request(`/api/v1/book/${bookId}`));
|
|
241
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';
|
|
@@ -11,6 +12,9 @@ const SAB_FORCE_PRIORITY = 2;
|
|
|
11
12
|
const RUNNING_COMMAND = new Set(['queued', 'started']);
|
|
12
13
|
const NARRATOR_CHOICES = 5;
|
|
13
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)';
|
|
14
18
|
const SEARCH_TIMING = { waitMs: 120_000, pollMs: 3_000 };
|
|
15
19
|
function chaptarr(config) {
|
|
16
20
|
if (config.chaptarr === undefined)
|
|
@@ -38,11 +42,19 @@ function formatState(books) {
|
|
|
38
42
|
narrator: book?.narrator && book.narrator.length > 0 ? book.narrator : null,
|
|
39
43
|
};
|
|
40
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
|
+
}
|
|
41
50
|
function httpDetail(err) {
|
|
42
51
|
if (err instanceof HttpError) {
|
|
43
52
|
const body = err.body;
|
|
44
53
|
if (typeof body === 'string' && body.length > 0)
|
|
45
54
|
return body.slice(0, 300);
|
|
55
|
+
const messages = validationMessages(body);
|
|
56
|
+
if (messages.length > 0)
|
|
57
|
+
return messages.join('; ').slice(0, 300);
|
|
46
58
|
if (typeof body === 'object' && body !== null && 'message' in body && typeof body.message === 'string') {
|
|
47
59
|
return body.message.slice(0, 300);
|
|
48
60
|
}
|
|
@@ -264,6 +276,78 @@ export function estimateKbps(size, seconds) {
|
|
|
264
276
|
return null;
|
|
265
277
|
return Math.round((size * 8) / seconds / 1000);
|
|
266
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
|
+
}
|
|
267
351
|
export function selectReleases(releases, limit, now = Date.now(), narration = null) {
|
|
268
352
|
const wanted = releases
|
|
269
353
|
.filter((r) => !r.rejections.some((reason) => UNWANTED_REJECTION.test(reason)))
|
|
@@ -282,6 +366,7 @@ export function selectReleases(releases, limit, now = Date.now(), narration = nu
|
|
|
282
366
|
a.order - b.order);
|
|
283
367
|
return ranked.slice(0, limit).map(({ r, narrator_match, kbps }, i) => ({
|
|
284
368
|
rank: i + 1,
|
|
369
|
+
source: r.source,
|
|
285
370
|
title: r.title,
|
|
286
371
|
size: r.size,
|
|
287
372
|
quality: r.quality,
|
|
@@ -309,7 +394,12 @@ export async function bookReleases(config, foreignBookId, format, opts) {
|
|
|
309
394
|
const title = (await client.book(id)).title;
|
|
310
395
|
const narration = format === 'audiobook' ? narrationOf(editions) : null;
|
|
311
396
|
const limit = opts.maxEntries ?? config.defaults.maxEntries;
|
|
312
|
-
const
|
|
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);
|
|
313
403
|
return {
|
|
314
404
|
output: {
|
|
315
405
|
foreign_book_id: foreignBookId,
|
|
@@ -320,7 +410,7 @@ export async function bookReleases(config, foreignBookId, format, opts) {
|
|
|
320
410
|
duration_seconds: narration?.seconds ?? null,
|
|
321
411
|
releases,
|
|
322
412
|
},
|
|
323
|
-
warnings
|
|
413
|
+
warnings,
|
|
324
414
|
};
|
|
325
415
|
}
|
|
326
416
|
export async function bookNarrators(config, foreignBookId, opts) {
|
|
@@ -365,21 +455,25 @@ export async function bestBook(config, foreignBookId, format, opts) {
|
|
|
365
455
|
});
|
|
366
456
|
const title = (await client.book(id)).title;
|
|
367
457
|
const narration = format === 'audiobook' ? narrationOf(editions) : null;
|
|
368
|
-
const found = await
|
|
369
|
-
|
|
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];
|
|
370
463
|
await client.setMonitored([id], true);
|
|
371
|
-
|
|
464
|
+
const now = Date.now();
|
|
465
|
+
const taken = await takeFirst(client, candidates, selectReleases(candidates, candidates.length, now, narration), now);
|
|
466
|
+
if (taken === null) {
|
|
372
467
|
result = { book_id: id, title, status: 'nothing_found', detail: null, release: null };
|
|
373
468
|
}
|
|
374
469
|
else {
|
|
375
|
-
await client.grab(pick.guid, pick.indexer_id);
|
|
376
470
|
const release = {
|
|
377
|
-
title: pick.title,
|
|
378
|
-
quality: pick.quality,
|
|
379
|
-
kbps: pick.kbps,
|
|
380
|
-
narrator_match: pick.narrator_match,
|
|
471
|
+
title: taken.pick.title,
|
|
472
|
+
quality: taken.pick.quality,
|
|
473
|
+
kbps: taken.pick.kbps,
|
|
474
|
+
narrator_match: taken.pick.narrator_match,
|
|
381
475
|
};
|
|
382
|
-
result = { book_id: id, title, status: 'downloading', detail:
|
|
476
|
+
result = { book_id: id, title, status: 'downloading', detail: filedUnder(taken.bookId, id), release };
|
|
383
477
|
}
|
|
384
478
|
}
|
|
385
479
|
}
|
|
@@ -389,6 +483,60 @@ export async function bestBook(config, foreignBookId, format, opts) {
|
|
|
389
483
|
const sabnzbd_paused = await sabPausedFor(config, client, format, warnings);
|
|
390
484
|
return { output: { ...base, ...result, sabnzbd_paused }, warnings };
|
|
391
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
|
+
}
|
|
392
540
|
export async function grabRelease(config, bookId, guid, indexerId) {
|
|
393
541
|
const client = chaptarr(config);
|
|
394
542
|
const warnings = [];
|
|
@@ -467,6 +615,29 @@ export async function listEbooks(config) {
|
|
|
467
615
|
const ebooks = found.sort((a, b) => b.addedAt - a.addedAt).map((f) => f.item);
|
|
468
616
|
return { output: { ebooks, kindles: await abs.ereaderDevices() }, warnings: [] };
|
|
469
617
|
}
|
|
618
|
+
export async function listAudiobooks(config) {
|
|
619
|
+
const abs = audiobookshelf(config);
|
|
620
|
+
const found = [];
|
|
621
|
+
for (const library of (await abs.libraries()).filter((l) => l.mediaType === 'book')) {
|
|
622
|
+
for (const i of await abs.items(library.id)) {
|
|
623
|
+
if (i.audioFiles === 0)
|
|
624
|
+
continue;
|
|
625
|
+
const added_at = i.addedAt === null ? null : new Date(i.addedAt).toISOString();
|
|
626
|
+
found.push({
|
|
627
|
+
item: {
|
|
628
|
+
item_id: i.id,
|
|
629
|
+
title: i.title ?? i.path,
|
|
630
|
+
author: i.author,
|
|
631
|
+
narrator: i.narrator,
|
|
632
|
+
duration_seconds: i.durationSeconds === null ? null : Math.round(i.durationSeconds),
|
|
633
|
+
added_at,
|
|
634
|
+
},
|
|
635
|
+
addedAt: i.addedAt ?? 0,
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
return { output: { audiobooks: found.sort((a, b) => b.addedAt - a.addedAt).map((f) => f.item) }, warnings: [] };
|
|
640
|
+
}
|
|
470
641
|
export async function sendItem(config, itemId, device) {
|
|
471
642
|
const abs = audiobookshelf(config);
|
|
472
643
|
const base = { item_id: itemId, device };
|
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
|
@@ -138,9 +138,12 @@ export function renderReleasesTable(output) {
|
|
|
138
138
|
if (output.releases.length === 0)
|
|
139
139
|
return `${title}\nNo releases.`;
|
|
140
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.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
|
|
143
|
-
|
|
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');
|
|
144
147
|
}
|
|
145
148
|
export function renderNarrators(output) {
|
|
146
149
|
const title = `${output.title} [audiobook] book ${output.book_id}`;
|
|
@@ -160,7 +163,8 @@ export function renderBookBest(output) {
|
|
|
160
163
|
}
|
|
161
164
|
export function renderBookGrab(output) {
|
|
162
165
|
const detail = output.detail === null ? '' : ` (${output.detail})`;
|
|
163
|
-
|
|
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');
|
|
164
168
|
}
|
|
165
169
|
export function renderBookSend(output) {
|
|
166
170
|
const detail = output.detail === null ? '' : ` (${output.detail})`;
|
|
@@ -180,6 +184,13 @@ export function renderEbookList(output) {
|
|
|
180
184
|
const kindles = output.kindles.length === 0 ? 'Kindles: none' : `Kindles: ${output.kindles.join(', ')}`;
|
|
181
185
|
return [pc.bold(header), ...rows, '', kindles].join('\n');
|
|
182
186
|
}
|
|
187
|
+
export function renderAudiobookList(output) {
|
|
188
|
+
if (output.audiobooks.length === 0)
|
|
189
|
+
return 'No audiobooks.';
|
|
190
|
+
const header = `${cell('TITLE', 40)} ${cell('AUTHOR', 22)} ${cell('NARRATOR', 22)} ${cell('LENGTH', 8)} ADDED`;
|
|
191
|
+
const rows = output.audiobooks.map((a) => `${cell(a.title, 40)} ${cell(dash(a.author), 22)} ${cell(dash(a.narrator), 22)} ${cell(hours(a.duration_seconds), 8)} ${a.added_at?.slice(0, 10) ?? '-'}`);
|
|
192
|
+
return [pc.bold(header), ...rows].join('\n');
|
|
193
|
+
}
|
|
183
194
|
export function renderItemSend(output) {
|
|
184
195
|
const detail = output.detail === null ? '' : ` (${output.detail})`;
|
|
185
196
|
return `${output.item_id} → ${output.device}: ${statusColor(output.status, ['sent'])}${detail}`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astrofoundry/trendarr",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.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",
|