@dominevo/series-scraper-core 0.0.92 → 0.0.93

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.
@@ -29,6 +29,9 @@ exports.DEFAULT_SETTINGS = {
29
29
  autoBind: false,
30
30
  autoStart: false,
31
31
  moveEp: true,
32
+ libraryOpenPermissions: true,
33
+ libraryDirMode: '0777',
34
+ libraryFileMode: '0666',
32
35
  renameEp: true,
33
36
  tagsMode: 'BLACKLIST',
34
37
  logLevel: 'info',
@@ -301,6 +301,10 @@ export declare class DownloadService implements OnApplicationBootstrap, OnModule
301
301
  /**
302
302
  * Move a file atomically. Falls back to copy+delete if src and dest are on different devices.
303
303
  */
304
+ /** The season folder name: Sonarr's own naming when readable, else "Season NN". */
305
+ private seasonFolderName;
306
+ /** mkdir the library dir, move the file in, and open permissions on both (a chmod failure never fails the move). */
307
+ private placeInLibrary;
304
308
  private moveFile;
305
309
  /**
306
310
  * Strip filesystem-reserved characters from a filename component.
@@ -83,6 +83,7 @@ const captcha_service_1 = require("./captcha.service");
83
83
  const maxstream_page_1 = require("./maxstream-page");
84
84
  const captcha_fallback_1 = require("./captcha-fallback");
85
85
  const failure_reason_1 = require("./failure-reason");
86
+ const library_permissions_1 = require("./library-permissions");
86
87
  /**
87
88
  * Bounded-concurrency scheduler with **per-group auto-balancing cap**.
88
89
  *
@@ -716,7 +717,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
716
717
  }
717
718
  if (!cachedFinalDirBase)
718
719
  return null;
719
- const seasonFolder = `Season ${String(seasonNumber).padStart(2, '0')}`;
720
+ const seasonFolder = await this.seasonFolderName(seasonNumber);
720
721
  return path.join(path.resolve(settings.sonarrRootPath), cachedFinalDirBase, seasonFolder);
721
722
  };
722
723
  const tempDir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
@@ -1026,8 +1027,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1026
1027
  this.logger.log(`${attemptTag} downloading → ${fileName}`);
1027
1028
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, childId, job);
1028
1029
  if (finalDir) {
1029
- await fs.mkdir(finalDir, { recursive: true });
1030
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
1030
+ await this.placeInLibrary(tempPath, finalDir);
1031
1031
  }
1032
1032
  await this.sonarr.rescanSeries(entry.arrId);
1033
1033
  if (settings.renameEp)
@@ -1341,9 +1341,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1341
1341
  // Move atomically to Radarr's library folder if moveEp is enabled
1342
1342
  let finalPath = tempPath;
1343
1343
  if (finalDir) {
1344
- await fs.mkdir(finalDir, { recursive: true });
1345
- const destPath = path.join(finalDir, path.basename(tempPath));
1346
- await this.moveFile(tempPath, destPath);
1344
+ const destPath = await this.placeInLibrary(tempPath, finalDir);
1347
1345
  finalPath = destPath;
1348
1346
  }
1349
1347
  await this.radarr.rescanMovie(entry.arrId);
@@ -2240,6 +2238,20 @@ let DownloadService = DownloadService_1 = class DownloadService {
2240
2238
  /**
2241
2239
  * Move a file atomically. Falls back to copy+delete if src and dest are on different devices.
2242
2240
  */
2241
+ /** The season folder name: Sonarr's own naming when readable, else "Season NN". */
2242
+ async seasonFolderName(season) {
2243
+ const named = await this.sonarr.getSeasonFolderName(season);
2244
+ return named ?? `Season ${String(season).padStart(2, '0')}`;
2245
+ }
2246
+ /** mkdir the library dir, move the file in, and open permissions on both (a chmod failure never fails the move). */
2247
+ async placeInLibrary(tempPath, finalDir) {
2248
+ const settings = this.settings.get();
2249
+ await (0, library_permissions_1.mkdirLibrary)(finalDir, settings, this.logger);
2250
+ const dest = path.join(finalDir, path.basename(tempPath));
2251
+ await this.moveFile(tempPath, dest);
2252
+ await (0, library_permissions_1.openLibraryFile)(dest, settings, this.logger);
2253
+ return dest;
2254
+ }
2243
2255
  async moveFile(src, dest) {
2244
2256
  try {
2245
2257
  await fs.rename(src, dest);
@@ -3068,7 +3080,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3068
3080
  const series = await this.sonarr.getSeriesById(entry.arrId);
3069
3081
  if (series) {
3070
3082
  const seriesFolder = path.basename(series.path);
3071
- const seasonFolder = `Season ${String(season).padStart(2, '0')}`;
3083
+ const seasonFolder = await this.seasonFolderName(season);
3072
3084
  finalDir = path.join(path.resolve(settings.sonarrRootPath), seriesFolder, seasonFolder);
3073
3085
  }
3074
3086
  }
@@ -3100,8 +3112,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3100
3112
  this.logger.log(`${attemptTag} downloading → ${fileName}`);
3101
3113
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, entry.id, job);
3102
3114
  if (finalDir) {
3103
- await fs.mkdir(finalDir, { recursive: true });
3104
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
3115
+ await this.placeInLibrary(tempPath, finalDir);
3105
3116
  }
3106
3117
  await this.sonarr.rescanSeries(entry.arrId);
3107
3118
  if (settings.renameEp)
@@ -3153,8 +3164,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3153
3164
  };
