@dominevo/series-scraper-core 0.0.93 → 0.0.94

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.
@@ -303,6 +303,8 @@ export declare class DownloadService implements OnApplicationBootstrap, OnModule
303
303
  */
304
304
  /** The season folder name: Sonarr's own naming when readable, else "Season NN". */
305
305
  private seasonFolderName;
306
+ /** A finished download goes into the library only once ffmpeg can read a video in it; else it is deleted and the job fails. */
307
+ private placeDownloadInLibrary;
306
308
  /** mkdir the library dir, move the file in, and open permissions on both (a chmod failure never fails the move). */
307
309
  private placeInLibrary;
308
310
  private moveFile;
@@ -47,6 +47,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
47
47
  var DownloadService_1;
48
48
  Object.defineProperty(exports, "__esModule", { value: true });
49
49
  exports.DownloadService = void 0;
50
+ const media_verify_1 = require("./media-verify");
50
51
  const common_1 = require("@nestjs/common");
51
52
  const tokens_1 = require("../ports/tokens");
52
53
  const logger_1 = require("../ports/logger");
@@ -1027,7 +1028,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1027
1028
  this.logger.log(`${attemptTag} downloading → ${fileName}`);
1028
1029
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, childId, job);
1029
1030
  if (finalDir) {
1030
- await this.placeInLibrary(tempPath, finalDir);
1031
+ await this.placeDownloadInLibrary(tempPath, finalDir);
1031
1032
  }
1032
1033
  await this.sonarr.rescanSeries(entry.arrId);
1033
1034
  if (settings.renameEp)
@@ -1341,7 +1342,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1341
1342
  // Move atomically to Radarr's library folder if moveEp is enabled
1342
1343
  let finalPath = tempPath;
1343
1344
  if (finalDir) {
1344
- const destPath = await this.placeInLibrary(tempPath, finalDir);
1345
+ const destPath = await this.placeDownloadInLibrary(tempPath, finalDir);
1345
1346
  finalPath = destPath;
1346
1347
  }
1347
1348
  await this.radarr.rescanMovie(entry.arrId);
@@ -2243,6 +2244,16 @@ let DownloadService = DownloadService_1 = class DownloadService {
2243
2244
  const named = await this.sonarr.getSeasonFolderName(season);
2244
2245
  return named ?? `Season ${String(season).padStart(2, '0')}`;
2245
2246
  }
2247
+ /** A finished download goes into the library only once ffmpeg can read a video in it; else it is deleted and the job fails. */
2248
+ async placeDownloadInLibrary(tempPath, finalDir) {
2249
+ const verdict = await (0, media_verify_1.verifyMediaFile)(await this.binaries.ffmpeg(), tempPath);
2250
+ if (!verdict.ok) {
2251
+ this.logger.error(`Refusing to place ${path.basename(tempPath)} in the library: ${verdict.reason}`);
2252
+ await fs.unlink(tempPath).catch(() => { });
2253
+ throw new Error(`Downloaded file is not a playable video: ${verdict.reason}`);
2254
+ }
2255
+ return this.placeInLibrary(tempPath, finalDir);
2256
+ }
2246
2257
  /** mkdir the library dir, move the file in, and open permissions on both (a chmod failure never fails the move). */
2247
2258
  async placeInLibrary(tempPath, finalDir) {
2248
2259
  const settings = this.settings.get();
@@ -2756,6 +2767,13 @@ let DownloadService = DownloadService_1 = class DownloadService {
2756
2767
  fs.unlink(outputPath).catch(() => { });
2757
2768
  reject(new Error('Download cancelled'));
2758
2769
  }
2770
+ else if (code === 0 && (0, media_verify_1.hlsStoppedEarly)(totalDuration, currentTimeSec)) {
2771
+ // ffmpeg exits 0 on a shutdown signal too (process restart, not a user abort): the file is truncated.
2772
+ const message = `ffmpeg stopped at ${Math.round(currentTimeSec)} of ${Math.round(totalDuration)} s`;
2773
+ this.logger.error(`HLS download incomplete (${message}): ${outputPath}`);
2774
+ fs.unlink(outputPath).catch(() => { });
2775
+ reject(new Error(message));
2776
+ }
2759
2777
  else if (code === 0) {
2760
2778
  this.logger.log(`HLS download completed: ${outputPath}`);
2761
2779
  resolve();
@@ -3112,7 +3130,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3112
3130
  this.logger.log(`${attemptTag} downloading → ${fileName}`);
3113
3131
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, entry.id, job);
3114
3132
  if (finalDir) {
3115
- await this.placeInLibrary(tempPath, finalDir);
3133
+ await this.placeDownloadInLibrary(tempPath, finalDir);
3116
3134
  }
3117
3135
  await this.sonarr.rescanSeries(entry.arrId);
3118
3136
  if (settings.renameEp)
@@ -3164,7 +3182,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3164
3182
  };
3165
3183
  const tempPath = await this.downloadFile(resolvedLink, tempDir, fileName, entry.id, job);
3166
3184
  if (finalDir) {
3167
- await this.placeInLibrary(tempPath, finalDir);
3185
+ await this.placeDownloadInLibrary(tempPath, finalDir);
3168
3186
  }
