@astrofoundry/trendarr 0.13.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 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 Audiobookshelf. No environment variables.
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,6 +24,7 @@ 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]
@@ -33,7 +34,7 @@ trendarr books send-item <itemId> <device> [--json]
33
34
 
34
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).
35
36
 
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.
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.
37
38
 
38
39
  ## Development
39
40
 
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
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, 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';
@@ -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,6 +336,7 @@ 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.
@@ -445,11 +452,15 @@ Behavior: adds the book unmonitored when Chaptarr does not have it, monitors --e
445
452
  releases come best first: the monitored narrator's surname in the name, then M4B over MP3 and FLAC
446
453
  over other formats, then the higher estimated bitrate, then Chaptarr's order. Grab one within
447
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.
448
458
 
449
459
  Output (--json): { foreign_book_id, format, book_id, title, narrators, duration_seconds,
450
460
  releases: BookRelease[] }
451
- BookRelease: { rank, title, size, quality, protocol, indexer, seeders, age_days, guid, indexer_id,
452
- rejections, narrator_match, kbps } — size in bytes; rejections are Chaptarr's reasons it would not
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
453
464
  pick it by itself; kbps is size divided by the edition's length (null without a length or for
454
465
  ebooks), so a release holding several books shows too high a value.
455
466
 
@@ -496,6 +507,35 @@ Examples:
496
507
  fail(err);
497
508
  }
498
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
+ });
499
539
  books
500
540
  .command('best')
501
541
  .description('download the best release Chaptarr accepts')
@@ -505,7 +545,8 @@ books
505
545
  .option('--json', 'output JSON')
506
546
  .addHelpText('after', `
507
547
  Behavior: does what books releases does, then monitors the book and grabs the first release in that
508
- order without rejections. When every release has one, the book stays monitored and Chaptarr keeps
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
509
550
  looking. A format that already has a file reports already_exists; one in the download queue
510
551
  reports downloading without a grab.
511
552
 
@@ -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
+ }
@@ -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 releases = selectReleases(await client.releases(id), limit, Date.now(), narration);
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 client.releases(id);
369
- const pick = selectReleases(found, found.length, Date.now(), narration).find((r) => r.rejections.length === 0);
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
- if (pick === undefined) {
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: null, release };
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 = [];
@@ -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
- books = { chaptarr, audiobookshelf };
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 note = output.releases.some((r) => r.narrator_match) ? ['* names the narrator'] : [];
143
- return [title, pc.bold(header), ...rows, ...note].join('\n');
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
- return [`${output.title ?? `book ${output.book_id}`} ${statusColor(output.status, ['grabbed'])}${detail}`, '', sabLine(output.sabnzbd_paused)].join('\n');
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})`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/trendarr",
3
- "version": "0.13.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",