3154
3165
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, entry.id, job);
3155
3166
  if (finalDir) {
3156
- await fs.mkdir(finalDir, { recursive: true });
3157
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
3167
+ await this.placeInLibrary(tempPath, finalDir);
3158
3168
  }
3159
3169
  await this.radarr.rescanMovie(entry.arrId);
3160
3170
  if (settings.renameEp)
@@ -3389,13 +3399,12 @@ let DownloadService = DownloadService_1 = class DownloadService {
3389
3399
  const series = await this.sonarr.getSeriesById(entry.arrId);
3390
3400
  if (series) {
3391
3401
  const seriesFolder = path.basename(series.path);
3392
- const seasonFolder = `Season ${String(partial.season).padStart(2, '0')}`;
3402
+ const seasonFolder = await this.seasonFolderName(partial.season);
3393
3403
  finalDir = path.join(path.resolve(settings.sonarrRootPath), seriesFolder, seasonFolder);
3394
3404
  }
3395
3405
  }
3396
3406
  if (finalDir) {
3397
- await fs.mkdir(finalDir, { recursive: true });
3398
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
3407
+ await this.placeInLibrary(tempPath, finalDir);
3399
3408
  }
3400
3409
  await this.sonarr.rescanSeries(entry.arrId);
3401
3410
  if (settings.renameEp)
@@ -3416,8 +3425,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3416
3425
  finalDir = path.join(path.resolve(settings.radarrRootPath), path.basename(movie.path));
3417
3426
  }
3418
3427
  if (finalDir) {
3419
- await fs.mkdir(finalDir, { recursive: true });
3420
- await this.moveFile(tempPath, path.join(finalDir, path.basename(tempPath)));
3428
+ await this.placeInLibrary(tempPath, finalDir);
3421
3429
  }
3422
3430
  await this.radarr.rescanMovie(entry.arrId);
3423
3431
  if (settings.renameEp)