3169
3187
  await this.radarr.rescanMovie(entry.arrId);
3170
3188
  if (settings.renameEp)
@@ -3404,7 +3422,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3404
3422
  }
3405
3423
  }
3406
3424
  if (finalDir) {
3407
- await this.placeInLibrary(tempPath, finalDir);
3425
+ await this.placeDownloadInLibrary(tempPath, finalDir);
3408
3426
  }
3409
3427
  await this.sonarr.rescanSeries(entry.arrId);
3410
3428
  if (settings.renameEp)
@@ -3425,7 +3443,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3425
3443
  finalDir = path.join(path.resolve(settings.radarrRootPath), path.basename(movie.path));
3426
3444
  }
3427
3445
  if (finalDir) {
3428
- await this.placeInLibrary(tempPath, finalDir);
3446
+ await this.placeDownloadInLibrary(tempPath, finalDir);
3429
3447
  }
3430
3448
  await this.radarr.rescanMovie(entry.arrId);
3431
3449
  if (settings.renameEp)
@@ -0,0 +1,19 @@
1
+ /** An ffmpeg that exits 0 before this share of the stream length was written did not finish. */
2
+ export declare const HLS_COMPLETE_SHARE = 0.97;
3
+ /** True when ffmpeg stopped (even with code 0) well short of the length it announced. Unknown length: false. */
4
+ export declare function hlsStoppedEarly(totalDurationSec: number, currentTimeSec: number): boolean;
5
+ export interface MediaProbe {
6
+ readonly hasVideo: boolean;
7
+ readonly durationSec: number;
8
+ }
9
+ export type MediaVerdict = {
10
+ readonly ok: true;
11
+ readonly durationSec: number;
12
+ } | {
13
+ readonly ok: false;
14
+ readonly reason: string;
15
+ };
16
+ /** Reads what `ffmpeg -i <file>` prints to stderr: a Video stream and the Duration line. */
17
+ export declare function parseMediaProbe(stderr: string): MediaProbe;
18
+ /** Is `file` a playable video: non-empty, has a video stream, has a duration. Never throws. */
19
+ export declare function verifyMediaFile(ffmpegPath: string, file: string): Promise<MediaVerdict>;
@@ -0,0 +1,79 @@
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.HLS_COMPLETE_SHARE = void 0;
37
+ exports.hlsStoppedEarly = hlsStoppedEarly;
38
+ exports.parseMediaProbe = parseMediaProbe;
39
+ exports.verifyMediaFile = verifyMediaFile;
40
+ const child_process_1 = require("child_process");
41
+ const fs = __importStar(require("fs/promises"));
42
+ /** An ffmpeg that exits 0 before this share of the stream length was written did not finish. */
43
+ exports.HLS_COMPLETE_SHARE = 0.97;
44
+ /** True when ffmpeg stopped (even with code 0) well short of the length it announced. Unknown length: false. */
45
+ function hlsStoppedEarly(totalDurationSec, currentTimeSec) {
46
+ return totalDurationSec > 0 && currentTimeSec < exports.HLS_COMPLETE_SHARE * totalDurationSec;
47
+ }
48
+ /** Reads what `ffmpeg -i <file>` prints to stderr: a Video stream and the Duration line. */
49
+ function parseMediaProbe(stderr) {
50
+ const dm = stderr.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/);
51
+ const durationSec = dm ? parseInt(dm[1], 10) * 3600 + parseInt(dm[2], 10) * 60 + parseFloat(dm[3]) : 0;
52
+ return { hasVideo: /Stream #\S+.*:\s*Video:/.test(stderr), durationSec };
53
+ }
54
+ function probeStderr(ffmpegPath, file) {
55
+ // `ffmpeg -i <file>` with no output prints the probe and exits non-zero: only stderr matters.
56
+ return new Promise((resolve) => {
57
+ (0, child_process_1.execFile)(ffmpegPath, ['-hide_banner', '-i', file], { maxBuffer: 4 * 1024 * 1024, timeout: 30_000 }, (_err, _out, stderr) => {
58
+ resolve(String(stderr ?? ''));
59
+ });
60
+ });
61
+ }
62
+ /** Is `file` a playable video: non-empty, has a video stream, has a duration. Never throws. */
63
+ async function verifyMediaFile(ffmpegPath, file) {
64
+ let size;
65
+ try {
66
+ size = (await fs.stat(file)).size;
67
+ }
68
+ catch (err) {
69
+ return { ok: false, reason: `file not readable: ${err instanceof Error ? err.message : String(err)}` };
70
+ }
71
+ if (size === 0)
72
+ return { ok: false, reason: 'file is 0 bytes' };
73
+ const probe = parseMediaProbe(await probeStderr(ffmpegPath, file));
74
+ if (!probe.hasVideo)
75
+ return { ok: false, reason: 'no video stream (unreadable or truncated container)' };
76
+ if (probe.durationSec <= 0)
77
+ return { ok: false, reason: 'duration is 0 or unknown' };
78
+ return { ok: true, durationSec: probe.durationSec };
79
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dominevo/series-scraper-core",
3
- "version": "0.0.93",
3
+ "version": "0.0.94",
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",