@astrofoundry/trendarr 0.6.0 → 0.9.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,19 +8,27 @@ 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). 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 and Audiobookshelf. No environment variables.
12
12
 
13
13
  ## Commands
14
14
 
15
15
  ```bash
16
16
  trendarr trending [--max-entries 10] [--type movies|series] [--min-rating 6.5] [--json|--discord]
17
17
  trendarr search <query> [--max-entries 10] [--type movies|series] [--json|--discord]
18
+ trendarr recommend [--max-entries 10] [--type movies|series] [--exclude tt1,tt2] [--json]
18
19
  trendarr add-movies <imdbIds...> [--json]
19
20
  trendarr add-series <imdbIds...> [--json]
20
21
  trendarr sabnzbd status|pause|resume|unpause [--json]
22
+ trendarr books search <query> [--max-entries 10] [--json]
23
+ trendarr books add <bookId> --format audiobook|ebook [--json]
24
+ trendarr books releases <bookId> --format audiobook|ebook [--max-entries 10] [--json]
25
+ trendarr books grab <chaptarrId> <guid> <indexerId> [--json]
26
+ trendarr books send <chaptarrId> <device> [--json]
21
27
  ```
22
28
 
23
- `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.
29
+ `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).
30
+
31
+ `books` works with Chaptarr, which keeps an audiobook and an ebook entry per work. `add` lets Chaptarr pick the release; `releases` then `grab` let you pick one yourself (narrator, size, format). `send` emails an ebook to a Kindle through Audiobookshelf's e-reader devices.
24
32
 
25
33
  ## Development
26
34
 
package/dist/cli.js CHANGED
@@ -2,12 +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, bookReleases, grabRelease, searchBooks, sendBook } from './commands/books.js';
5
6
  import { runInit } from './commands/init.js';
6
7
  import { runSabnzbd } from './commands/sabnzbd.js';
8
+ import { CANDIDATE_LIMIT, getRecommendations } from './commands/recommend.js';
7
9
  import { getSearch } from './commands/search.js';
8
10
  import { getTrending } from './commands/trending.js';
9
11
  import { ConfigError, loadConfig } from './config.js';
10
- import { renderAddTable, renderSabStatus, renderSearchDiscord, renderSearchTable, renderTrendingDiscord, renderTrendingTable, toJson, } from './format.js';
12
+ import { renderAddTable, renderBookAdd, renderBookGrab, renderBookSearchTable, renderBookSend, renderReleasesTable, renderRecommendTable, renderSabStatus, renderSearchDiscord, renderSearchTable, renderTrendingDiscord, renderTrendingTable, toJson, } from './format.js';
11
13
  import { describeError } from './http.js';
12
14
  const pkg = createRequire(import.meta.url)('../package.json');
13
15
  const program = new Command();
@@ -28,6 +30,23 @@ function parseRating(value) {
28
30
  throw new InvalidArgumentError('must be a number between 0 and 10');
29
31
  return n;
30
32
  }
33
+ function parseFormat(value) {
34
+ if (value === 'audiobook' || value === 'ebook')
35
+ return value;
36
+ throw new InvalidArgumentError("must be 'audiobook' or 'ebook'");
37
+ }
38
+ function parseBookId(value) {
39
+ if (/^[a-z]{2,10}:[\w:-]{1,40}$/.test(value))
40
+ return value;
41
+ throw new InvalidArgumentError('not a Chaptarr book id (e.g. gr:3060926 or hc:194793)');
42
+ }
43
+ function parseImdbList(value) {
44
+ const ids = [...new Set(value.split(',').map((p) => p.trim()).filter((p) => p.length > 0))];
45
+ const bad = ids.find((id) => !/^tt\d+$/.test(id));
46
+ if (bad !== undefined)
47
+ throw new InvalidArgumentError(`not an IMDb id: ${bad}`);
48
+ return ids;
49
+ }
31
50
  function fail(err) {
32
51
  process.stderr.write(`${err instanceof ConfigError ? err.message : describeError(err)}\n`);
33
52
  process.exit(1);
@@ -54,9 +73,11 @@ Commands:
54
73
  init Interactive setup with live credential validation.
55
74
  trending Trending movies and series (TMDB, weekly) with IMDb ratings and a library flag.
56
75
  search <query> Search movies and series by name (full or partial).
76
+ recommend Titles TMDB recommends for your Radarr/Sonarr library, not yet in it.
57
77
  add-movies <imdbIds...> Add movies to Radarr by IMDb id and start a search.
58
78
  add-series <imdbIds...> Add series to Sonarr by IMDb id and start a search.
59
79
  sabnzbd <action> Read or toggle the SABnzbd queue pause state.
80
+ books <action> Audiobooks and ebooks: Chaptarr search, adds, release picks, Send to Kindle.
60
81
 
61
82
  Run "trendarr <command> --help" for that command's parameters and output shape.`);
62
83
  program
@@ -163,6 +184,48 @@ Examples:
163
184
  fail(err);
164
185
  }
165
186
  });