@@ -0,0 +1,27 @@
1
+ /** Unraid "New Permissions" convention: every user may read and write the library. */
2
+ export declare const DEFAULT_LIBRARY_DIR_MODE = "0777";
3
+ export declare const DEFAULT_LIBRARY_FILE_MODE = "0666";
4
+ export interface LibraryPermissionSettings {
5
+ libraryOpenPermissions?: boolean;
6
+ libraryDirMode?: string;
7
+ libraryFileMode?: string;
8
+ }
9
+ export interface PermissionLog {
10
+ warn(message: string): void;
11
+ }
12
+ /** Parse an octal string ("0777", "777", "0o775"); null when it is not a valid mode. */
13
+ export declare function parseOctalMode(raw: unknown): number | null;
14
+ /** chmod that never throws: a failure is logged with the path and errno. */
15
+ export declare function chmodQuiet(target: string, mode: number, log: PermissionLog): Promise<void>;
16
+ /**
17
+ * mkdir -p that also opens every directory it CREATED (an existing ancestor is
18
+ * left alone). `recursive` mkdir applies the umask, so each new level is chmod-ed.
19
+ */
20
+ export declare function mkdirLibrary(dir: string, s: LibraryPermissionSettings, log: PermissionLog): Promise<void>;
21
+ /** Open a file that was just moved or copied into a library. */
22
+ export declare function openLibraryFile(file: string, s: LibraryPermissionSettings, log: PermissionLog): Promise<void>;
23
+ /**
24
+ * Render a Sonarr `seasonFolderFormat`. Only `{season}` and `{season:00}` are
25
+ * understood; any other token returns null so the caller falls back.
26
+ */
27
+ export declare function renderSeasonFolder(format: string, season: number): string | null;
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DEFAULT_LIBRARY_FILE_MODE = exports.DEFAULT_LIBRARY_DIR_MODE = void 0;
37
+ exports.parseOctalMode = parseOctalMode;
38
+ exports.chmodQuiet = chmodQuiet;
39
+ exports.mkdirLibrary = mkdirLibrary;
40
+ exports.openLibraryFile = openLibraryFile;
41
+ exports.renderSeasonFolder = renderSeasonFolder;
42
+ const fs = __importStar(require("fs/promises"));
43
+ const path = __importStar(require("path"));
44
+ /** Unraid "New Permissions" convention: every user may read and write the library. */
45
+ exports.DEFAULT_LIBRARY_DIR_MODE = '0777';
46
+ exports.DEFAULT_LIBRARY_FILE_MODE = '0666';
47
+ /** Parse an octal string ("0777", "777", "0o775"); null when it is not a valid mode. */
48
+ function parseOctalMode(raw) {
49
+ if (typeof raw !== 'string')
50
+ return null;
51
+ const text = raw.trim().replace(/^0o/i, '');
52
+ if (!/^[0-7]{3,4}$/.test(text))
53
+ return null;
54
+ return parseInt(text, 8);
55
+ }
56
+ function modeOrDefault(raw, fallback) {
57
+ return parseOctalMode(raw) ?? parseOctalMode(fallback);
58
+ }
59
+ function errnoOf(err) {
60
+ if (err && typeof err === 'object' && 'code' in err)
61
+ return String(err.code);
62
+ return 'unknown';
63
+ }
64
+ /** chmod that never throws: a failure is logged with the path and errno. */
65
+ async function chmodQuiet(target, mode, log) {
66
+ try {
67
+ await fs.chmod(target, mode);
68
+ }
69
+ catch (err) {
70
+ log.warn(`chmod ${mode.toString(8)} failed on ${target} (${errnoOf(err)}): ${err instanceof Error ? err.message : String(err)}`);
71
+ }
72
+ }
73
+ /**
74
+ * mkdir -p that also opens every directory it CREATED (an existing ancestor is
75
+ * left alone). `recursive` mkdir applies the umask, so each new level is chmod-ed.
76
+ */
77
+ async function mkdirLibrary(dir, s, log) {
78
+ const first = await fs.mkdir(dir, { recursive: true });
79
+ if (s.libraryOpenPermissions === false || !first)
80
+ return;
81
+ const mode = modeOrDefault(s.libraryDirMode, exports.DEFAULT_LIBRARY_DIR_MODE);
82
+ // `first` is the topmost directory created; open it and every level down to `dir`.
83
+ const levels = [];
84
+ for (let cur = dir;; cur = path.dirname(cur)) {
85
+ levels.unshift(cur);
86
+ if (cur === first || path.dirname(cur) === cur)
87
+ break;
88
+ }
89
+ for (const level of levels)
90
+ await chmodQuiet(level, mode, log);
91
+ }
92
+ /** Open a file that was just moved or copied into a library. */
93
+ async function openLibraryFile(file, s, log) {
94
+ if (s.libraryOpenPermissions === false)
95
+ return;
96
+ await chmodQuiet(file, modeOrDefault(s.libraryFileMode, exports.DEFAULT_LIBRARY_FILE_MODE), log);
97
+ }
98
+ /**
99
+ * Render a Sonarr `seasonFolderFormat`. Only `{season}` and `{season:00}` are
100
+ * understood; any other token returns null so the caller falls back.
101
+ */
102
+ function renderSeasonFolder(format, season) {
103
+ let unknown = false;
104
+ const out = format.replace(/\{([^}]*)\}/g, (_m, token) => {
105
+ if (token === 'season')
106
+ return String(season);
107
+ if (token === 'season:00')
108
+ return String(season).padStart(2, '0');
109
+ unknown = true;
110
+ return '';
111
+ });
112
+ return unknown || !out.trim() ? null : out;
113
+ }
@@ -3,7 +3,15 @@ import { SettingsService } from './settings.service';
3
3
  export declare class SonarrService {
4
4
  private readonly settings;
5
5
  private readonly logger;
6
+ /** Sonarr's `seasonFolderFormat`, per Sonarr address; null = unreadable (fall back). */
7
+ private namingCache;
8
+ private namingErrorLogged;
6
9
  constructor(settings: SettingsService);
10
+ /**
11
+ * The season folder name as Sonarr itself would build it ("Season 5" or "Season 05"), from its naming
12
+ * config. Null when Sonarr is absent, errors (logged once) or uses a token we do not render.
13
+ */
14
+ getSeasonFolderName(season: number): Promise<string | null>;
7
15
  private getConfig;
8
16
  status(): Promise<{
9
17
  configured: boolean;
@@ -16,10 +16,41 @@ const logger_1 = require("../ports/logger");
16
16
  const egress_context_1 = require("./egress/egress-context");
17
17
  const arr_images_1 = require("./arr-images");
18
18
  const settings_service_1 = require("./settings.service");
19
+ const library_permissions_1 = require("./library-permissions");
19
20
  let SonarrService = SonarrService_1 = class SonarrService {
20
21
  constructor(settings) {
21
22
  this.settings = settings;
22
23
  this.logger = new logger_1.ScopedLogger(SonarrService_1.name);
24
+ /** Sonarr's `seasonFolderFormat`, per Sonarr address; null = unreadable (fall back). */
25
+ this.namingCache = null;
26
+ this.namingErrorLogged = false;
27
+ }
28
+ /**
29
+ * The season folder name as Sonarr itself would build it ("Season 5" or "Season 05"), from its naming
30
+ * config. Null when Sonarr is absent, errors (logged once) or uses a token we do not render.
31
+ */
32
+ async getSeasonFolderName(season) {
33
+ const config = this.getConfig();
34
+ if (!config)
35
+ return null;
36
+ const key = `${config.url}\n${config.apiKey}`;
37
+ if (this.namingCache?.key !== key) {
38
+ let format = null;
39
+ try {
40
+ const data = await this.apiGet(config, '/api/v3/config/naming');
41
+ format = typeof data.seasonFolderFormat === 'string' ? data.seasonFolderFormat : null;
42
+ this.namingErrorLogged = false;
43
+ }
44
+ catch (err) {
45
+ if (!this.namingErrorLogged) {
46
+ this.namingErrorLogged = true;
47
+ this.logger.warn(`Sonarr naming config unreadable, using "Season NN" folders: ${err}`);
48
+ }
49
+ return null; // not cached: a later call retries
50
+ }
51
+ this.namingCache = { key, format };
52
+ }
53
+ return this.namingCache.format ? (0, library_permissions_1.renderSeasonFolder)(this.namingCache.format, season) : null;
23
54
  }
24
55
  getConfig() {
25
56
  const s = this.settings.get();
package/dist/types.d.ts CHANGED
@@ -441,6 +441,12 @@ export interface AppSettings {
441
441
  scanDelay: number;
442
442
  autoBind: boolean;
443
443
  moveEp: boolean;
444
+ /** chmod everything the scraper puts in a library so Sonarr/Radarr (another uid) can rename it. */
445
+ libraryOpenPermissions: boolean;
446
+ /** Octal mode for directories the scraper creates in a library. */
447
+ libraryDirMode: string;
448
+ /** Octal mode for files the scraper moves into a library. */
449
+ libraryFileMode: string;
444
450
  renameEp: boolean;
445
451
  tagsMode: 'WHITELIST' | 'BLACKLIST';
446
452
  logLevel: 'debug' | 'info' | 'warning' | 'error';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dominevo/series-scraper-core",
3
- "version": "0.0.92",
3
+ "version": "0.0.93",
4
4
  "description": "Host-agnostic scraper core: services, repositories, controllers and the ports a host supplies",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",