187
+ program
188
+ .command('recommend')
189
+ .description('titles TMDB recommends for the most library titles, released, well rated, not in the library')
190
+ .option('--max-entries <n>', 'results per media type', parsePositiveInt)
191
+ .option('--type <type>', "'movies' or 'series'", parseType)
192
+ .option('--exclude <ids>', 'comma-separated IMDb ids to leave out', parseImdbList)
193
+ .option('--json', 'output JSON')
194
+ .addHelpText('after', `
195
+ Parameters:
196
+ --max-entries <n> Results per media type (positive integer). Default: 10 (config defaults.maxEntries).
197
+ --type <type> Restrict to "movies" or "series". Default: both.
198
+ --exclude <ids> Comma-separated IMDb ids that never appear (e.g. titles already suggested).
199
+ --json Output JSON instead of the table.
200
+
201
+ Behavior: reads every Radarr movie and Sonarr series, asks TMDB for the recommendations of each, and
202
+ ranks the titles not in the library by how many library titles lead to them, then by TMDB popularity.
203
+ A title is kept only when it is released (movies: a digital or physical release date that has passed;
204
+ series: a first air date that has passed) and its IMDb rating is 7.0 or higher with at least 5,000
205
+ votes (movies) or 2,000 votes (series). At most ${CANDIDATE_LIMIT} candidates per type are checked. With a large
206
+ library this takes minutes.
207
+
208
+ Output (table): a MOVIES block then a SERIES block, best first.
209
+ Columns: # rank, TITLE, YEAR, IMDB (rating), VOTES, BECAUSE (library titles, +N more), LINK.
210
+ Output (--json): { "movies": RecommendItem[], "series": RecommendItem[] }
211
+ RecommendItem: the search MediaItem plus "matches" (how many library titles lead to it) and
212
+ "because" (up to three of those titles). in_library is always false.
213
+
214
+ Examples:
215
+ trendarr recommend
216
+ trendarr recommend --type movies --max-entries 3
217
+ trendarr recommend --exclude tt1160419,tt0903747 --json`)
218
+ .action(async (opts) => {
219
+ try {
220
+ const config = loadConfig();
221
+ const { output, warnings } = await getRecommendations(config, opts);
222
+ printWarnings(warnings);
223
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderRecommendTable(output)}\n`);
224
+ }
225
+ catch (err) {
226
+ fail(err);
227
+ }
228
+ });
166
229
  function addAction(kind) {
167
230
  return async (ids, opts) => {
168
231
  try {
@@ -253,6 +316,164 @@ Examples:
253
316
  fail(err);
254
317
  }
255
318
  });
319
+ const books = program
320
+ .command('books')
321
+ .description('audiobooks and ebooks: Chaptarr search and adds, Audiobookshelf Send to Kindle')
322
+ .addHelpText('after', `
323
+ Needs the optional "chaptarr" section of the config (and "audiobookshelf" for send and the Kindle list).
324
+ Chaptarr keeps one book per format: an audiobook id and an ebook id for the same work. The book id
325
+ used by add and releases is Chaptarr's foreign book id (e.g. gr:3060926), from books search.
326
+
327
+ Actions:
328
+ search <query> Find works, with each format's state and the Kindle devices.
329
+ add <bookId> --format <f> Monitor one format and let Chaptarr pick and download a release.
330
+ releases <bookId> --format <f> List the releases you can pick from (narrator, size, quality).
331
+ grab <chaptarrId> <guid> <indexerId> Download one release from that list.
332
+ send <chaptarrId> <device> Email the ebook to a Kindle through Audiobookshelf.`);
333
+ books
334
+ .command('search')
335
+ .description('search Chaptarr for books by title or author')
336
+ .argument('<query>', 'title or author, e.g. "pride and prejudice"')
337
+ .option('--max-entries <n>', 'results', parsePositiveInt)
338
+ .option('--json', 'output JSON')
339
+ .addHelpText('after', `
340
+ Parameters:
341
+ <query> Title or author words. Quote multi-word queries.
342
+ --max-entries <n> Results (positive integer). Default: 10 (config defaults.maxEntries).
343
+ --json Output JSON instead of the table.
344
+
345
+ Output (--json): { "books": BookItem[], "kindles": string[] }
346
+ BookItem: { rank, title, author, foreign_book_id, votes, audiobook: Format, ebook: Format }
347
+ Format: { book_id, monitored, has_file, narrator } — book_id is Chaptarr's id for that format,
348
+ null when Chaptarr does not have it yet. kindles lists the Audiobookshelf e-reader device names;
349
+ empty when Audiobookshelf is not configured or unreachable (then a warning).
350
+
351
+ Examples:
352
+ trendarr books search "the two towers"
353
+ trendarr books search austen --json`)
354
+ .action(async (query, opts) => {
355
+ try {
356
+ const { output, warnings } = await searchBooks(loadConfig(), query, opts);
357
+ printWarnings(warnings);
358
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderBookSearchTable(output)}\n`);
359
+ }
360
+ catch (err) {
361
+ fail(err);
362
+ }
363
+ });
364
+ books
365
+ .command('add')
366
+ .description('monitor one format of a book and start a search')
367
+ .argument('<bookId>', 'foreign book id from books search, e.g. gr:3060926', parseBookId)
368
+ .requiredOption('--format <format>', "'audiobook' or 'ebook'", parseFormat)
369
+ .option('--json', 'output JSON')
370
+ .addHelpText('after', `
371
+ Behavior: adds the book (and its author, with no other book monitored) when Chaptarr does not have it,
372
+ or monitors the existing entry, then starts a search; Chaptarr picks the release by the format's
373
+ quality profile. A format that already has a file reports already_exists.
374
+
375
+ Output (--json): { foreign_book_id, format, book_id, title, status, detail, sabnzbd_paused }
376
+ status is one of: added | searching | already_exists | not_found | error. Exit code 1 on not_found or error.
377
+
378
+ Examples:
379
+ trendarr books add gr:3060926 --format ebook`)
380
+ .action(async (bookId, opts) => {
381
+ try {
382
+ const config = loadConfig();
383
+ const { output, warnings } = await addBook(config, bookId, opts.format);
384
+ printWarnings(warnings);
385
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderBookAdd(output)}\n`);
386
+ if (output.status === 'not_found' || output.status === 'error')
387
+ process.exitCode = 1;
388
+ }
389
+ catch (err) {
390
+ fail(err);
391
+ }
392
+ });
393
+ books
394
+ .command('releases')
395
+ .description('list the releases of one format to pick from')
396
+ .argument('<bookId>', 'foreign book id from books search, e.g. gr:3060926', parseBookId)
397
+ .requiredOption('--format <format>', "'audiobook' or 'ebook'", parseFormat)
398
+ .option('--max-entries <n>', 'releases', parsePositiveInt)
399
+ .option('--json', 'output JSON')
400
+ .addHelpText('after', `
401
+ Behavior: adds the book unmonitored when Chaptarr does not have it, then runs Chaptarr's interactive
402
+ search (can take a minute). Releases in a format the profile does not want, and torrents without
403
+ enough seeders, are left out. Order is Chaptarr's. Grab one within 30 minutes, while Chaptarr
404
+ still caches the search.
405
+
406
+ Output (--json): { foreign_book_id, format, book_id, title, releases: BookRelease[] }
407
+ BookRelease: { rank, title, size, quality, protocol, indexer, seeders, age_days, guid, indexer_id,
408
+ rejections } — size in bytes; rejections are Chaptarr's reasons it would not pick it by itself.
409
+
410
+ Examples:
411
+ trendarr books releases gr:3060926 --format audiobook --max-entries 5`)
412
+ .action(async (bookId, opts) => {
413
+ try {
414
+ const { output, warnings } = await bookReleases(loadConfig(), bookId, opts.format, opts);
415
+ printWarnings(warnings);
416
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderReleasesTable(output)}\n`);
417
+ }
418
+ catch (err) {
419
+ fail(err);
420
+ }
421
+ });
422
+ books
423
+ .command('grab')
424
+ .description('download one release from books releases')
425
+ .argument('<chaptarrId>', 'book_id from books releases', parsePositiveInt)
426
+ .argument('<guid>', 'guid of the release')
427
+ .argument('<indexerId>', 'indexer_id of the release', parsePositiveInt)
428
+ .option('--json', 'output JSON')
429
+ .addHelpText('after', `
430
+ Behavior: monitors the book and sends that release to the download client.
431
+
432
+ Output (--json): { book_id, title, status, detail, sabnzbd_paused }
433
+ status is grabbed or error (an expired search reports Chaptarr's cache message). Exit code 1 on error.
434
+
435
+ Examples:
436
+ trendarr books grab 450 "https://example.org/details/abc" 1`)
437
+ .action(async (chaptarrId, guid, indexerId, opts) => {
438
+ try {
439
+ const { output, warnings } = await grabRelease(loadConfig(), chaptarrId, guid, indexerId);
440
+ printWarnings(warnings);
441
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderBookGrab(output)}\n`);
442
+ if (output.status === 'error')
443
+ process.exitCode = 1;
444
+ }
445
+ catch (err) {
446
+ fail(err);
447
+ }
448
+ });
449
+ books
450
+ .command('send')
451
+ .description('email an ebook to a Kindle through Audiobookshelf')
452
+ .argument('<chaptarrId>', "the ebook's book_id from books search", parsePositiveInt)
453
+ .argument('<device>', 'Audiobookshelf e-reader device name, from books search "kindles"')
454
+ .option('--json', 'output JSON')
455
+ .addHelpText('after', `
456
+ Behavior: finds the ebook's folder from Chaptarr's file, the Audiobookshelf item in that folder,
457
+ and asks Audiobookshelf to email it to the device. The sender must be approved on the Amazon account.
458
+
459
+ Output (--json): { book_id, title, device, status, detail }
460
+ status is one of: sent | no_file | not_in_audiobookshelf | unknown_device | error.
461
+ Exit code 1 unless sent.
462
+
463
+ Examples:
464
+ trendarr books send 3274 "Kindle Astro"`)
465
+ .action(async (chaptarrId, device, opts) => {
466
+ try {
467
+ const { output, warnings } = await sendBook(loadConfig(), chaptarrId, device);
468
+ printWarnings(warnings);
469
+ process.stdout.write(`${opts.json === true ? toJson(output) : renderBookSend(output)}\n`);
470
+ if (output.status !== 'sent')
471
+ process.exitCode = 1;
472
+ }
473
+ catch (err) {
474
+ fail(err);
475
+ }
476
+ });
256
477
  if (process.argv.slice(2).length === 0) {
257
478
  program.outputHelp();
258
479
  process.exit(0);
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod';
2
+ import { fetchJson } from '../http.js';
3
+ const authorizeSchema = z.object({ ereaderDevices: z.array(z.object({ name: z.string() })).nullish() });
4
+ const librariesSchema = z.object({
5
+ libraries: z.array(z.object({ id: z.string(), name: z.string(), mediaType: z.string() })),
6
+ });
7
+ const itemsSchema = z.object({
8
+ results: z.array(z.object({
9
+ id: z.string(),
10
+ path: z.string(),
11
+ media: z.object({ ebookFormat: z.string().nullish() }).nullish(),
12
+ })),
13
+ });
14
+ export class AudiobookshelfClient {
15
+ baseUrl;
16
+ apiKey;
17
+ constructor(baseUrl, apiKey) {
18
+ this.baseUrl = baseUrl;
19
+ this.apiKey = apiKey;
20
+ }
21
+ request(path, opts = {}) {
22
+ return fetchJson(`${this.baseUrl}${path}`, { ...opts, headers: { Authorization: `Bearer ${this.apiKey}` } });
23
+ }
24
+ async ereaderDevices() {
25
+ const parsed = authorizeSchema.parse(await this.request('/api/authorize', { method: 'POST' }));
26
+ return (parsed.ereaderDevices ?? []).map((d) => d.name);
27
+ }
28
+ async libraries() {
29
+ return librariesSchema.parse(await this.request('/api/libraries')).libraries;
30
+ }
31
+ async items(libraryId) {
32
+ const parsed = itemsSchema.parse(await this.request(`/api/libraries/${encodeURIComponent(libraryId)}/items?limit=0`));
33
+ return parsed.results.map((i) => ({ id: i.id, path: i.path, ebookFormat: i.media?.ebookFormat ?? null }));
34
+ }
35
+ async sendEbook(libraryItemId, deviceName) {
36
+ await this.request('/api/emails/send-ebook-to-device', {
37
+ method: 'POST',
38
+ body: { libraryItemId, deviceName },
39
+ timeoutMs: 60_000,
40
+ });
41
+ }
42
+ }
@@ -0,0 +1,183 @@
1
+ import { z } from 'zod';
2
+ import { fetchJson } from '../http.js';
3
+ const LOOKUP_TIMEOUT_MS = 60_000;
4
+ const RELEASE_TIMEOUT_MS = 180_000;
5
+ const statusSchema = z.object({ appName: z.string(), version: z.string() });
6
+ const localBookSchema = z.object({
7
+ id: z.number(),
8
+ monitored: z.boolean(),
9
+ hasFiles: z.boolean(),
10
+ narrator: z.string().nullish(),
11
+ });
12
+ const lookupSchema = z.object({
13
+ title: z.string(),
14
+ mediaType: z.string(),
15
+ foreignBookId: z.string(),
16
+ author: z.object({ authorName: z.string() }).nullish(),
17
+ ratings: z.object({ votes: z.number() }).nullish(),
18
+ localAudiobookBooks: z.array(localBookSchema).nullish(),
19
+ localEbookBooks: z.array(localBookSchema).nullish(),
20
+ });
21
+ const rootFolderSchema = z.object({
22
+ path: z.string(),
23
+ isEffectiveDefaultAudiobook: z.boolean().nullish(),
24
+ isEffectiveDefaultEbook: z.boolean().nullish(),
25
+ audiobookQualityProfileId: z.number().nullish(),
26
+ audiobookMetadataProfileId: z.number().nullish(),
27
+ ebookQualityProfileId: z.number().nullish(),
28
+ ebookMetadataProfileId: z.number().nullish(),
29
+ });
30
+ const rejectionSchema = z.union([z.string(), z.object({ reason: z.string() }).transform((r) => r.reason)]);
31
+ const releaseSchema = z.object({
32
+ guid: z.string(),
33
+ indexerId: z.number(),
34
+ title: z.string(),
35
+ size: z.number().nullish(),
36
+ indexer: z.string().nullish(),
37
+ protocol: z.string().nullish(),
38
+ seeders: z.number().nullish(),
39
+ publishDate: z.string().nullish(),
40
+ quality: z.object({ quality: z.object({ name: z.string() }) }).nullish(),
41
+ rejections: z.array(rejectionSchema).nullish(),
42
+ });
43
+ const releasePageSchema = z.object({ releases: z.array(z.unknown()), hiddenReleases: z.array(z.unknown()).nullish() });
44
+ const bookSchema = z.object({ id: z.number(), title: z.string(), mediaType: z.string(), monitored: z.boolean() });
45
+ const bookFilesSchema = z.array(z.object({ path: z.string() }));
46
+ const addedSchema = z.object({ id: z.number() });
47
+ function localBooks(value) {
48
+ return (value ?? []).map((b) => ({ id: b.id, monitored: b.monitored, hasFiles: b.hasFiles, narrator: b.narrator ?? null }));
49
+ }
50
+ function toRelease(value) {
51
+ const parsed = releaseSchema.safeParse(value);
52
+ if (!parsed.success)
53
+ return null;
54
+ const r = parsed.data;
55
+ return {
56
+ guid: r.guid,
57
+ indexerId: r.indexerId,
58
+ title: r.title,
59
+ size: r.size ?? null,
60
+ indexer: r.indexer ?? null,
61
+ protocol: r.protocol ?? null,
62
+ seeders: r.seeders ?? null,
63
+ publishDate: r.publishDate ?? null,
64
+ quality: r.quality?.quality.name ?? null,
65
+ rejections: r.rejections ?? [],
66
+ };
67
+ }
68
+ export class ChaptarrClient {
69
+ baseUrl;
70
+ apiKey;
71
+ constructor(baseUrl, apiKey) {
72
+ this.baseUrl = baseUrl;
73
+ this.apiKey = apiKey;
74
+ }
75
+ request(path, opts = {}) {
76
+ return fetchJson(`${this.baseUrl}${path}`, { ...opts, headers: { 'X-Api-Key': this.apiKey } });
77
+ }
78
+ async systemStatus() {
79
+ return statusSchema.parse(await this.request('/api/v1/system/status'));
80
+ }
81
+ async lookup(term) {
82
+ const value = await this.request(`/api/v1/book/lookup?term=${encodeURIComponent(term)}`, {
83
+ timeoutMs: LOOKUP_TIMEOUT_MS,
84
+ });
85
+ if (!Array.isArray(value))
86
+ return [];
87
+ return value.flatMap((item) => {
88
+ const parsed = lookupSchema.safeParse(item);
89
+ if (!parsed.success)
90
+ return [];
91
+ const b = parsed.data;
92
+ return [
93
+ {
94
+ title: b.title,
95
+ mediaType: b.mediaType,
96
+ foreignBookId: b.foreignBookId,
97
+ author: b.author?.authorName ?? null,
98
+ votes: b.ratings?.votes ?? null,
99
+ audiobook: localBooks(b.localAudiobookBooks),
100
+ ebook: localBooks(b.localEbookBooks),
101
+ raw: item,
102
+ },
103
+ ];
104
+ });
105
+ }
106
+ async formatDefaults() {
107
+ const folders = z.array(rootFolderSchema).parse(await this.request('/api/v1/rootfolder'));
108
+ const audiobook = folders.find((f) => f.isEffectiveDefaultAudiobook === true);
109
+ const ebook = folders.find((f) => f.isEffectiveDefaultEbook === true);
110
+ if (audiobook?.audiobookQualityProfileId == null ||
111
+ audiobook.audiobookMetadataProfileId == null ||
112
+ ebook?.ebookQualityProfileId == null ||
113
+ ebook.ebookMetadataProfileId == null) {
114
+ throw new Error('Chaptarr has no default audiobook and ebook root folders with profiles');
115
+ }
116
+ return {
117
+ audiobook: {
118
+ rootFolderPath: audiobook.path,
119
+ qualityProfileId: audiobook.audiobookQualityProfileId,
120
+ metadataProfileId: audiobook.audiobookMetadataProfileId,
121
+ },
122
+ ebook: {
123
+ rootFolderPath: ebook.path,
124
+ qualityProfileId: ebook.ebookQualityProfileId,
125
+ metadataProfileId: ebook.ebookMetadataProfileId,
126
+ },
127
+ };
128
+ }
129
+ async addBook(lookup, format, defaults, opts) {
130
+ const rawAuthor = lookup.raw.author;
131
+ const author = typeof rawAuthor === 'object' && rawAuthor !== null ? rawAuthor : {};
132
+ const body = {
133
+ ...lookup.raw,
134
+ mediaType: format,
135
+ monitored: opts.monitored,
136
+ addOptions: { searchForNewBook: opts.search },
137
+ author: {
138
+ ...author,
139
+ audiobookQualityProfileId: defaults.audiobook.qualityProfileId,
140
+ audiobookMetadataProfileId: defaults.audiobook.metadataProfileId,
141
+ ebookQualityProfileId: defaults.ebook.qualityProfileId,
142
+ ebookMetadataProfileId: defaults.ebook.metadataProfileId,
143
+ qualityProfileId: defaults[format].qualityProfileId,
144
+ metadataProfileId: defaults[format].metadataProfileId,
145
+ audiobookRootFolderPath: defaults.audiobook.rootFolderPath,
146
+ ebookRootFolderPath: defaults.ebook.rootFolderPath,
147
+ rootFolderPath: defaults[format].rootFolderPath,
148
+ monitored: true,
149
+ audiobookMonitored: true,
150
+ ebookMonitored: true,
151
+ audiobookMonitorNewItems: 'none',
152
+ ebookMonitorNewItems: 'none',
153
+ addOptions: { monitor: 'none', searchForMissingBooks: false },
154
+ },
155
+ };
156
+ return addedSchema.parse(await this.request('/api/v1/book', { method: 'POST', body })).id;
157
+ }
158
+ async setMonitored(bookIds, monitored) {
159
+ await this.request('/api/v1/book/monitor', { method: 'PUT', body: { bookIds, monitored } });
160
+ }
161
+ async searchBook(bookId) {
162
+ await this.request('/api/v1/command', { method: 'POST', body: { name: 'BookSearch', bookIds: [bookId] } });
163
+ }
164
+ async releases(bookId) {
165
+ const value = await this.request(`/api/v1/release?bookId=${bookId}`, { timeoutMs: RELEASE_TIMEOUT_MS });
166
+ const page = releasePageSchema.safeParse(value);
167
+ const items = Array.isArray(value)
168
+ ? value
169
+ : page.success
170
+ ? [...page.data.releases, ...(page.data.hiddenReleases ?? [])]
171
+ : [];
172
+ return items.flatMap((item) => toRelease(item) ?? []);
173
+ }
174
+ async grab(guid, indexerId) {
175
+ await this.request('/api/v1/release', { method: 'POST', body: { guid, indexerId }, timeoutMs: LOOKUP_TIMEOUT_MS });
176
+ }
177
+ async book(bookId) {
178
+ return bookSchema.parse(await this.request(`/api/v1/book/${bookId}`));
179
+ }
180
+ async bookFilePaths(bookId) {
181
+ return bookFilesSchema.parse(await this.request(`/api/v1/bookfile?bookId=${bookId}`)).map((f) => f.path);
182
+ }
183
+ }
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { ArrClient } from './arr.js';
3
3
  const librarySchema = z.array(z.object({ tmdbId: z.number().nullish() }));
4
+ const libraryTitlesSchema = z.array(z.object({ tmdbId: z.number().nullish(), title: z.string().nullish() }));
4
5
  export class RadarrClient extends ArrClient {
5
6
  async lookupByImdb(imdbId) {
6
7
  const raw = await this.getJson(`/api/v3/movie/lookup/imdb?imdbId=${encodeURIComponent(imdbId)}`);
@@ -22,6 +23,10 @@ export class RadarrClient extends ArrClient {
22
23
  return this.mapAddError(err);
23
24
  }
24
25
  }
26
+ async libraryMovies() {
27
+ const items = libraryTitlesSchema.parse(await this.getJson('/api/v3/movie'));
28
+ return items.flatMap((m) => typeof m.tmdbId === 'number' && m.tmdbId > 0 ? [{ tmdbId: m.tmdbId, title: m.title ?? 'Unknown movie' }] : []);
29
+ }
25
30
  async libraryTmdbIds() {
26
31
  const items = librarySchema.parse(await this.getJson('/api/v3/movie'));
27
32
  return new Set(items.flatMap((m) => (typeof m.tmdbId === 'number' ? [m.tmdbId] : [])));
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { ArrClient } from './arr.js';
3
3
  const librarySchema = z.array(z.object({ tvdbId: z.number().nullish() }));
4
+ const libraryTitlesSchema = z.array(z.object({ tmdbId: z.number().nullish(), tvdbId: z.number().nullish(), title: z.string().nullish() }));
4
5
  export class SonarrClient extends ArrClient {
5
6
  async lookupByTvdb(tvdbId) {
6
7
  const raw = await this.getJson(`/api/v3/series/lookup?term=${encodeURIComponent(`tvdb:${tvdbId}`)}`);
@@ -24,6 +25,14 @@ export class SonarrClient extends ArrClient {
24
25
  return this.mapAddError(err);
25
26
  }
26
27
  }
28
+ async librarySeries() {
29
+ const items = libraryTitlesSchema.parse(await this.getJson('/api/v3/series'));
30
+ return items.map((s) => ({
31
+ tmdbId: typeof s.tmdbId === 'number' && s.tmdbId > 0 ? s.tmdbId : null,
32
+ tvdbId: typeof s.tvdbId === 'number' && s.tvdbId > 0 ? s.tvdbId : null,
33
+ title: s.title ?? 'Unknown series',
34
+ }));
35
+ }
27
36
  async libraryTvdbIds() {
28
37
  const items = librarySchema.parse(await this.getJson('/api/v3/series'));
29
38
  return new Set(items.flatMap((s) => (typeof s.tvdbId === 'number' ? [s.tvdbId] : [])));
@@ -23,7 +23,11 @@ const genreListSchema = z.object({ genres: z.array(z.object({ id: z.number(), na
23
23
  const movieExternalIdsSchema = z.object({ imdb_id: z.string().nullish() });
24
24
  const showExternalIdsSchema = z.object({ imdb_id: z.string().nullish(), tvdb_id: z.number().nullish() });
25
25
  const findSchema = z.object({ tv_results: z.array(z.object({ id: z.number() })) });
26
- function yearOf(date) {
26
+ const releaseDatesSchema = z.object({
27
+ results: z.array(z.object({ release_dates: z.array(z.object({ release_date: z.string(), type: z.number() })) })),
28
+ });
29
+ export const HOME_RELEASE_TYPES = [4, 5];
30
+ export function yearOf(date) {
27
31
  if (date === undefined || date === null || date.length < 4)
28
32
  return null;
29
33
  const year = Number(date.slice(0, 4));
@@ -80,6 +84,19 @@ export class TmdbClient {
80
84
  this.genreMaps[kind] = map;
81
85
  return map;
82
86
  }
87
+ async genres(kind, ids) {
88
+ return genreNames(ids, await this.genreMap(kind));
89
+ }
90
+ async movieRecommendations(tmdbId) {
91
+ return moviePageSchema.parse(await this.get(`/movie/${tmdbId}/recommendations?page=1`)).results;
92
+ }
93
+ async showRecommendations(tmdbId) {
94
+ return showPageSchema.parse(await this.get(`/tv/${tmdbId}/recommendations?page=1`)).results;
95
+ }
96
+ async movieHomeRelease(tmdbId, now) {
97
+ const parsed = releaseDatesSchema.parse(await this.get(`/movie/${tmdbId}/release_dates`));
98
+ return parsed.results.some((country) => country.release_dates.some((r) => HOME_RELEASE_TYPES.includes(r.type) && Number.isFinite(Date.parse(r.release_date)) && Date.parse(r.release_date) <= now));
99
+ }
83
100
  async movieImdbId(tmdbId) {
84
101
  const raw = await this.get(`/movie/${tmdbId}/external_ids`);
85
102
  const imdbId = movieExternalIdsSchema.parse(raw).imdb_id;
@@ -20,7 +20,7 @@ export function parseImdbIds(raw) {
20
20
  export function hasFailure(output) {
21
21
  return output.results.some((r) => r.status === 'not_found' || r.status === 'error');
22
22
  }
23
- async function sabPaused(config, warnings) {
23
+ export async function sabPaused(config, warnings) {
24
24
  try {
25
25
  return await new SabnzbdClient(config.sabnzbd.url, config.sabnzbd.apiKey).isPaused();
26
26
  }
@@ -0,0 +1,195 @@
1
+ import { dirname } from 'node:path';
2
+ import { AudiobookshelfClient } from '../clients/audiobookshelf.js';
3
+ import { ChaptarrClient } from '../clients/chaptarr.js';
4
+ import { ConfigError } from '../config.js';
5
+ import { HttpError, describeError } from '../http.js';
6
+ import { sabPaused } from './add.js';
7
+ const DAY_MS = 86_400_000;
8
+ const UNWANTED_REJECTION = /not wanted in profile|not enough seeders/i;
9
+ function chaptarr(config) {
10
+ if (config.chaptarr === undefined)
11
+ throw new ConfigError("Chaptarr is not configured — run 'trendarr init'.");
12
+ return new ChaptarrClient(config.chaptarr.url, config.chaptarr.apiKey);
13
+ }
14
+ function audiobookshelf(config) {
15
+ if (config.audiobookshelf === undefined) {
16
+ throw new ConfigError("Audiobookshelf is not configured — run 'trendarr init'.");
17
+ }
18
+ return new AudiobookshelfClient(config.audiobookshelf.url, config.audiobookshelf.apiKey);
19
+ }
20
+ function preferred(books) {
21
+ return books.find((b) => b.hasFiles) ?? books.find((b) => b.monitored) ?? books[0] ?? null;
22
+ }
23
+ function formatState(books) {
24
+ const book = preferred(books);
25
+ return {
26
+ book_id: book?.id ?? null,
27
+ monitored: book?.monitored ?? false,
28
+ has_file: book?.hasFiles ?? false,
29
+ narrator: book?.narrator && book.narrator.length > 0 ? book.narrator : null,
30
+ };
31
+ }
32
+ function httpDetail(err) {
33
+ if (err instanceof HttpError) {
34
+ const body = err.body;
35
+ if (typeof body === 'string' && body.length > 0)
36
+ return body.slice(0, 300);
37
+ if (typeof body === 'object' && body !== null && 'message' in body && typeof body.message === 'string') {
38
+ return body.message.slice(0, 300);
39
+ }
40
+ }
41
+ return describeError(err);
42
+ }
43
+ export async function searchBooks(config, query, opts) {
44
+ const client = chaptarr(config);
45
+ const warnings = [];
46
+ const limit = opts.maxEntries ?? config.defaults.maxEntries;
47
+ const seen = new Set();
48
+ const books = [];
49
+ for (const found of await client.lookup(query)) {
50
+ if (seen.has(found.foreignBookId) || books.length >= limit)
51
+ continue;
52
+ seen.add(found.foreignBookId);
53
+ books.push({
54
+ rank: books.length + 1,
55
+ title: found.title,
56
+ author: found.author,
57
+ foreign_book_id: found.foreignBookId,
58
+ votes: found.votes,
59
+ audiobook: formatState(found.audiobook),
60
+ ebook: formatState(found.ebook),
61
+ });
62
+ }
63
+ let kindles = [];
64
+ if (config.audiobookshelf !== undefined) {
65
+ try {
66
+ kindles = await audiobookshelf(config).ereaderDevices();
67
+ }
68
+ catch (err) {
69
+ warnings.push(`Audiobookshelf unreachable — no Kindle list (${describeError(err)})`);
70
+ }
71
+ }
72
+ return { output: { books, kindles }, warnings };
73
+ }
74
+ async function findFormat(client, foreignBookId, format) {
75
+ const found = (await client.lookup(foreignBookId)).filter((b) => b.foreignBookId === foreignBookId);
76
+ return found.find((b) => b.mediaType === format) ?? found[0] ?? null;
77
+ }
78
+ async function ensureBook(client, lookup, format, opts) {
79
+ const local = preferred(lookup[format]);
80
+ if (local !== null)
81
+ return { id: local.id, added: false };
82
+ const id = await client.addBook(lookup, format, await client.formatDefaults(), opts);
83
+ return { id, added: true };
84
+ }
85
+ export async function addBook(config, foreignBookId, format) {
86
+ const client = chaptarr(config);
87
+ const warnings = [];
88
+ const base = { foreign_book_id: foreignBookId, format };
89
+ let result;
90
+ try {
91
+ const lookup = await findFormat(client, foreignBookId, format);
92
+ if (lookup === null) {
93
+ result = { book_id: null, title: null, status: 'not_found', detail: null };
94
+ }
95
+ else {
96
+ const local = preferred(lookup[format]);
97
+ if (local?.hasFiles === true) {
98
+ result = { book_id: local.id, title: lookup.title, status: 'already_exists', detail: null };
99
+ }
100
+ else if (local !== null) {
101
+ await client.setMonitored([local.id], true);
102
+ await client.searchBook(local.id);
103
+ result = { book_id: local.id, title: lookup.title, status: 'searching', detail: null };
104
+ }
105
+ else {
106
+ const { id } = await ensureBook(client, lookup, format, { monitored: true, search: true });
107
+ result = { book_id: id, title: lookup.title, status: 'added', detail: null };
108
+ }
109
+ }
110
+ }
111
+ catch (err) {
112
+ result = { book_id: null, title: null, status: 'error', detail: httpDetail(err) };
113
+ }
114
+ const sabnzbd_paused = await sabPaused(config, warnings);
115
+ return { output: { ...base, ...result, sabnzbd_paused }, warnings };
116
+ }
117
+ function ageDays(publishDate, now) {
118
+ if (publishDate === null)
119
+ return null;
120
+ const time = Date.parse(publishDate);
121
+ return Number.isNaN(time) ? null : Math.max(0, Math.floor((now - time) / DAY_MS));
122
+ }
123
+ export function selectReleases(releases, limit, now = Date.now()) {
124
+ return releases
125
+ .filter((r) => !r.rejections.some((reason) => UNWANTED_REJECTION.test(reason)))
126
+ .slice(0, limit)
127
+ .map((r, i) => ({
128
+ rank: i + 1,
129
+ title: r.title,
130
+ size: r.size,
131
+ quality: r.quality,
132
+ protocol: r.protocol,
133
+ indexer: r.indexer,
134
+ seeders: r.seeders,
135
+ age_days: ageDays(r.publishDate, now),
136
+ guid: r.guid,
137
+ indexer_id: r.indexerId,
138
+ rejections: r.rejections,
139
+ }));
140
+ }
141
+ export async function bookReleases(config, foreignBookId, format, opts) {
142
+ const client = chaptarr(config);
143
+ const lookup = await findFormat(client, foreignBookId, format);
144
+ if (lookup === null)
145
+ throw new Error(`no book ${foreignBookId} in Chaptarr's lookup`);
146
+ const { id } = await ensureBook(client, lookup, format, { monitored: false, search: false });
147
+ const releases = selectReleases(await client.releases(id), opts.maxEntries ?? config.defaults.maxEntries);
148
+ return {
149
+ output: { foreign_book_id: foreignBookId, format, book_id: id, title: lookup.title, releases },
150
+ warnings: [],
151
+ };
152
+ }
153
+ export async function grabRelease(config, bookId, guid, indexerId) {
154
+ const client = chaptarr(config);
155
+ const warnings = [];
156
+ let title = null;
157
+ let result;
158
+ try {
159
+ title = (await client.book(bookId)).title;
160
+ await client.setMonitored([bookId], true);
161
+ await client.grab(guid, indexerId);
162
+ result = { status: 'grabbed', detail: null };
163
+ }
164
+ catch (err) {
165
+ result = { status: 'error', detail: httpDetail(err) };
166
+ }
167
+ const sabnzbd_paused = await sabPaused(config, warnings);
168
+ return { output: { book_id: bookId, title, ...result, sabnzbd_paused }, warnings };
169
+ }
170
+ export async function sendBook(config, bookId, device) {
171
+ const client = chaptarr(config);
172
+ const abs = audiobookshelf(config);
173
+ const base = { book_id: bookId, device };
174
+ let title = null;
175
+ try {
176
+ title = (await client.book(bookId)).title;
177
+ if (!(await abs.ereaderDevices()).includes(device)) {
178
+ return { output: { ...base, title, status: 'unknown_device', detail: null }, warnings: [] };
179
+ }
180
+ const folders = new Set((await client.bookFilePaths(bookId)).map((p) => dirname(p)));
181
+ if (folders.size === 0)
182
+ return { output: { ...base, title, status: 'no_file', detail: null }, warnings: [] };
183
+ for (const library of (await abs.libraries()).filter((l) => l.mediaType === 'book')) {
184
+ const item = (await abs.items(library.id)).find((i) => folders.has(i.path) && i.ebookFormat !== null);
185
+ if (item === undefined)
186
+ continue;
187
+ await abs.sendEbook(item.id, device);
188
+ return { output: { ...base, title, status: 'sent', detail: null }, warnings: [] };
189
+ }
190
+ return { output: { ...base, title, status: 'not_in_audiobookshelf', detail: null }, warnings: [] };
191
+ }
192
+ catch (err) {
193
+ return { output: { ...base, title, status: 'error', detail: httpDetail(err) }, warnings: [] };
194
+ }
195
+ }
@@ -1,4 +1,6 @@
1
- import { cancel, intro, isCancel, log, outro, select, spinner, text } from '@clack/prompts';
1
+ import { cancel, confirm, intro, isCancel, log, outro, select, spinner, text } from '@clack/prompts';
2
+ import { AudiobookshelfClient } from '../clients/audiobookshelf.js';
3
+ import { ChaptarrClient } from '../clients/chaptarr.js';
2
4
  import { OmdbClient } from '../clients/omdb.js';
3
5
  import { RadarrClient } from '../clients/radarr.js';
4
6
  import { SonarrClient } from '../clients/sonarr.js';
@@ -141,6 +143,32 @@ export async function runInit() {
141
143
  const ok = await validated('SABnzbd', () => new SabnzbdClient(url, apiKey).isPaused());
142
144
  return ok === null ? null : { url, apiKey };
143
145
  });
146
+ const wantBooks = await confirm({
147
+ message: 'Set up books (Chaptarr and Audiobookshelf)?',
148
+ initialValue: prior.chaptarr !== undefined,
149
+ });
150
+ if (isCancel(wantBooks))
151
+ bail();
152
+ let books = {};
153
+ if (wantBooks) {
154
+ const chaptarr = await askUntilValid(async () => {
155
+ const url = (await ask('Chaptarr URL (e.g. http://localhost:8789)', prior.chaptarr?.url)).replace(/\/+$/, '');
156
+ const apiKey = await ask('Chaptarr API key (Settings > General > Security)', prior.chaptarr?.apiKey);
157
+ const client = new ChaptarrClient(url, apiKey);
158
+ const ok = await validated('Chaptarr', async () => {
159
+ await client.systemStatus();
160
+ return client.formatDefaults();
161
+ });
162
+ return ok === null ? null : { url, apiKey };
163
+ });
164
+ const audiobookshelf = await askUntilValid(async () => {
165
+ const url = (await ask('Audiobookshelf URL (e.g. http://localhost:13378)', prior.audiobookshelf?.url)).replace(/\/+$/, '');
166
+ const apiKey = await ask('Audiobookshelf API key (Settings > API Keys)', prior.audiobookshelf?.apiKey);
167
+ const ok = await validated('Audiobookshelf', () => new AudiobookshelfClient(url, apiKey).ereaderDevices());
168
+ return ok === null ? null : { url, apiKey };
169
+ });
170
+ books = { chaptarr, audiobookshelf };
171
+ }
144
172
  const config = {
145
173
  tmdb,
146
174
  omdb,
@@ -148,6 +176,7 @@ export async function runInit() {
148
176
  sonarr,
149
177
  sabnzbd,
150
178
  defaults: { maxEntries: prior.defaults?.maxEntries ?? 10 },
179
+ ...books,
151
180
  };
152
181
  saveConfig(config);
153
182
  outro(`Saved ${configPath()} (chmod 600). Try: trendarr trending`);
@@ -0,0 +1,186 @@
1
+ import { OmdbClient } from '../clients/omdb.js';
2
+ import { RadarrClient } from '../clients/radarr.js';
3
+ import { SonarrClient } from '../clients/sonarr.js';
4
+ import { TmdbClient, yearOf } from '../clients/tmdb.js';
5
+ import { mapConcurrent } from '../concurrency.js';
6
+ import { describeError } from '../http.js';
7
+ export const MIN_RATING = 7;
8
+ export const MIN_VOTES = { movies: 5000, series: 2000 };
9
+ export const BECAUSE_NAMES = 3;
10
+ export const CANDIDATE_LIMIT = 200;
11
+ export const RECOMMEND_CONCURRENCY = 5;
12
+ function isPast(date, now) {
13
+ if (date === undefined || date === null || date.length === 0)
14
+ return false;
15
+ const time = Date.parse(date);
16
+ return Number.isFinite(time) && time <= now;
17
+ }
18
+ export function votesOf(value) {
19
+ if (value === null)
20
+ return null;
21
+ const digits = value.replace(/[^0-9]/g, '');
22
+ return digits.length === 0 ? null : Number(digits);
23
+ }
24
+ export function passesThresholds(enrich, minVotes) {
25
+ if (enrich === null || enrich.imdbRating === null)
26
+ return false;
27
+ const rating = Number.parseFloat(enrich.imdbRating);
28
+ const votes = votesOf(enrich.imdbVotes);
29
+ return Number.isFinite(rating) && rating >= MIN_RATING && votes !== null && votes >= minVotes;
30
+ }
31
+ export function rankCandidates(lists, library) {
32
+ const byId = new Map();
33
+ for (const { source, results } of lists) {
34
+ for (const result of results) {
35
+ if (library.has(result.id))
36
+ continue;
37
+ const known = byId.get(result.id);
38
+ if (known === undefined)
39
+ byId.set(result.id, { result, because: [source] });
40
+ else if (!known.because.includes(source))
41
+ known.because.push(source);
42
+ }
43
+ }
44
+ return [...byId.values()].sort((a, b) => b.because.length - a.because.length || b.result.popularity - a.result.popularity);
45
+ }
46
+ async function collect(sources, kind, warnings) {
47
+ const errors = [];
48
+ const lists = await mapConcurrent(sources, RECOMMEND_CONCURRENCY, async (s) => {
49
+ try {
50
+ return { source: s.title, results: await kind.fetch(s.tmdbId) };
51
+ }
52
+ catch (err) {
53
+ errors.push(err);
54
+ return { source: s.title, results: [] };
55
+ }
56
+ });
57
+ if (errors.length > 0 && errors.length === sources.length)
58
+ throw errors[0];
59
+ if (errors.length > 0) {
60
+ warnings.push(`TMDB recommendations failed for ${errors.length} of ${sources.length} library ${kind.label} (${describeError(errors[0])})`);
61
+ }
62
+ return lists;
63
+ }
64
+ async function select(ranked, kind, limit, warnings) {
65
+ const picked = [];
66
+ const queue = ranked.slice(0, CANDIDATE_LIMIT);
67
+ let failures = 0;
68
+ let firstError;
69
+ for (let i = 0; i < queue.length && picked.length < limit; i += RECOMMEND_CONCURRENCY) {
70
+ const batch = queue.slice(i, i + RECOMMEND_CONCURRENCY);
71
+ const checked = await mapConcurrent(batch, RECOMMEND_CONCURRENCY, async (c) => {
72
+ try {
73
+ return await kind.check(c);
74
+ }
75
+ catch (err) {
76
+ failures += 1;
77
+ firstError ??= err;
78
+ return null;
79
+ }
80
+ });
81
+ for (const [j, result] of checked.entries()) {
82
+ const candidate = batch[j];
83
+ if (result === null || candidate === undefined || picked.length >= limit)
84
+ continue;
85
+ picked.push(await kind.toItem(candidate, result, picked.length + 1));
86
+ }
87
+ }
88
+ if (failures > 0)
89
+ warnings.push(`${failures} ${kind.label} candidates could not be checked (${describeError(firstError)})`);
90
+ return picked;
91
+ }
92
+ function baseItem(candidate, checked, rank, title, year, genres) {
93
+ return {
94
+ rank,
95
+ title,
96
+ year,
97
+ imdb_rating: checked.enrich.imdbRating,
98
+ imdb_votes: checked.enrich.imdbVotes,
99
+ rotten_tomatoes: checked.enrich.rottenTomatoes,
100
+ metascore: checked.enrich.metascore,
101
+ genres,
102
+ imdb_id: checked.imdbId,
103
+ tmdb_id: candidate.result.id,
104
+ tvdb_id: checked.tvdbId,
105
+ in_library: false,
106
+ matches: candidate.because.length,
107
+ because: candidate.because.slice(0, BECAUSE_NAMES),
108
+ };
109
+ }
110
+ export async function getRecommendations(config, opts) {
111
+ const tmdb = new TmdbClient(config.tmdb.accessToken);
112
+ const omdb = new OmdbClient(config.omdb.apiKey);
113
+ const radarr = new RadarrClient(config.radarr.url, config.radarr.apiKey);
114
+ const sonarr = new SonarrClient(config.sonarr.url, config.sonarr.apiKey);
115
+ const limit = opts.maxEntries ?? config.defaults.maxEntries;
116
+ const exclude = new Set(opts.exclude ?? []);
117
+ const now = Date.now();
118
+ const warnings = [];
119
+ const movieKind = {
120
+ label: 'movies',
121
+ fetch: (id) => tmdb.movieRecommendations(id),
122
+ check: async (c) => {
123
+ if (!isPast(c.result.release_date, now))
124
+ return null;
125
+ const imdbId = await tmdb.movieImdbId(c.result.id);
126
+ if (imdbId === null || exclude.has(imdbId))
127
+ return null;
128
+ if (!(await tmdb.movieHomeRelease(c.result.id, now)))
129
+ return null;
130
+ const enrich = await omdb.byImdbId(imdbId);
131
+ return passesThresholds(enrich, MIN_VOTES.movies) ? { imdbId, tvdbId: null, enrich } : null;
132
+ },
133
+ toItem: async (c, checked, rank) => baseItem(c, checked, rank, c.result.title, yearOf(c.result.release_date), await tmdb.genres('movie', c.result.genre_ids)),
134
+ };
135
+ const recommendMovies = async () => {
136
+ let library;
137
+ try {
138
+ library = await radarr.libraryMovies();
139
+ }
140
+ catch (err) {
141
+ warnings.push(`Radarr unreachable — no movie recommendations (${describeError(err)})`);
142
+ return [];
143
+ }
144
+ if (library.length === 0)
145
+ return [];
146
+ const lists = await collect(library, movieKind, warnings);
147
+ const ranked = rankCandidates(lists, new Set(library.map((m) => m.tmdbId)));
148
+ return select(ranked, movieKind, limit, warnings);
149
+ };
150
+ const recommendSeries = async () => {
151
+ let library;
152
+ try {
153
+ library = await sonarr.librarySeries();
154
+ }
155
+ catch (err) {
156
+ warnings.push(`Sonarr unreachable — no series recommendations (${describeError(err)})`);
157
+ return [];
158
+ }
159
+ const libraryTvdb = new Set(library.flatMap((s) => (s.tvdbId === null ? [] : [s.tvdbId])));
160
+ const sources = library.flatMap((s) => (s.tmdbId === null ? [] : [{ tmdbId: s.tmdbId, title: s.title }]));
161
+ if (sources.length === 0)
162
+ return [];
163
+ const seriesKind = {
164
+ label: 'series',
165
+ fetch: (id) => tmdb.showRecommendations(id),
166
+ check: async (c) => {
167
+ if (!isPast(c.result.first_air_date, now))
168
+ return null;
169
+ const { imdbId, tvdbId } = await tmdb.showExternalIds(c.result.id);
170
+ if (imdbId === null || exclude.has(imdbId) || (tvdbId !== null && libraryTvdb.has(tvdbId)))
171
+ return null;
172
+ const enrich = await omdb.byImdbId(imdbId);
173
+ return passesThresholds(enrich, MIN_VOTES.series) ? { imdbId, tvdbId, enrich } : null;
174
+ },
175
+ toItem: async (c, checked, rank) => baseItem(c, checked, rank, c.result.name, yearOf(c.result.first_air_date), await tmdb.genres('tv', c.result.genre_ids)),
176
+ };
177
+ const lists = await collect(sources, seriesKind, warnings);
178
+ const ranked = rankCandidates(lists, new Set(sources.map((s) => s.tmdbId)));
179
+ return select(ranked, seriesKind, limit, warnings);
180
+ };
181
+ const [movies, series] = await Promise.all([
182
+ opts.type === 'series' ? Promise.resolve([]) : recommendMovies(),
183
+ opts.type === 'movies' ? Promise.resolve([]) : recommendSeries(),
184
+ ]);
185
+ return { output: { movies, series }, warnings };
186
+ }
package/dist/config.js CHANGED
@@ -8,6 +8,7 @@ const arrSchema = z.object({
8
8
  qualityProfileId: z.number().int().positive(),
9
9
  rootFolderPath: z.string().min(1),
10
10
  });
11
+ const serviceSchema = z.object({ url: z.string().min(1), apiKey: z.string().min(1) });
11
12
  export const configSchema = z.object({
12
13
  tmdb: z.object({ accessToken: z.string().min(1) }),
13
14
  omdb: z.object({ apiKey: z.string().min(1) }),
@@ -15,6 +16,8 @@ export const configSchema = z.object({
15
16
  sonarr: arrSchema.extend({ monitor: z.string().min(1) }),
16
17
  sabnzbd: z.object({ url: z.string().min(1), apiKey: z.string().min(1) }),
17
18
  defaults: z.object({ maxEntries: z.number().int().positive() }),
19
+ chaptarr: serviceSchema.optional(),
20
+ audiobookshelf: serviceSchema.optional(),
18
21
  });
19
22
  export class ConfigError extends Error {
20
23
  constructor(message) {
package/dist/format.js CHANGED
@@ -19,6 +19,15 @@ function searchRows(items) {
19
19
  const rows = items.map((i) => `${cell(String(i.rank), 3)} ${cell(i.title, 34)} ${cell(dash(i.year), 5)} ${cell(dash(i.imdb_rating), 5)} ${cell(tableLib(i), 3)} ${tableLink(i)}`);
20
20
  return [pc.bold(header), ...rows];
21
21
  }
22
+ function recommendRows(items) {
23
+ const header = `${cell('#', 3)} ${cell('TITLE', 34)} ${cell('YEAR', 5)} ${cell('IMDB', 5)} ${cell('VOTES', 10)} ${cell('BECAUSE', 40)} LINK`;
24
+ const rows = items.map((i) => {
25
+ const more = i.matches - i.because.length;
26
+ const because = `${i.because.join(', ')}${more > 0 ? ` +${more}` : ''}`;
27
+ return `${cell(String(i.rank), 3)} ${cell(i.title, 34)} ${cell(dash(i.year), 5)} ${cell(dash(i.imdb_rating), 5)} ${cell(dash(i.imdb_votes), 10)} ${cell(because, 40)} ${tableLink(i)}`;
28
+ });
29
+ return [pc.bold(header), ...rows];
30
+ }
22
31
  function renderBlocks(movies, series, moviesEmpty, seriesEmpty) {
23
32
  const sections = [];
24
33
  if (!moviesEmpty)
@@ -35,6 +44,9 @@ function renderBlocks(movies, series, moviesEmpty, seriesEmpty) {
35
44
  export function renderTrendingTable(output) {
36
45
  return renderBlocks(trendingRows(output.movies), trendingRows(output.series), output.movies.length === 0, output.series.length === 0);
37
46
  }
47
+ export function renderRecommendTable(output) {
48
+ return renderBlocks(recommendRows(output.movies), recommendRows(output.series), output.movies.length === 0, output.series.length === 0);
49
+ }
38
50
  export function renderSearchTable(output) {
39
51
  return renderBlocks(searchRows(output.movies), searchRows(output.series), output.movies.length === 0, output.series.length === 0);
40
52
  }
@@ -85,3 +97,48 @@ export function renderAddTable(output) {
85
97
  const sab = output.sabnzbd_paused === null ? 'SABnzbd status: unknown' : renderSabStatus(output.sabnzbd_paused);
86
98
  return [...lines, '', sab].join('\n');
87
99
  }
100
+ function formatCell(state) {
101
+ if (state.has_file)
102
+ return '✓';
103
+ if (state.monitored)
104
+ return 'wanted';
105
+ return state.book_id === null ? '' : 'known';
106
+ }
107
+ export function renderBookSearchTable(output) {
108
+ if (output.books.length === 0)
109
+ return 'No results.';
110
+ const header = `${cell('#', 3)} ${cell('TITLE', 40)} ${cell('AUTHOR', 24)} ${cell('AUDIO', 7)} ${cell('EBOOK', 7)} ID`;
111
+ const rows = output.books.map((b) => `${cell(String(b.rank), 3)} ${cell(b.title, 40)} ${cell(dash(b.author), 24)} ${cell(formatCell(b.audiobook), 7)} ${cell(formatCell(b.ebook), 7)} ${b.foreign_book_id}`);
112
+ const kindles = output.kindles.length === 0 ? 'Kindles: none' : `Kindles: ${output.kindles.join(', ')}`;
113
+ return [pc.bold(header), ...rows, '', kindles].join('\n');
114
+ }
115
+ function statusColor(status, good) {
116
+ return good.includes(status) ? pc.green(status) : status === 'already_exists' ? pc.yellow(status) : pc.red(status);
117
+ }
118
+ function sabLine(paused) {
119
+ return paused === null ? 'SABnzbd status: unknown' : renderSabStatus(paused);
120
+ }
121
+ export function renderBookAdd(output) {
122
+ const detail = output.detail === null ? '' : ` (${output.detail})`;
123
+ const line = `${output.title ?? output.foreign_book_id} [${output.format}] ${statusColor(output.status, ['added', 'searching'])}${detail}`;
124
+ return [line, '', sabLine(output.sabnzbd_paused)].join('\n');
125
+ }
126
+ function megabytes(size) {
127
+ return size === null ? '-' : `${Math.round(size / 1_048_576)} MB`;
128
+ }
129
+ export function renderReleasesTable(output) {
130
+ const title = `${output.title} [${output.format}] book ${output.book_id}`;
131
+ if (output.releases.length === 0)
132
+ 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, 60)} ${cell(megabytes(r.size), 9)} ${cell(dash(r.quality), 13)} ${cell(r.protocol === 'usenet' ? 'nzb' : dash(r.seeders), 5)} ${r.age_days === null ? '-' : `${r.age_days}d`}`);
135
+ return [title, pc.bold(header), ...rows].join('\n');
136
+ }
137
+ export function renderBookGrab(output) {
138
+ const detail = output.detail === null ? '' : ` (${output.detail})`;
139
+ return [`${output.title ?? `book ${output.book_id}`} ${statusColor(output.status, ['grabbed'])}${detail}`, '', sabLine(output.sabnzbd_paused)].join('\n');
140
+ }
141
+ export function renderBookSend(output) {
142
+ const detail = output.detail === null ? '' : ` (${output.detail})`;
143
+ return `${output.title ?? `book ${output.book_id}`} → ${output.device}: ${statusColor(output.status, ['sent'])}${detail}`;
144
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/trendarr",
3
- "version": "0.6.0",
3
+ "version": "0.9.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",
@@ -42,6 +42,6 @@
42
42
  },
43
43
  "repository": {
44
44
  "type": "git",
45
- "url": "git+https://github.com/astrofoundry/traktarr.git"
45
+ "url": "git+https://github.com/astrofoundry/trendarr.git"
46
46
  }
47
47
  }
@@ -1,91 +0,0 @@
1
- import { z } from 'zod';
2
- import { HttpError, fetchJson } from '../http.js';
3
- const BASE = 'https://api.trakt.tv';
4
- const idsSchema = z.object({
5
- imdb: z.string().nullish(),
6
- tmdb: z.number().nullish(),
7
- tvdb: z.number().nullish(),
8
- });
9
- const mediaSchema = z.object({
10
- title: z.string(),
11
- year: z.number().nullish(),
12
- ids: idsSchema,
13
- rating: z.number().nullish(),
14
- votes: z.number().nullish(),
15
- genres: z.array(z.string()).nullish(),
16
- });
17
- const trendingMoviesSchema = z.array(z.object({ watchers: z.number(), movie: mediaSchema }));
18
- const trendingShowsSchema = z.array(z.object({ watchers: z.number(), show: mediaSchema }));
19
- const showSearchSchema = z.array(z.object({ type: z.string(), show: mediaSchema.optional() }));
20
- const movieResultsSchema = z.array(z.object({ type: z.string(), movie: mediaSchema.optional() }));
21
- const showResultsSchema = z.array(z.object({ type: z.string(), show: mediaSchema.optional() }));
22
- function toMedia(media) {
23
- return {
24
- title: media.title,
25
- year: media.year ?? null,
26
- imdbId: media.ids.imdb ?? null,
27
- tmdbId: media.ids.tmdb ?? null,
28
- tvdbId: media.ids.tvdb ?? null,
29
- rating: media.rating ?? null,
30
- votes: media.votes ?? null,
31
- genres: media.genres ?? [],
32
- };
33
- }
34
- function toTrending(watchers, media) {
35
- return { ...toMedia(media), watchers };
36
- }
37
- export class TraktClient {
38
- clientId;
39
- constructor(clientId) {
40
- this.clientId = clientId;
41
- }
42
- headers() {
43
- return {
44
- 'trakt-api-version': '2',
45
- 'trakt-api-key': this.clientId,
46
- 'User-Agent': 'traktarr',
47
- };
48
- }
49
- async get(path) {
50
- const url = `${BASE}${path}`;
51
- try {
52
- return await fetchJson(url, { headers: this.headers() });
53
- }
54
- catch (err) {
55
- if (err instanceof HttpError && err.status === 429 && err.retryAfterSeconds !== undefined) {
56
- const retryAfterSeconds = err.retryAfterSeconds;
57
- await new Promise((r) => setTimeout(r, retryAfterSeconds * 1000));
58
- return fetchJson(url, { headers: this.headers() });
59
- }
60
- throw err;
61
- }
62
- }
63
- async trendingMovies(limit) {
64
- const raw = await this.get(`/movies/trending?extended=full&limit=${limit}`);
65
- return trendingMoviesSchema.parse(raw).map((e) => toTrending(e.watchers, e.movie));
66
- }
67
- async trendingShows(limit) {
68
- const raw = await this.get(`/shows/trending?extended=full&limit=${limit}`);
69
- return trendingShowsSchema.parse(raw).map((e) => toTrending(e.watchers, e.show));
70
- }
71
- async searchMovies(query, limit) {
72
- const raw = await this.get(`/search/movie?query=${encodeURIComponent(query)}&extended=full&limit=${limit}`);
73
- return movieResultsSchema
74
- .parse(raw)
75
- .flatMap((r) => (r.movie === undefined ? [] : [toMedia(r.movie)]));
76
- }
77
- async searchShows(query, limit) {
78
- const raw = await this.get(`/search/show?query=${encodeURIComponent(query)}&extended=full&limit=${limit}`);
79
- return showResultsSchema.parse(raw).flatMap((r) => (r.show === undefined ? [] : [toMedia(r.show)]));
80
- }
81
- async findShowTvdbIdByImdb(imdbId) {
82
- const raw = await this.get(`/search/imdb/${imdbId}?type=show`);
83
- const results = showSearchSchema.parse(raw);
84
- for (const result of results) {
85
- const tvdb = result.show?.ids.tvdb;
86
- if (typeof tvdb === 'number')
87
- return tvdb;
88
- }
89
- return null;
90
- }
91
- }