Compare commits
300 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44f202d116 | ||
|
|
008f16a05d | ||
|
|
927013d9a6 | ||
|
|
9f62c7c29c | ||
|
|
6897776460 | ||
|
|
3089a45b13 | ||
|
|
e37545c9c9 | ||
|
|
17e7862307 | ||
|
|
d1eadff425 | ||
|
|
650988c7ac | ||
|
|
49e62c1f83 | ||
|
|
4c67455c67 | ||
|
|
5a5e3d2960 | ||
|
|
11da8b6e9a | ||
|
|
265e6a72be | ||
|
|
7816dc9488 | ||
|
|
678d642683 | ||
|
|
0f4174d153 | ||
|
|
babcd8edb7 | ||
|
|
6e00bbab53 | ||
|
|
72642351d0 | ||
|
|
51a01ea03f | ||
|
|
d9a78ea837 | ||
|
|
5b221d5bd5 | ||
|
|
c36549ca69 | ||
|
|
7e79bef8da | ||
|
|
e3b4a4ba19 | ||
|
|
30d216c7ca | ||
|
|
d80483adc2 | ||
|
|
1cda391dfe | ||
|
|
375ec36781 | ||
|
|
4ad1c05444 | ||
|
|
c88eeb0b12 | ||
|
|
c6261aba6a | ||
|
|
a010b967b9 | ||
|
|
af6547f254 | ||
|
|
ba235b0b93 | ||
|
|
1bfde96e46 | ||
|
|
e1f9b4b6d3 | ||
|
|
95cf4fbed8 | ||
|
|
9ddc7d31bb | ||
|
|
83626017b9 | ||
|
|
b9372f0ef0 | ||
|
|
db97a7df14 | ||
|
|
575fca3806 | ||
|
|
a1c8f42435 | ||
|
|
a3c2680fec | ||
|
|
12dade0240 | ||
|
|
2a528a126c | ||
|
|
8839080069 | ||
|
|
8f66d75eb3 | ||
|
|
56ee681aec | ||
|
|
6db03f05a9 | ||
|
|
068da94e2a | ||
|
|
4b824b2d9f | ||
|
|
284c5e7aa6 | ||
|
|
036cd3e066 | ||
|
|
479c7a3f3f | ||
|
|
0404d870ad | ||
|
|
93a53763e0 | ||
|
|
c20d743286 | ||
|
|
ba938f64c5 | ||
|
|
af00d69e5c | ||
|
|
bc47da504c | ||
|
|
5a24c891c0 | ||
|
|
1103df98c1 | ||
|
|
74920e2e2f | ||
|
|
75775f2798 | ||
|
|
fad0f1060b | ||
|
|
0ca359e509 | ||
|
|
1d0ee31001 | ||
|
|
20a0a59670 | ||
|
|
9a00304a93 | ||
|
|
55b00bf884 | ||
|
|
e85f12977f | ||
|
|
940346e2f4 | ||
|
|
1854e6bb17 | ||
|
|
26b2ef0abb | ||
|
|
9cceaacd14 | ||
|
|
1ed13f7f88 | ||
|
|
729aa30253 | ||
|
|
b8bbc9c32f | ||
|
|
a263e3eb2c | ||
|
|
10bae4f98b | ||
|
|
b02aef2af9 | ||
|
|
56c0b633c8 | ||
|
|
4e8e8eba66 | ||
|
|
d5638b922d | ||
|
|
dc695c9a04 | ||
|
|
52909258ca | ||
|
|
e9b9801ac1 | ||
|
|
86a358d568 | ||
|
|
97c5bfaa7d | ||
|
|
8d0c110415 | ||
|
|
a131f4a11b | ||
|
|
335873a7f6 | ||
|
|
7446e07a8c | ||
|
|
693f7b482a | ||
|
|
1d4a13466f | ||
|
|
17844d4c28 | ||
|
|
55d0e3141c | ||
|
|
a967eb1080 | ||
|
|
21ff749cf3 | ||
|
|
18862bb8e0 | ||
|
|
27833615b7 | ||
|
|
00fae5cadd | ||
|
|
4fcbd5c4f7 | ||
|
|
bb8fd0646a | ||
|
|
1218adf5f2 | ||
|
|
818bf40a9c | ||
|
|
254612a49b | ||
|
|
92101e249a | ||
|
|
a18ab484cc | ||
|
|
7af9d67770 | ||
|
|
d63afcce89 | ||
|
|
15d0969cd9 | ||
|
|
5574b50d20 | ||
|
|
662c903bf3 | ||
|
|
545043e1d6 | ||
|
|
8f10ff8f96 | ||
|
|
62f3bd94de | ||
|
|
253b1868ec | ||
|
|
c4aefb6175 | ||
|
|
956cad0da4 | ||
|
|
83d8df84bf | ||
|
|
0c058fa162 | ||
|
|
21dbf46f81 | ||
|
|
af6eea8253 | ||
|
|
7029271999 | ||
|
|
5dabee332e | ||
|
|
d9fe98231f | ||
|
|
6ee98328fb | ||
|
|
3dbb94d298 | ||
|
|
1956be0c71 | ||
|
|
e9414853f9 | ||
|
|
d67cce501b | ||
|
|
d87b74d359 | ||
|
|
be7a8fd103 | ||
|
|
d23740eac7 | ||
|
|
56a507b45d | ||
|
|
31ce1e6618 | ||
|
|
b637fb3db8 | ||
|
|
1d876f8ded | ||
|
|
2f43164732 | ||
|
|
9747cabb14 | ||
|
|
9b460758f9 | ||
|
|
8cc1f788ad | ||
|
|
0888e16aec | ||
|
|
cab550a13c | ||
|
|
2ef3983049 | ||
|
|
ca4392fa8b | ||
|
|
8fad61e329 | ||
|
|
02bd4a61fb | ||
|
|
30ac5bf9db | ||
|
|
87e0a986e6 | ||
|
|
353cef7dbd | ||
|
|
f9b0bbe676 | ||
|
|
93d54c8f84 | ||
|
|
26bf675a41 | ||
|
|
35e84e652e | ||
|
|
462fc0397e | ||
|
|
d4bf574370 | ||
|
|
d3ec000da5 | ||
|
|
d7d256f716 | ||
|
|
804fbe2bdc | ||
|
|
1fde0a9951 | ||
|
|
0cf5ebe5e9 | ||
|
|
0b7c658c8f | ||
|
|
e6ec1ed755 | ||
|
|
ac479bb023 | ||
|
|
9ac557b0a8 | ||
|
|
4585db0281 | ||
|
|
0d86356f96 | ||
|
|
140ee488b7 | ||
|
|
486379183b | ||
|
|
19a588a997 | ||
|
|
fa30e738d9 | ||
|
|
eefb536cb3 | ||
|
|
02b136dac7 | ||
|
|
b712282f62 | ||
|
|
de369f3bcd | ||
|
|
3ee3af03cf | ||
|
|
9a646d516b | ||
|
|
311fb00430 | ||
|
|
4008e20278 | ||
|
|
375b9885ee | ||
|
|
ce01512537 | ||
|
|
7dc12aca0c | ||
|
|
a6c65acfcb | ||
|
|
19342647e5 | ||
|
|
7fe7d93e83 | ||
|
|
19769ea0bb | ||
|
|
c9bace1e5a | ||
|
|
2d1b6de51a | ||
|
|
c07c0fbdf7 | ||
|
|
578d050926 | ||
|
|
cb66661d9b | ||
|
|
e35fc1f31a | ||
|
|
0d6053fa76 | ||
|
|
546d6af598 | ||
|
|
2b12bd8c42 | ||
|
|
05dc0ca1c6 | ||
|
|
5023a99f91 | ||
|
|
b2b62aeb52 | ||
|
|
ba7fe24a0a | ||
|
|
55e5b0079a | ||
|
|
e90e731eaa | ||
|
|
0b73ea1386 | ||
|
|
e013c63c59 | ||
|
|
2ae22f942e | ||
|
|
a22a90adf3 | ||
|
|
ecf56cb977 | ||
|
|
430ec7352b | ||
|
|
bc70ff94cc | ||
|
|
549328893e | ||
|
|
e6c17393fb | ||
|
|
ba673b9e53 | ||
|
|
3c510fc265 | ||
|
|
4ea3a75dc0 | ||
|
|
670c2f1ff5 | ||
|
|
0d1deadb6f | ||
|
|
f11190ee25 | ||
|
|
eb42fbabfd | ||
|
|
84d5c0f13f | ||
|
|
09bc354c18 | ||
|
|
3ed31b7994 | ||
|
|
550942aad7 | ||
|
|
a9c8ee2ff4 | ||
|
|
10b4f18d33 | ||
|
|
45b0d71dd0 | ||
|
|
e0eb3f0453 | ||
|
|
daf70211ac | ||
|
|
c28384e78d | ||
|
|
122c797652 | ||
|
|
14d5a3abb4 | ||
|
|
ca05fa184d | ||
|
|
13ff41aa95 | ||
|
|
d8a53dcea6 | ||
|
|
9f589439a1 | ||
|
|
5bb984d410 | ||
|
|
1825e8ba04 | ||
|
|
0e55c28142 | ||
|
|
e485cf734b | ||
|
|
520ef91d2d | ||
|
|
674cf101da | ||
|
|
4371e53b86 | ||
|
|
bf2b685e83 | ||
|
|
e7f0b1d1fd | ||
|
|
647679f581 | ||
|
|
237bf6731d | ||
|
|
25af89d7a0 | ||
|
|
e384199c6e | ||
|
|
98425764d3 | ||
|
|
8f186ad894 | ||
|
|
8b153bdabe | ||
|
|
401ad3b9f9 | ||
|
|
5e1e62d5b6 | ||
|
|
afc70e6a10 | ||
|
|
20c32d39c8 | ||
|
|
73cd2ea6b9 | ||
|
|
c5c862b516 | ||
|
|
a0cdac87e8 | ||
|
|
f5d7ee4d1a | ||
|
|
43950014b2 | ||
|
|
ec45983810 | ||
|
|
7795208332 | ||
|
|
b0dc7b80ab | ||
|
|
ab9b3e87b1 | ||
|
|
116135289c | ||
|
|
2bddd5b3b2 | ||
|
|
5f2eb907b6 | ||
|
|
3f17cc8cb4 | ||
|
|
33e2e126f1 | ||
|
|
467d4bbc58 | ||
|
|
e1e7f63f50 | ||
|
|
18fdbcba18 | ||
|
|
4bcb069ec7 | ||
|
|
bfbaee8e5c | ||
|
|
282c1ebf1d | ||
|
|
6e50841387 | ||
|
|
508977e70b | ||
|
|
cb1e4bb0c1 | ||
|
|
809aec69c2 | ||
|
|
71aa9204f4 | ||
|
|
65cf4c217f | ||
|
|
2d3a1df21d | ||
|
|
43bc95b7fc | ||
|
|
fe59e064f0 | ||
|
|
67fc7a9226 | ||
|
|
474ff8cd26 | ||
|
|
310f4dc58a | ||
|
|
d491c21b97 | ||
|
|
a0c58aad2c | ||
|
|
48c89713ba | ||
|
|
778124312c | ||
|
|
edbfba6663 | ||
|
|
ff1036563a | ||
|
|
6ac56c0a77 | ||
|
|
6ae687f3ab | ||
|
|
eda9754d30 |
52
.github/workflows/release.yml
vendored
52
.github/workflows/release.yml
vendored
@ -1,52 +0,0 @@
|
|||||||
name: Build and Release
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: windows-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Node
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: "22"
|
|
||||||
cache: "npm"
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Apply tag version
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
$version = "${{ github.ref_name }}".TrimStart('v')
|
|
||||||
node scripts/set_version_node.mjs $version
|
|
||||||
|
|
||||||
- name: Build app
|
|
||||||
run: npm run build
|
|
||||||
|
|
||||||
- name: Build Windows artifacts
|
|
||||||
run: npm run release:win
|
|
||||||
|
|
||||||
- name: Pack portable zip
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
Compress-Archive -Path "release\win-unpacked\*" -DestinationPath "Real-Debrid-Downloader-win64.zip" -Force
|
|
||||||
|
|
||||||
- name: Publish GitHub Release
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
files: |
|
|
||||||
Real-Debrid-Downloader-win64.zip
|
|
||||||
release/*.exe
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
14
.gitignore
vendored
14
.gitignore
vendored
@ -17,9 +17,23 @@ rd_download_manifest.json
|
|||||||
_update_staging/
|
_update_staging/
|
||||||
apply_update.cmd
|
apply_update.cmd
|
||||||
|
|
||||||
|
.claude/
|
||||||
|
.github/
|
||||||
|
docs/plans/
|
||||||
|
CHANGELOG.md
|
||||||
|
|
||||||
node_modules/
|
node_modules/
|
||||||
.vite/
|
.vite/
|
||||||
coverage/
|
coverage/
|
||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
yarn-debug.log*
|
yarn-debug.log*
|
||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
|
|
||||||
|
# Forgejo deployment runtime files
|
||||||
|
deploy/forgejo/.env
|
||||||
|
deploy/forgejo/forgejo/
|
||||||
|
deploy/forgejo/postgres/
|
||||||
|
deploy/forgejo/caddy/data/
|
||||||
|
deploy/forgejo/caddy/config/
|
||||||
|
deploy/forgejo/caddy/logs/
|
||||||
|
deploy/forgejo/backups/
|
||||||
|
|||||||
23
CLAUDE.md
Normal file
23
CLAUDE.md
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
## Release + Update Source (Wichtig)
|
||||||
|
|
||||||
|
- Primäre Plattform ist `https://git.24-music.de`
|
||||||
|
- Standard-Repo: `Administrator/real-debrid-downloader`
|
||||||
|
- Nicht mehr primär über Codeberg/GitHub releasen
|
||||||
|
|
||||||
|
## Releasen
|
||||||
|
|
||||||
|
1. Token setzen:
|
||||||
|
- PowerShell: `$env:GITEA_TOKEN="<token>"`
|
||||||
|
2. Release ausführen:
|
||||||
|
- `npm run release:gitea -- <version> [notes]`
|
||||||
|
|
||||||
|
Das Script:
|
||||||
|
- bumped `package.json`
|
||||||
|
- baut Windows-Artefakte
|
||||||
|
- pusht `main` + Tag
|
||||||
|
- erstellt Release auf `git.24-music.de`
|
||||||
|
- lädt Assets hoch
|
||||||
|
|
||||||
|
## Auto-Update
|
||||||
|
|
||||||
|
- Updater nutzt aktuell `git.24-music.de` als Standardquelle
|
||||||
224
README.md
224
README.md
@ -1,83 +1,203 @@
|
|||||||
# Real-Debrid Download Manager (Node/Electron)
|
# Multi Debrid Downloader
|
||||||
|
|
||||||
Desktop-App auf **Node.js + Electron + React + TypeScript** mit JDownloader-Style Workflow, optimiert fuer Real-Debrid.
|
Desktop downloader with fast queue management, automatic extraction, and robust error handling.
|
||||||
|
|
||||||
## Highlights
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
- Modernes, dunkles UI mit Header-Steuerung (Start, Pause, Stop, Speed, ETA)
|
## Why this tool?
|
||||||
- Tabs: **Linksammler**, **Downloads**, **Settings**
|
|
||||||
- Paketbasierte Queue mit Datei-Status, Progress, Speed, Retries
|
|
||||||
- Paket-Abbruch waehrend laufender Downloads inklusive sicherem Archiv-Cleanup
|
|
||||||
- `.dlc` Import (Dateidialog und Drag-and-Drop)
|
|
||||||
- Session-Persistenz (robustes JSON-State-Management)
|
|
||||||
- Auto-Resume beim Start (optional)
|
|
||||||
- Reconnect-Basislogik (429/503, Wartefenster, resumable priorisiert)
|
|
||||||
- Integritaetscheck (SFV/CRC32/MD5/SHA1) nach Download
|
|
||||||
- Auto-Retry bei Integritaetsfehlern
|
|
||||||
- Cleanup-Trigger fuer fertige Tasks:
|
|
||||||
- Nie
|
|
||||||
- Sofort
|
|
||||||
- Beim App-Start
|
|
||||||
- Sobald Paket fertig ist
|
|
||||||
|
|
||||||
## Voraussetzungen
|
- Familiar download-manager workflow: collect links, start, pause, resume, and finish cleanly.
|
||||||
|
- Multiple debrid providers in one app, including automatic fallback.
|
||||||
|
- Built for stability with large queues: session persistence, reconnect handling, resume support, and integrity verification.
|
||||||
|
|
||||||
- Node.js 20+ (empfohlen 22+)
|
## Core features
|
||||||
- Windows 10/11 (fuer Release-Build)
|
|
||||||
- Optional: 7-Zip/UnRAR fuer RAR/7Z Entpacken
|
### Queue and download engine
|
||||||
|
|
||||||
|
- Package-based queue with file status, progress, ETA, speed, and retry counters.
|
||||||
|
- Start, pause, stop, and cancel for both single items and full packages.
|
||||||
|
- Multi-select via Ctrl+Click for batch operations on packages and items.
|
||||||
|
- Duplicate handling when adding links: keep, skip, or overwrite.
|
||||||
|
- Session recovery after restart, including optional auto-resume.
|
||||||
|
- Circuit breaker with escalating backoff cooldowns to handle provider outages gracefully.
|
||||||
|
|
||||||
|
### Debrid and link handling
|
||||||
|
|
||||||
|
- Supported providers: `realdebrid`, `megadebrid`, `bestdebrid`, `alldebrid`.
|
||||||
|
- Configurable provider order: primary + secondary + tertiary.
|
||||||
|
- Optional automatic fallback to alternative providers on failures.
|
||||||
|
- `.dlc` import via file picker and drag-and-drop.
|
||||||
|
|
||||||
|
### Extraction, cleanup, and quality
|
||||||
|
|
||||||
|
- JVM-based extraction backend using SevenZipJBinding + Zip4j (supports RAR, 7z, ZIP, and more).
|
||||||
|
- Automatic fallback to legacy UnRAR/7z CLI tools when JVM is unavailable.
|
||||||
|
- Auto-extract with separate target directory and conflict strategies.
|
||||||
|
- Hybrid extraction: simultaneous downloading and extracting with smart I/O priority throttling.
|
||||||
|
- Nested extraction: archives within archives are automatically extracted (one level deep).
|
||||||
|
- Pre-extraction disk space validation to prevent incomplete extracts.
|
||||||
|
- Right-click "Extract now" on any package with at least one completed item.
|
||||||
|
- Post-download integrity checks (`CRC32`, `MD5`, `SHA1`) with auto-retry on failures.
|
||||||
|
- Completed-item cleanup policy: `never`, `immediate`, `on_start`, `package_done`.
|
||||||
|
- Optional removal of link artifacts and sample files after extraction.
|
||||||
|
|
||||||
|
### Auto-rename
|
||||||
|
|
||||||
|
- Automatic renaming of extracted files based on series/episode patterns.
|
||||||
|
- Multi-episode token parsing for batch renames.
|
||||||
|
|
||||||
|
### UI and progress
|
||||||
|
|
||||||
|
- Visual progress bars with percentage overlay for packages and individual items.
|
||||||
|
- Real-time bandwidth chart showing current download speeds.
|
||||||
|
- Persistent download counters: all-time totals and per-session statistics.
|
||||||
|
- Download history for completed packages.
|
||||||
|
- Vertical sidebar with organized settings tabs.
|
||||||
|
- Hoster display showing both the original source and the debrid provider used.
|
||||||
|
|
||||||
|
### Convenience and automation
|
||||||
|
|
||||||
|
- Clipboard watcher for automatic link detection.
|
||||||
|
- Minimize-to-tray with tray menu controls.
|
||||||
|
- Speed limits globally or per download.
|
||||||
|
- Bandwidth schedules for time-based speed profiles.
|
||||||
|
- Built-in auto-updater via `git.24-music.de` Releases.
|
||||||
|
- Long path support (>260 characters) on Windows.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
### Option A: prebuilt releases (recommended)
|
||||||
|
|
||||||
|
1. Download a release from the `git.24-music.de` Releases page.
|
||||||
|
2. Run the installer or portable build.
|
||||||
|
3. Add your debrid tokens in Settings.
|
||||||
|
|
||||||
|
Releases: `https://git.24-music.de/Administrator/real-debrid-downloader/releases`
|
||||||
|
|
||||||
|
### Option B: build from source
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
|
||||||
|
- Node.js `20+` (recommended `22+`)
|
||||||
|
- npm
|
||||||
|
- Windows `10/11` (for packaging and regular desktop use)
|
||||||
|
- Java Runtime `8+` (for SevenZipJBinding sidecar backend)
|
||||||
|
- Optional fallback: 7-Zip/UnRAR if you force legacy extraction mode
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
```
|
|
||||||
|
|
||||||
## Entwicklung
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run dev
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
## Build
|
## NPM scripts
|
||||||
|
|
||||||
|
| Command | Description |
|
||||||
|
| --- | --- |
|
||||||
|
| `npm run dev` | Starts main process, renderer, and Electron in dev mode |
|
||||||
|
| `npm run build` | Builds main and renderer bundles |
|
||||||
|
| `npm run start` | Starts the app locally in production mode |
|
||||||
|
| `npm test` | Runs Vitest unit tests |
|
||||||
|
| `npm run self-check` | Runs integrated end-to-end self-checks |
|
||||||
|
| `npm run release:win` | Creates Windows installer and portable build |
|
||||||
|
| `npm run release:gitea -- <version> [notes]` | One-command version bump + build + tag + release upload to `git.24-music.de` |
|
||||||
|
| `npm run release:codeberg -- <version> [notes]` | Legacy path for old Codeberg workflow |
|
||||||
|
|
||||||
|
### One-command git.24-music release
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run build
|
npm run release:gitea -- 1.6.31 "- Maintenance update"
|
||||||
```
|
```
|
||||||
|
|
||||||
Danach liegen die Artefakte in:
|
This command will:
|
||||||
|
|
||||||
- `build/main`
|
1. Bump `package.json` version.
|
||||||
- `build/renderer`
|
2. Build setup/portable artifacts (`npm run release:win`).
|
||||||
|
3. Commit and push `main` to your `git.24-music.de` remote.
|
||||||
|
4. Create and push tag `v<version>`.
|
||||||
|
5. Create/update the Gitea release and upload required assets.
|
||||||
|
|
||||||
## Start (Production lokal)
|
Required once before release:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run start
|
git remote add gitea https://git.24-music.de/<user>/<repo>.git
|
||||||
```
|
```
|
||||||
|
|
||||||
## Tests
|
PowerShell token setup:
|
||||||
|
|
||||||
```bash
|
```powershell
|
||||||
npm test
|
$env:GITEA_TOKEN="<dein-token>"
|
||||||
npm run self-check
|
|
||||||
```
|
```
|
||||||
|
|
||||||
- `npm test`: Unit-Tests fuer Parser/Cleanup/Integrity
|
## Typical workflow
|
||||||
- `npm run self-check`: End-to-End-Checks mit lokalem Mock-Server (Queue, Pause/Resume, Reconnect, Paket-Cancel)
|
|
||||||
|
|
||||||
## Projektstruktur
|
1. Add provider tokens in Settings.
|
||||||
|
2. Paste/import links or `.dlc` containers.
|
||||||
|
3. Optionally set package names, target folders, extraction, and cleanup rules.
|
||||||
|
4. Start the queue and monitor progress in the Downloads tab.
|
||||||
|
5. Review integrity results and summary after completion.
|
||||||
|
|
||||||
- `src/main`: Electron Main Process + Download/Queue Logik
|
## Project structure
|
||||||
- `src/preload`: sichere IPC Bridge
|
|
||||||
- `src/renderer`: React UI
|
|
||||||
- `src/shared`: gemeinsame Typen und IPC-Channel
|
|
||||||
- `tests`: Unit- und Self-Check Tests
|
|
||||||
|
|
||||||
## Hinweise
|
- `src/main` - Electron main process, queue/download/provider logic
|
||||||
|
- `src/preload` - secure IPC bridge between main and renderer
|
||||||
|
- `src/renderer` - React UI
|
||||||
|
- `src/shared` - shared types and IPC contracts
|
||||||
|
- `tests` - unit tests and self-check tests
|
||||||
|
- `resources/extractor-jvm` - SevenZipJBinding + Zip4j sidecar JAR and native libraries
|
||||||
|
|
||||||
- Runtime-Dateien liegen im Electron `userData` Verzeichnis:
|
## Data and logs
|
||||||
- `rd_downloader_config.json`
|
|
||||||
- `rd_session_state.json`
|
|
||||||
- `rd_downloader.log`
|
|
||||||
|
|
||||||
- Das Repository enthält jetzt nur noch die aktive Node/Electron-Codebasis.
|
The app stores runtime files in Electron's `userData` directory, including:
|
||||||
|
|
||||||
|
- `rd_downloader_config.json`
|
||||||
|
- `rd_session_state.json`
|
||||||
|
- `rd_downloader.log`
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
- Download does not start: verify token and selected provider in Settings.
|
||||||
|
- Extraction fails: check archive passwords and native extractor installation (7-Zip/WinRAR). Optional JVM extractor can be forced with `RD_EXTRACT_BACKEND=jvm`.
|
||||||
|
- Very slow downloads: check active speed limit and bandwidth schedules.
|
||||||
|
- Unexpected interruptions: enable reconnect and fallback providers.
|
||||||
|
- Stalled downloads: the app auto-detects stalls within 10 seconds and retries automatically.
|
||||||
|
|
||||||
|
## Changelog
|
||||||
|
|
||||||
|
Release history is available on [git.24-music.de Releases](https://git.24-music.de/Administrator/real-debrid-downloader/releases).
|
||||||
|
|
||||||
|
### v1.6.61 (2026-03-05)
|
||||||
|
|
||||||
|
- Fixed leftover empty package folders in `Downloader Unfertig` after successful extraction.
|
||||||
|
- Resume marker files (`.rd_extract_progress*.json`) are now treated as ignorable for empty-folder cleanup.
|
||||||
|
- Deferred post-processing now clears resume markers before running empty-directory removal.
|
||||||
|
|
||||||
|
### v1.6.60 (2026-03-05)
|
||||||
|
|
||||||
|
- Added package-scoped password cache for extraction: once the first archive in a package is solved, following archives in the same package reuse that password first.
|
||||||
|
- Kept fallback behavior intact (`""` and other candidates are still tested), but moved empty-password probing behind the learned password to reduce per-archive delays.
|
||||||
|
- Added cache invalidation on real `wrong_password` failures so stale passwords are automatically discarded.
|
||||||
|
|
||||||
|
### v1.6.59 (2026-03-05)
|
||||||
|
|
||||||
|
- Switched default extraction backend to native tools (`legacy`) for more stable archive-to-archive flow.
|
||||||
|
- Prioritized 7-Zip as primary native extractor, with WinRAR/UnRAR as fallback.
|
||||||
|
- JVM extractor remains available as opt-in via `RD_EXTRACT_BACKEND=jvm`.
|
||||||
|
|
||||||
|
### v1.6.58 (2026-03-05)
|
||||||
|
|
||||||
|
- Fixed extraction progress oscillation (`1% -> 100% -> 1%` loops) during password retries.
|
||||||
|
- Kept strict archive completion logic, but normalized in-progress archive percent to avoid false visual done states before real completion.
|
||||||
|
|
||||||
|
### v1.6.57 (2026-03-05)
|
||||||
|
|
||||||
|
- Fixed extraction flow so archives are marked done only on real completion, not on temporary `100%` progress spikes.
|
||||||
|
- Improved password handling: after the first successful archive, the discovered password is prioritized for subsequent archives.
|
||||||
|
- Fixed progress parsing for password retries (reset/restart handling), reducing visible and real gaps between archive extractions.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT - see `LICENSE`.
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 121 KiB After Width: | Height: | Size: 279 KiB |
@ -25,11 +25,11 @@ AppPublisher=Sucukdeluxe
|
|||||||
DefaultDirName={autopf}\{#MyAppName}
|
DefaultDirName={autopf}\{#MyAppName}
|
||||||
DefaultGroupName={#MyAppName}
|
DefaultGroupName={#MyAppName}
|
||||||
OutputDir={#MyOutputDir}
|
OutputDir={#MyOutputDir}
|
||||||
OutputBaseFilename=Real-Debrid-Downloader-Setup-{#MyAppVersion}
|
OutputBaseFilename=Real-Debrid-Downloader Setup {#MyAppVersion}
|
||||||
Compression=lzma
|
Compression=lzma
|
||||||
SolidCompression=yes
|
SolidCompression=yes
|
||||||
WizardStyle=modern
|
WizardStyle=modern
|
||||||
PrivilegesRequired=admin
|
PrivilegesRequired=lowest
|
||||||
ArchitecturesInstallIn64BitMode=x64compatible
|
ArchitecturesInstallIn64BitMode=x64compatible
|
||||||
UninstallDisplayIcon={app}\{#MyAppExeName}
|
UninstallDisplayIcon={app}\{#MyAppExeName}
|
||||||
SetupIconFile={#MyIconFile}
|
SetupIconFile={#MyIconFile}
|
||||||
@ -39,8 +39,8 @@ Name: "german"; MessagesFile: "compiler:Languages\German.isl"
|
|||||||
Name: "english"; MessagesFile: "compiler:Default.isl"
|
Name: "english"; MessagesFile: "compiler:Default.isl"
|
||||||
|
|
||||||
[Files]
|
[Files]
|
||||||
Source: "{#MySourceDir}\\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
|
Source: "{#MySourceDir}\\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs
|
||||||
Source: "{#MyIconFile}"; DestDir: "{app}"; DestName: "app_icon.ico"; Flags: ignoreversion
|
Source: "{#MyIconFile}"; DestDir: "{app}"; DestName: "app_icon.ico"
|
||||||
|
|
||||||
[Icons]
|
[Icons]
|
||||||
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; IconFilename: "{app}\app_icon.ico"
|
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; IconFilename: "{app}\app_icon.ico"
|
||||||
|
|||||||
161
package-lock.json
generated
161
package-lock.json
generated
@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "real-debrid-downloader",
|
"name": "real-debrid-downloader",
|
||||||
"version": "1.4.28",
|
"version": "1.5.66",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "real-debrid-downloader",
|
"name": "real-debrid-downloader",
|
||||||
"version": "1.4.28",
|
"version": "1.5.66",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"adm-zip": "^0.5.16",
|
"adm-zip": "^0.5.16",
|
||||||
@ -25,6 +25,7 @@
|
|||||||
"cross-env": "^7.0.3",
|
"cross-env": "^7.0.3",
|
||||||
"electron": "^31.7.7",
|
"electron": "^31.7.7",
|
||||||
"electron-builder": "^25.1.8",
|
"electron-builder": "^25.1.8",
|
||||||
|
"rcedit": "^5.0.2",
|
||||||
"tsup": "^8.3.6",
|
"tsup": "^8.3.6",
|
||||||
"tsx": "^4.19.2",
|
"tsx": "^4.19.2",
|
||||||
"typescript": "^5.7.3",
|
"typescript": "^5.7.3",
|
||||||
@ -64,7 +65,6 @@
|
|||||||
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
|
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/code-frame": "^7.29.0",
|
"@babel/code-frame": "^7.29.0",
|
||||||
"@babel/generator": "^7.29.0",
|
"@babel/generator": "^7.29.0",
|
||||||
@ -2043,7 +2043,6 @@
|
|||||||
"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",
|
"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@types/prop-types": "*",
|
"@types/prop-types": "*",
|
||||||
"csstype": "^3.2.2"
|
"csstype": "^3.2.2"
|
||||||
@ -2305,7 +2304,6 @@
|
|||||||
"integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
|
"integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"fast-deep-equal": "^3.1.1",
|
"fast-deep-equal": "^3.1.1",
|
||||||
"fast-json-stable-stringify": "^2.0.0",
|
"fast-json-stable-stringify": "^2.0.0",
|
||||||
@ -2479,6 +2477,7 @@
|
|||||||
"integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==",
|
"integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"archiver-utils": "^2.1.0",
|
"archiver-utils": "^2.1.0",
|
||||||
"async": "^3.2.4",
|
"async": "^3.2.4",
|
||||||
@ -2498,6 +2497,7 @@
|
|||||||
"integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==",
|
"integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"glob": "^7.1.4",
|
"glob": "^7.1.4",
|
||||||
"graceful-fs": "^4.2.0",
|
"graceful-fs": "^4.2.0",
|
||||||
@ -2520,6 +2520,7 @@
|
|||||||
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
|
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"core-util-is": "~1.0.0",
|
"core-util-is": "~1.0.0",
|
||||||
"inherits": "~2.0.3",
|
"inherits": "~2.0.3",
|
||||||
@ -2535,7 +2536,8 @@
|
|||||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||||
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/archiver-utils/node_modules/string_decoder": {
|
"node_modules/archiver-utils/node_modules/string_decoder": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
@ -2543,6 +2545,7 @@
|
|||||||
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
|
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"safe-buffer": "~5.1.0"
|
"safe-buffer": "~5.1.0"
|
||||||
}
|
}
|
||||||
@ -2762,7 +2765,6 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"baseline-browser-mapping": "^2.9.0",
|
"baseline-browser-mapping": "^2.9.0",
|
||||||
"caniuse-lite": "^1.0.30001759",
|
"caniuse-lite": "^1.0.30001759",
|
||||||
@ -3344,6 +3346,7 @@
|
|||||||
"integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==",
|
"integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"buffer-crc32": "^0.2.13",
|
"buffer-crc32": "^0.2.13",
|
||||||
"crc32-stream": "^4.0.2",
|
"crc32-stream": "^4.0.2",
|
||||||
@ -3517,6 +3520,7 @@
|
|||||||
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
|
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
|
"peer": true,
|
||||||
"bin": {
|
"bin": {
|
||||||
"crc32": "bin/crc32.njs"
|
"crc32": "bin/crc32.njs"
|
||||||
},
|
},
|
||||||
@ -3530,6 +3534,7 @@
|
|||||||
"integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==",
|
"integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"crc-32": "^1.2.0",
|
"crc-32": "^1.2.0",
|
||||||
"readable-stream": "^3.4.0"
|
"readable-stream": "^3.4.0"
|
||||||
@ -3572,6 +3577,54 @@
|
|||||||
"node": ">= 8"
|
"node": ">= 8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/cross-spawn-windows-exe": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/cross-spawn-windows-exe/-/cross-spawn-windows-exe-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-mkLtJJcYbDCxEG7Js6eUnUNndWjyUZwJ3H7bErmmtOYU/Zb99DyUkpamuIZE0b3bhmJyZ7D90uS6f+CGxRRjOw==",
|
||||||
|
"dev": true,
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "individual",
|
||||||
|
"url": "https://github.com/sponsors/malept"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "tidelift",
|
||||||
|
"url": "https://tidelift.com/subscription/pkg/npm-cross-spawn-windows-exe?utm_medium=referral&utm_source=npm_fund"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@malept/cross-spawn-promise": "^1.1.0",
|
||||||
|
"is-wsl": "^2.2.0",
|
||||||
|
"which": "^2.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/cross-spawn-windows-exe/node_modules/@malept/cross-spawn-promise": {
|
||||||
|
"version": "1.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-1.1.1.tgz",
|
||||||
|
"integrity": "sha512-RTBGWL5FWQcg9orDOCcp4LvItNzUPcyEU9bwaeJX0rJ1IQxzucC48Y0/sQLp/g6t99IQgAlGIaesJS+gTn7tVQ==",
|
||||||
|
"dev": true,
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "individual",
|
||||||
|
"url": "https://github.com/sponsors/malept"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "tidelift",
|
||||||
|
"url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"cross-spawn": "^7.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/csstype": {
|
"node_modules/csstype": {
|
||||||
"version": "3.2.3",
|
"version": "3.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||||
@ -3780,7 +3833,6 @@
|
|||||||
"integrity": "sha512-NoXo6Liy2heSklTI5OIZbCgXC1RzrDQsZkeEwXhdOro3FT1VBOvbubvscdPnjVuQ4AMwwv61oaH96AbiYg9EnQ==",
|
"integrity": "sha512-NoXo6Liy2heSklTI5OIZbCgXC1RzrDQsZkeEwXhdOro3FT1VBOvbubvscdPnjVuQ4AMwwv61oaH96AbiYg9EnQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"app-builder-lib": "25.1.8",
|
"app-builder-lib": "25.1.8",
|
||||||
"builder-util": "25.1.7",
|
"builder-util": "25.1.7",
|
||||||
@ -3976,6 +4028,7 @@
|
|||||||
"integrity": "sha512-2ntkJ+9+0GFP6nAISiMabKt6eqBB0kX1QqHNWFWAXgi0VULKGisM46luRFpIBiU3u/TDmhZMM8tzvo2Abn3ayg==",
|
"integrity": "sha512-2ntkJ+9+0GFP6nAISiMabKt6eqBB0kX1QqHNWFWAXgi0VULKGisM46luRFpIBiU3u/TDmhZMM8tzvo2Abn3ayg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"app-builder-lib": "25.1.8",
|
"app-builder-lib": "25.1.8",
|
||||||
"archiver": "^5.3.1",
|
"archiver": "^5.3.1",
|
||||||
@ -3989,6 +4042,7 @@
|
|||||||
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
|
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"graceful-fs": "^4.2.0",
|
"graceful-fs": "^4.2.0",
|
||||||
"jsonfile": "^6.0.1",
|
"jsonfile": "^6.0.1",
|
||||||
@ -4004,6 +4058,7 @@
|
|||||||
"integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
|
"integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"universalify": "^2.0.0"
|
"universalify": "^2.0.0"
|
||||||
},
|
},
|
||||||
@ -4017,6 +4072,7 @@
|
|||||||
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
|
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 10.0.0"
|
"node": ">= 10.0.0"
|
||||||
}
|
}
|
||||||
@ -4253,7 +4309,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"esbuild": "bin/esbuild"
|
"esbuild": "bin/esbuild"
|
||||||
},
|
},
|
||||||
@ -4539,7 +4594,8 @@
|
|||||||
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
|
||||||
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/fs-extra": {
|
"node_modules/fs-extra": {
|
||||||
"version": "8.1.0",
|
"version": "8.1.0",
|
||||||
@ -5146,6 +5202,22 @@
|
|||||||
"is-ci": "bin.js"
|
"is-ci": "bin.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/is-docker": {
|
||||||
|
"version": "2.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
|
||||||
|
"integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"is-docker": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/is-fullwidth-code-point": {
|
"node_modules/is-fullwidth-code-point": {
|
||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||||
@ -5186,12 +5258,26 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/is-wsl": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"is-docker": "^2.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/isarray": {
|
"node_modules/isarray": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
||||||
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
|
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/isbinaryfile": {
|
"node_modules/isbinaryfile": {
|
||||||
"version": "5.0.7",
|
"version": "5.0.7",
|
||||||
@ -5376,6 +5462,7 @@
|
|||||||
"integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==",
|
"integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"readable-stream": "^2.0.5"
|
"readable-stream": "^2.0.5"
|
||||||
},
|
},
|
||||||
@ -5389,6 +5476,7 @@
|
|||||||
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
|
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"core-util-is": "~1.0.0",
|
"core-util-is": "~1.0.0",
|
||||||
"inherits": "~2.0.3",
|
"inherits": "~2.0.3",
|
||||||
@ -5404,7 +5492,8 @@
|
|||||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||||
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/lazystream/node_modules/string_decoder": {
|
"node_modules/lazystream/node_modules/string_decoder": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
@ -5412,6 +5501,7 @@
|
|||||||
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
|
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"safe-buffer": "~5.1.0"
|
"safe-buffer": "~5.1.0"
|
||||||
}
|
}
|
||||||
@ -5458,35 +5548,40 @@
|
|||||||
"resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
|
||||||
"integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
|
"integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/lodash.difference": {
|
"node_modules/lodash.difference": {
|
||||||
"version": "4.5.0",
|
"version": "4.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz",
|
||||||
"integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==",
|
"integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/lodash.flatten": {
|
"node_modules/lodash.flatten": {
|
||||||
"version": "4.4.0",
|
"version": "4.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz",
|
||||||
"integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==",
|
"integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/lodash.isplainobject": {
|
"node_modules/lodash.isplainobject": {
|
||||||
"version": "4.0.6",
|
"version": "4.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||||
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/lodash.union": {
|
"node_modules/lodash.union": {
|
||||||
"version": "4.6.0",
|
"version": "4.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz",
|
||||||
"integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==",
|
"integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/log-symbols": {
|
"node_modules/log-symbols": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
@ -6050,6 +6145,7 @@
|
|||||||
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
|
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@ -6310,7 +6406,6 @@
|
|||||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
},
|
},
|
||||||
@ -6375,7 +6470,6 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.11",
|
"nanoid": "^3.3.11",
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
@ -6433,7 +6527,8 @@
|
|||||||
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
|
||||||
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
|
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/progress": {
|
"node_modules/progress": {
|
||||||
"version": "2.0.3",
|
"version": "2.0.3",
|
||||||
@ -6507,12 +6602,24 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/rcedit": {
|
||||||
|
"version": "5.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/rcedit/-/rcedit-5.0.2.tgz",
|
||||||
|
"integrity": "sha512-dgysxaeXZ4snLpPjn8aVtHvZDCx+aRcvZbaWBgl1poU6OPustMvOkj9a9ZqASQ6i5Y5szJ13LSvglEOwrmgUxA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cross-spawn-windows-exe": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 22.12.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/react": {
|
"node_modules/react": {
|
||||||
"version": "18.3.1",
|
"version": "18.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"loose-envify": "^1.1.0"
|
"loose-envify": "^1.1.0"
|
||||||
},
|
},
|
||||||
@ -6577,6 +6684,7 @@
|
|||||||
"integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==",
|
"integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"minimatch": "^5.1.0"
|
"minimatch": "^5.1.0"
|
||||||
}
|
}
|
||||||
@ -6586,7 +6694,8 @@
|
|||||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/readdir-glob/node_modules/brace-expansion": {
|
"node_modules/readdir-glob/node_modules/brace-expansion": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
@ -6594,6 +6703,7 @@
|
|||||||
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"balanced-match": "^1.0.0"
|
"balanced-match": "^1.0.0"
|
||||||
}
|
}
|
||||||
@ -6604,6 +6714,7 @@
|
|||||||
"integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
|
"integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"brace-expansion": "^2.0.1"
|
"brace-expansion": "^2.0.1"
|
||||||
},
|
},
|
||||||
@ -7284,6 +7395,7 @@
|
|||||||
"integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
|
"integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bl": "^4.0.3",
|
"bl": "^4.0.3",
|
||||||
"end-of-stream": "^1.4.1",
|
"end-of-stream": "^1.4.1",
|
||||||
@ -7568,7 +7680,6 @@
|
|||||||
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
|
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "~0.27.0",
|
"esbuild": "~0.27.0",
|
||||||
"get-tsconfig": "^4.7.5"
|
"get-tsconfig": "^4.7.5"
|
||||||
@ -7751,7 +7862,6 @@
|
|||||||
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
|
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.25.0",
|
"esbuild": "^0.25.0",
|
||||||
"fdir": "^6.4.4",
|
"fdir": "^6.4.4",
|
||||||
@ -9361,7 +9471,6 @@
|
|||||||
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
|
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.21.3",
|
"esbuild": "^0.21.3",
|
||||||
"postcss": "^8.4.43",
|
"postcss": "^8.4.43",
|
||||||
@ -9619,6 +9728,7 @@
|
|||||||
"integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==",
|
"integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"archiver-utils": "^3.0.4",
|
"archiver-utils": "^3.0.4",
|
||||||
"compress-commons": "^4.1.2",
|
"compress-commons": "^4.1.2",
|
||||||
@ -9634,6 +9744,7 @@
|
|||||||
"integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==",
|
"integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"glob": "^7.2.3",
|
"glob": "^7.2.3",
|
||||||
"graceful-fs": "^4.2.0",
|
"graceful-fs": "^4.2.0",
|
||||||
|
|||||||
16
package.json
16
package.json
@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "real-debrid-downloader",
|
"name": "real-debrid-downloader",
|
||||||
"version": "1.4.28",
|
"version": "1.6.65",
|
||||||
"description": "Real-Debrid Downloader Desktop (Electron + React + TypeScript)",
|
"description": "Desktop downloader",
|
||||||
"main": "build/main/main/main.js",
|
"main": "build/main/main/main.js",
|
||||||
"author": "Sucukdeluxe",
|
"author": "Sucukdeluxe",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@ -16,7 +16,9 @@
|
|||||||
"start": "cross-env NODE_ENV=production electron .",
|
"start": "cross-env NODE_ENV=production electron .",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"self-check": "tsx tests/self-check.ts",
|
"self-check": "tsx tests/self-check.ts",
|
||||||
"release:win": "npm run build && electron-builder --publish never --win nsis portable"
|
"release:win": "npm run build && electron-builder --publish never --win nsis portable",
|
||||||
|
"release:gitea": "node scripts/release_gitea.mjs",
|
||||||
|
"release:forgejo": "node scripts/release_gitea.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"adm-zip": "^0.5.16",
|
"adm-zip": "^0.5.16",
|
||||||
@ -35,6 +37,7 @@
|
|||||||
"cross-env": "^7.0.3",
|
"cross-env": "^7.0.3",
|
||||||
"electron": "^31.7.7",
|
"electron": "^31.7.7",
|
||||||
"electron-builder": "^25.1.8",
|
"electron-builder": "^25.1.8",
|
||||||
|
"rcedit": "^5.0.2",
|
||||||
"tsup": "^8.3.6",
|
"tsup": "^8.3.6",
|
||||||
"tsx": "^4.19.2",
|
"tsx": "^4.19.2",
|
||||||
"typescript": "^5.7.3",
|
"typescript": "^5.7.3",
|
||||||
@ -52,8 +55,12 @@
|
|||||||
"files": [
|
"files": [
|
||||||
"build/main/**/*",
|
"build/main/**/*",
|
||||||
"build/renderer/**/*",
|
"build/renderer/**/*",
|
||||||
|
"resources/extractor-jvm/**/*",
|
||||||
"package.json"
|
"package.json"
|
||||||
],
|
],
|
||||||
|
"asarUnpack": [
|
||||||
|
"resources/extractor-jvm/**/*"
|
||||||
|
],
|
||||||
"win": {
|
"win": {
|
||||||
"target": [
|
"target": [
|
||||||
"nsis",
|
"nsis",
|
||||||
@ -67,6 +74,7 @@
|
|||||||
"perMachine": false,
|
"perMachine": false,
|
||||||
"allowToChangeInstallationDirectory": true,
|
"allowToChangeInstallationDirectory": true,
|
||||||
"createDesktopShortcut": true
|
"createDesktopShortcut": true
|
||||||
}
|
},
|
||||||
|
"afterPack": "scripts/afterPack.cjs"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
22
resources/extractor-jvm/README.md
Normal file
22
resources/extractor-jvm/README.md
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
# JVM extractor runtime
|
||||||
|
|
||||||
|
This directory contains the Java sidecar runtime used by `src/main/extractor.ts`.
|
||||||
|
|
||||||
|
## Included backends
|
||||||
|
|
||||||
|
- `sevenzipjbinding` for the primary extraction path (RAR/7z/ZIP and others)
|
||||||
|
- `zip4j` for ZIP multipart handling (JD-style split ZIP behavior)
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
- `classes/` compiled `JBindExtractorMain` classes
|
||||||
|
- `lib/` runtime jars required by the sidecar
|
||||||
|
- `src/` Java source for the sidecar
|
||||||
|
|
||||||
|
## Rebuild notes
|
||||||
|
|
||||||
|
The checked-in classes are Java 8 compatible and built from:
|
||||||
|
|
||||||
|
`resources/extractor-jvm/src/com/sucukdeluxe/extractor/JBindExtractorMain.java`
|
||||||
|
|
||||||
|
If you need to rebuild, compile against the jars in `lib/` with a Java 8-compatible compiler.
|
||||||
12
resources/extractor-jvm/THIRD_PARTY_NOTICES.txt
Normal file
12
resources/extractor-jvm/THIRD_PARTY_NOTICES.txt
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
Bundled JVM extractor dependencies:
|
||||||
|
|
||||||
|
1) sevenzipjbinding (16.02-2.01)
|
||||||
|
- Maven artifact: net.sf.sevenzipjbinding:sevenzipjbinding
|
||||||
|
- Maven artifact: net.sf.sevenzipjbinding:sevenzipjbinding-all-platforms
|
||||||
|
- Upstream: https://sevenzipjbind.sourceforge.net/
|
||||||
|
|
||||||
|
2) zip4j (2.11.5)
|
||||||
|
- Maven artifact: net.lingala.zip4j:zip4j
|
||||||
|
- Upstream: https://github.com/srikanth-lingala/zip4j
|
||||||
|
|
||||||
|
Please review upstream licenses and notices before redistribution.
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
resources/extractor-jvm/lib/sevenzipjbinding-all-platforms.jar
Normal file
BIN
resources/extractor-jvm/lib/sevenzipjbinding-all-platforms.jar
Normal file
Binary file not shown.
BIN
resources/extractor-jvm/lib/sevenzipjbinding.jar
Normal file
BIN
resources/extractor-jvm/lib/sevenzipjbinding.jar
Normal file
Binary file not shown.
BIN
resources/extractor-jvm/lib/zip4j.jar
Normal file
BIN
resources/extractor-jvm/lib/zip4j.jar
Normal file
Binary file not shown.
File diff suppressed because it is too large
Load Diff
18
scripts/afterPack.cjs
Normal file
18
scripts/afterPack.cjs
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
const path = require("path");
|
||||||
|
const { rcedit } = require("rcedit");
|
||||||
|
|
||||||
|
module.exports = async function afterPack(context) {
|
||||||
|
const productFilename = context.packager?.appInfo?.productFilename;
|
||||||
|
if (!productFilename) {
|
||||||
|
console.warn(" • rcedit: skipped — productFilename not available");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const exePath = path.join(context.appOutDir, `${productFilename}.exe`);
|
||||||
|
const iconPath = path.resolve(__dirname, "..", "assets", "app_icon.ico");
|
||||||
|
console.log(` • rcedit: patching icon → ${exePath}`);
|
||||||
|
try {
|
||||||
|
await rcedit(exePath, { icon: iconPath });
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(` • rcedit: failed — ${String(error)}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -31,6 +31,7 @@ async function main(): Promise<void> {
|
|||||||
login: settings.megaLogin,
|
login: settings.megaLogin,
|
||||||
password: settings.megaPassword
|
password: settings.megaPassword
|
||||||
}));
|
}));
|
||||||
|
try {
|
||||||
const service = new DebridService(settings, {
|
const service = new DebridService(settings, {
|
||||||
megaWebUnrestrict: (link) => megaWeb.unrestrict(link)
|
megaWebUnrestrict: (link) => megaWeb.unrestrict(link)
|
||||||
});
|
});
|
||||||
@ -42,7 +43,9 @@ async function main(): Promise<void> {
|
|||||||
console.log(`[FAIL] ${String(error)}`);
|
console.log(`[FAIL] ${String(error)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
megaWeb.dispose();
|
megaWeb.dispose();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void main();
|
main().catch(e => { console.error(e); process.exit(1); });
|
||||||
|
|||||||
@ -16,8 +16,8 @@ function sleep(ms) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function cookieFrom(headers) {
|
function cookieFrom(headers) {
|
||||||
const raw = headers.get("set-cookie") || "";
|
const cookies = headers.getSetCookie();
|
||||||
return raw.split(",").map((x) => x.split(";")[0].trim()).filter(Boolean).join("; ");
|
return cookies.map((x) => x.split(";")[0].trim()).filter(Boolean).join("; ");
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseDebridCodes(html) {
|
function parseDebridCodes(html) {
|
||||||
@ -47,6 +47,9 @@ async function resolveCode(cookie, code) {
|
|||||||
});
|
});
|
||||||
const text = (await res.text()).trim();
|
const text = (await res.text()).trim();
|
||||||
if (text === "reload") {
|
if (text === "reload") {
|
||||||
|
if (attempt % 5 === 0) {
|
||||||
|
console.log(` [retry] code=${code} attempt=${attempt}/50 (waiting for server)`);
|
||||||
|
}
|
||||||
await sleep(800);
|
await sleep(800);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -98,7 +101,13 @@ async function main() {
|
|||||||
redirect: "manual"
|
redirect: "manual"
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (loginRes.status >= 400) {
|
||||||
|
throw new Error(`Login failed with HTTP ${loginRes.status}`);
|
||||||
|
}
|
||||||
const cookie = cookieFrom(loginRes.headers);
|
const cookie = cookieFrom(loginRes.headers);
|
||||||
|
if (!cookie) {
|
||||||
|
throw new Error("Login returned no session cookie");
|
||||||
|
}
|
||||||
console.log("login", loginRes.status, loginRes.headers.get("location") || "");
|
console.log("login", loginRes.status, loginRes.headers.get("location") || "");
|
||||||
|
|
||||||
const debridRes = await fetch("https://www.mega-debrid.eu/index.php?form=debrid", {
|
const debridRes = await fetch("https://www.mega-debrid.eu/index.php?form=debrid", {
|
||||||
@ -136,4 +145,4 @@ async function main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await main();
|
await main().catch((e) => { console.error(e); process.exit(1); });
|
||||||
|
|||||||
@ -66,6 +66,8 @@ async function callRealDebrid(link) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// megaCookie is intentionally cached at module scope so that multiple
|
||||||
|
// callMegaDebrid() invocations reuse the same session cookie.
|
||||||
async function callMegaDebrid(link) {
|
async function callMegaDebrid(link) {
|
||||||
if (!megaCookie) {
|
if (!megaCookie) {
|
||||||
const loginRes = await fetch("https://www.mega-debrid.eu/index.php?form=login", {
|
const loginRes = await fetch("https://www.mega-debrid.eu/index.php?form=login", {
|
||||||
@ -77,13 +79,15 @@ async function callMegaDebrid(link) {
|
|||||||
body: new URLSearchParams({ login: megaLogin, password: megaPassword, remember: "on" }),
|
body: new URLSearchParams({ login: megaLogin, password: megaPassword, remember: "on" }),
|
||||||
redirect: "manual"
|
redirect: "manual"
|
||||||
});
|
});
|
||||||
megaCookie = (loginRes.headers.get("set-cookie") || "")
|
if (loginRes.status >= 400) {
|
||||||
.split(",")
|
return { ok: false, error: `Mega-Web login failed with HTTP ${loginRes.status}` };
|
||||||
|
}
|
||||||
|
megaCookie = loginRes.headers.getSetCookie()
|
||||||
.map((chunk) => chunk.split(";")[0].trim())
|
.map((chunk) => chunk.split(";")[0].trim())
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join("; ");
|
.join("; ");
|
||||||
if (!megaCookie) {
|
if (!megaCookie) {
|
||||||
return { ok: false, error: "Mega-Web login failed" };
|
return { ok: false, error: "Mega-Web login returned no session cookie" };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -290,4 +294,4 @@ async function main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await main();
|
await main().catch((e) => { console.error(e); process.exit(1); });
|
||||||
|
|||||||
356
scripts/release_gitea.mjs
Normal file
356
scripts/release_gitea.mjs
Normal file
@ -0,0 +1,356 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
|
||||||
|
const NPM_RELEASE_WIN = process.platform === "win32"
|
||||||
|
? {
|
||||||
|
command: process.env.ComSpec || "cmd.exe",
|
||||||
|
args: ["/d", "/s", "/c", "npm run release:win"]
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
command: "npm",
|
||||||
|
args: ["run", "release:win"]
|
||||||
|
};
|
||||||
|
|
||||||
|
function run(command, args, options = {}) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
cwd: process.cwd(),
|
||||||
|
encoding: "utf8",
|
||||||
|
stdio: options.capture ? ["pipe", "pipe", "pipe"] : "inherit"
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
const stderr = result.stderr ? String(result.stderr).trim() : "";
|
||||||
|
const stdout = result.stdout ? String(result.stdout).trim() : "";
|
||||||
|
const details = [stderr, stdout].filter(Boolean).join("\n");
|
||||||
|
throw new Error(`Command failed: ${command} ${args.join(" ")}${details ? `\n${details}` : ""}`);
|
||||||
|
}
|
||||||
|
return options.capture ? String(result.stdout || "") : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function runCapture(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
cwd: process.cwd(),
|
||||||
|
encoding: "utf8",
|
||||||
|
stdio: ["pipe", "pipe", "pipe"]
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
const stderr = String(result.stderr || "").trim();
|
||||||
|
throw new Error(stderr || `Command failed: ${command} ${args.join(" ")}`);
|
||||||
|
}
|
||||||
|
return String(result.stdout || "").trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function runWithInput(command, args, input) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
cwd: process.cwd(),
|
||||||
|
encoding: "utf8",
|
||||||
|
input,
|
||||||
|
stdio: ["pipe", "pipe", "pipe"],
|
||||||
|
timeout: 10000
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
const stderr = String(result.stderr || "").trim();
|
||||||
|
throw new Error(stderr || `Command failed: ${command} ${args.join(" ")}`);
|
||||||
|
}
|
||||||
|
return String(result.stdout || "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const args = argv.slice(2);
|
||||||
|
if (args.includes("--help") || args.includes("-h")) {
|
||||||
|
return { help: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const dryRun = args.includes("--dry-run");
|
||||||
|
const cleaned = args.filter((arg) => arg !== "--dry-run");
|
||||||
|
const version = cleaned[0] || "";
|
||||||
|
const notes = cleaned.slice(1).join(" ").trim();
|
||||||
|
return { help: false, dryRun, version, notes };
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRemoteUrl(url) {
|
||||||
|
const raw = String(url || "").trim();
|
||||||
|
const httpsMatch = raw.match(/^https?:\/\/([^/]+)\/([^/]+)\/([^/]+?)(?:\.git)?$/i);
|
||||||
|
if (httpsMatch) {
|
||||||
|
return { host: httpsMatch[1], owner: httpsMatch[2], repo: httpsMatch[3] };
|
||||||
|
}
|
||||||
|
const sshMatch = raw.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/i);
|
||||||
|
if (sshMatch) {
|
||||||
|
return { host: sshMatch[1], owner: sshMatch[2], repo: sshMatch[3] };
|
||||||
|
}
|
||||||
|
const sshAltMatch = raw.match(/^ssh:\/\/git@([^/:]+)(?::\d+)?\/([^/]+)\/([^/]+?)(?:\.git)?$/i);
|
||||||
|
if (sshAltMatch) {
|
||||||
|
return { host: sshAltMatch[1], owner: sshAltMatch[2], repo: sshAltMatch[3] };
|
||||||
|
}
|
||||||
|
throw new Error(`Cannot parse remote URL: ${raw}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeBaseUrl(url) {
|
||||||
|
const raw = String(url || "").trim().replace(/\/+$/, "");
|
||||||
|
if (!raw) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (!/^https?:\/\//i.test(raw)) {
|
||||||
|
throw new Error("GITEA_BASE_URL must start with http:// or https://");
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getGiteaRepo() {
|
||||||
|
const forcedRemote = String(process.env.GITEA_REMOTE || process.env.FORGEJO_REMOTE || "").trim();
|
||||||
|
const remotes = forcedRemote
|
||||||
|
? [forcedRemote]
|
||||||
|
: ["gitea", "forgejo", "origin", "github-new", "codeberg"];
|
||||||
|
|
||||||
|
const preferredBase = normalizeBaseUrl(process.env.GITEA_BASE_URL || process.env.FORGEJO_BASE_URL || "https://git.24-music.de");
|
||||||
|
|
||||||
|
const preferredProtocol = preferredBase ? new URL(preferredBase).protocol : "https:";
|
||||||
|
|
||||||
|
for (const remote of remotes) {
|
||||||
|
try {
|
||||||
|
const remoteUrl = runCapture("git", ["remote", "get-url", remote]);
|
||||||
|
const parsed = parseRemoteUrl(remoteUrl);
|
||||||
|
const remoteBase = `https://${parsed.host}`.toLowerCase();
|
||||||
|
if (preferredBase && remoteBase !== preferredBase.toLowerCase().replace(/^http:/, "https:")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return { remote, ...parsed, baseUrl: `${preferredProtocol}//${parsed.host}` };
|
||||||
|
} catch {
|
||||||
|
// try next remote
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preferredBase) {
|
||||||
|
throw new Error(
|
||||||
|
`No remote found for ${preferredBase}. Add one with: git remote add gitea ${preferredBase}/<owner>/<repo>.git`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("No suitable remote found. Set GITEA_REMOTE or GITEA_BASE_URL.");
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAuthHeader(host) {
|
||||||
|
const explicitToken = String(process.env.GITEA_TOKEN || process.env.FORGEJO_TOKEN || "").trim();
|
||||||
|
if (explicitToken) {
|
||||||
|
return `token ${explicitToken}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const credentialText = runWithInput("git", ["credential", "fill"], `protocol=https\nhost=${host}\n\n`);
|
||||||
|
const map = new Map();
|
||||||
|
for (const line of credentialText.split(/\r?\n/)) {
|
||||||
|
if (!line.includes("=")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const [key, value] = line.split("=", 2);
|
||||||
|
map.set(key, value);
|
||||||
|
}
|
||||||
|
const username = map.get("username") || "";
|
||||||
|
const password = map.get("password") || "";
|
||||||
|
if (!username || !password) {
|
||||||
|
throw new Error(
|
||||||
|
`Missing credentials for ${host}. Set GITEA_TOKEN or store credentials for this host in git credential helper.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const token = Buffer.from(`${username}:${password}`, "utf8").toString("base64");
|
||||||
|
return `Basic ${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function apiRequest(method, url, authHeader, body, contentType = "application/json") {
|
||||||
|
const headers = {
|
||||||
|
Accept: "application/json",
|
||||||
|
Authorization: authHeader
|
||||||
|
};
|
||||||
|
if (body !== undefined) {
|
||||||
|
headers["Content-Type"] = contentType;
|
||||||
|
}
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
body
|
||||||
|
});
|
||||||
|
const text = await response.text();
|
||||||
|
let parsed;
|
||||||
|
try {
|
||||||
|
parsed = text ? JSON.parse(text) : null;
|
||||||
|
} catch {
|
||||||
|
parsed = text;
|
||||||
|
}
|
||||||
|
return { ok: response.ok, status: response.status, body: parsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureVersionString(version) {
|
||||||
|
const trimmed = String(version || "").trim();
|
||||||
|
if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(trimmed)) {
|
||||||
|
throw new Error("Invalid version format. Expected e.g. 1.4.42");
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePackageVersion(rootDir, version) {
|
||||||
|
const packagePath = path.join(rootDir, "package.json");
|
||||||
|
const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf8"));
|
||||||
|
if (String(packageJson.version || "") === version) {
|
||||||
|
process.stdout.write(`package.json is already at version ${version}, skipping update.\n`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
packageJson.version = version;
|
||||||
|
fs.writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`, "utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
function patchLatestYml(releaseDir, version) {
|
||||||
|
const ymlPath = path.join(releaseDir, "latest.yml");
|
||||||
|
let content = fs.readFileSync(ymlPath, "utf8");
|
||||||
|
const setupName = `Real-Debrid-Downloader Setup ${version}.exe`;
|
||||||
|
const dashedName = `Real-Debrid-Downloader-Setup-${version}.exe`;
|
||||||
|
if (content.includes(dashedName)) {
|
||||||
|
content = content.split(dashedName).join(setupName);
|
||||||
|
fs.writeFileSync(ymlPath, content, "utf8");
|
||||||
|
process.stdout.write(`Patched latest.yml: replaced "${dashedName}" with "${setupName}"\n`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureAssetsExist(rootDir, version) {
|
||||||
|
const releaseDir = path.join(rootDir, "release");
|
||||||
|
const files = [
|
||||||
|
`Real-Debrid-Downloader Setup ${version}.exe`,
|
||||||
|
`Real-Debrid-Downloader ${version}.exe`,
|
||||||
|
"latest.yml",
|
||||||
|
`Real-Debrid-Downloader Setup ${version}.exe.blockmap`
|
||||||
|
];
|
||||||
|
for (const fileName of files) {
|
||||||
|
const fullPath = path.join(releaseDir, fileName);
|
||||||
|
if (!fs.existsSync(fullPath)) {
|
||||||
|
throw new Error(`Missing release artifact: ${fullPath}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
patchLatestYml(releaseDir, version);
|
||||||
|
return { releaseDir, files };
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureNoTrackedChanges() {
|
||||||
|
const output = runCapture("git", ["status", "--porcelain"]);
|
||||||
|
const lines = output.split(/\r?\n/).filter(Boolean);
|
||||||
|
const tracked = lines.filter((line) => !line.startsWith("?? "));
|
||||||
|
if (tracked.length > 0) {
|
||||||
|
throw new Error(`Working tree has tracked changes:\n${tracked.join("\n")}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureTagMissing(tag) {
|
||||||
|
const result = spawnSync("git", ["rev-parse", "--verify", `refs/tags/${tag}`], {
|
||||||
|
cwd: process.cwd(),
|
||||||
|
stdio: "ignore"
|
||||||
|
});
|
||||||
|
if (result.status === 0) {
|
||||||
|
throw new Error(`Tag already exists: ${tag}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createOrGetRelease(baseApi, tag, authHeader, notes) {
|
||||||
|
const byTag = await apiRequest("GET", `${baseApi}/releases/tags/${encodeURIComponent(tag)}`, authHeader);
|
||||||
|
if (byTag.ok) {
|
||||||
|
return byTag.body;
|
||||||
|
}
|
||||||
|
const payload = {
|
||||||
|
tag_name: tag,
|
||||||
|
target_commitish: "main",
|
||||||
|
name: tag,
|
||||||
|
body: notes || `Release ${tag}`,
|
||||||
|
draft: false,
|
||||||
|
prerelease: false
|
||||||
|
};
|
||||||
|
const created = await apiRequest("POST", `${baseApi}/releases`, authHeader, JSON.stringify(payload));
|
||||||
|
if (!created.ok) {
|
||||||
|
throw new Error(`Failed to create release (${created.status}): ${JSON.stringify(created.body)}`);
|
||||||
|
}
|
||||||
|
return created.body;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadReleaseAssets(baseApi, releaseId, authHeader, releaseDir, files) {
|
||||||
|
for (const fileName of files) {
|
||||||
|
const filePath = path.join(releaseDir, fileName);
|
||||||
|
const fileSize = fs.statSync(filePath).size;
|
||||||
|
const uploadUrl = `${baseApi}/releases/${releaseId}/assets?name=${encodeURIComponent(fileName)}`;
|
||||||
|
|
||||||
|
// Stream large files instead of loading them entirely into memory
|
||||||
|
const fileStream = fs.createReadStream(filePath);
|
||||||
|
const response = await fetch(uploadUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
Authorization: authHeader,
|
||||||
|
"Content-Type": "application/octet-stream",
|
||||||
|
"Content-Length": String(fileSize)
|
||||||
|
},
|
||||||
|
body: fileStream,
|
||||||
|
duplex: "half"
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
let parsed;
|
||||||
|
try {
|
||||||
|
parsed = text ? JSON.parse(text) : null;
|
||||||
|
} catch {
|
||||||
|
parsed = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
process.stdout.write(`Uploaded: ${fileName}\n`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (response.status === 409 || response.status === 422) {
|
||||||
|
process.stdout.write(`Skipped existing asset: ${fileName}\n`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw new Error(`Asset upload failed for ${fileName} (${response.status}): ${JSON.stringify(parsed)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const rootDir = process.cwd();
|
||||||
|
const args = parseArgs(process.argv);
|
||||||
|
if (args.help) {
|
||||||
|
process.stdout.write("Usage: npm run release:gitea -- <version> [release notes] [--dry-run]\n");
|
||||||
|
process.stdout.write("Env: GITEA_BASE_URL, GITEA_REMOTE, GITEA_TOKEN\n");
|
||||||
|
process.stdout.write("Compatibility envs still supported: FORGEJO_BASE_URL, FORGEJO_REMOTE, FORGEJO_TOKEN\n");
|
||||||
|
process.stdout.write("Example: npm run release:gitea -- 1.6.31 \"- Bugfixes\"\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const version = ensureVersionString(args.version);
|
||||||
|
const tag = `v${version}`;
|
||||||
|
const releaseNotes = args.notes || `- Release ${tag}`;
|
||||||
|
const repo = getGiteaRepo();
|
||||||
|
|
||||||
|
ensureNoTrackedChanges();
|
||||||
|
ensureTagMissing(tag);
|
||||||
|
|
||||||
|
if (args.dryRun) {
|
||||||
|
process.stdout.write(`Dry run: would release ${tag}. No changes made.\n`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
updatePackageVersion(rootDir, version);
|
||||||
|
|
||||||
|
process.stdout.write(`Building release artifacts for ${tag}...\n`);
|
||||||
|
run(NPM_RELEASE_WIN.command, NPM_RELEASE_WIN.args);
|
||||||
|
const assets = ensureAssetsExist(rootDir, version);
|
||||||
|
|
||||||
|
run("git", ["add", "package.json"]);
|
||||||
|
run("git", ["commit", "-m", `Release ${tag}`]);
|
||||||
|
run("git", ["push", repo.remote, "main"]);
|
||||||
|
run("git", ["tag", tag]);
|
||||||
|
run("git", ["push", repo.remote, tag]);
|
||||||
|
|
||||||
|
const authHeader = getAuthHeader(repo.host);
|
||||||
|
const baseApi = `${repo.baseUrl}/api/v1/repos/${repo.owner}/${repo.repo}`;
|
||||||
|
const release = await createOrGetRelease(baseApi, tag, authHeader, releaseNotes);
|
||||||
|
await uploadReleaseAssets(baseApi, release.id, authHeader, assets.releaseDir, assets.files);
|
||||||
|
|
||||||
|
process.stdout.write(`Release published: ${release.html_url || `${repo.baseUrl}/${repo.owner}/${repo.repo}/releases/tag/${tag}`}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
process.stderr.write(`${String(error?.message || error)}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@ -1,24 +0,0 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
|
|
||||||
const version = process.argv[2];
|
|
||||||
if (!version) {
|
|
||||||
console.error("Usage: node scripts/set_version_node.mjs <version>");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const root = process.cwd();
|
|
||||||
|
|
||||||
const packageJsonPath = path.join(root, "package.json");
|
|
||||||
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
|
|
||||||
packageJson.version = version;
|
|
||||||
fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`, "utf8");
|
|
||||||
|
|
||||||
const constantsPath = path.join(root, "src", "main", "constants.ts");
|
|
||||||
const constants = fs.readFileSync(constantsPath, "utf8").replace(
|
|
||||||
/APP_VERSION = "[^"]+"/,
|
|
||||||
`APP_VERSION = "${version}"`
|
|
||||||
);
|
|
||||||
fs.writeFileSync(constantsPath, constants, "utf8");
|
|
||||||
|
|
||||||
console.log(`Set version to ${version}`);
|
|
||||||
@ -4,11 +4,15 @@ import {
|
|||||||
AddLinksPayload,
|
AddLinksPayload,
|
||||||
AppSettings,
|
AppSettings,
|
||||||
DuplicatePolicy,
|
DuplicatePolicy,
|
||||||
|
HistoryEntry,
|
||||||
|
PackagePriority,
|
||||||
ParsedPackageInput,
|
ParsedPackageInput,
|
||||||
|
SessionStats,
|
||||||
StartConflictEntry,
|
StartConflictEntry,
|
||||||
StartConflictResolutionResult,
|
StartConflictResolutionResult,
|
||||||
UiSnapshot,
|
UiSnapshot,
|
||||||
UpdateCheckResult,
|
UpdateCheckResult,
|
||||||
|
UpdateInstallProgress,
|
||||||
UpdateInstallResult
|
UpdateInstallResult
|
||||||
} from "../shared/types";
|
} from "../shared/types";
|
||||||
import { importDlcContainers } from "./container";
|
import { importDlcContainers } from "./container";
|
||||||
@ -16,9 +20,11 @@ import { APP_VERSION } from "./constants";
|
|||||||
import { DownloadManager } from "./download-manager";
|
import { DownloadManager } from "./download-manager";
|
||||||
import { parseCollectorInput } from "./link-parser";
|
import { parseCollectorInput } from "./link-parser";
|
||||||
import { configureLogger, getLogFilePath, logger } from "./logger";
|
import { configureLogger, getLogFilePath, logger } from "./logger";
|
||||||
|
import { initSessionLog, getSessionLogPath, shutdownSessionLog } from "./session-log";
|
||||||
import { MegaWebFallback } from "./mega-web-fallback";
|
import { MegaWebFallback } from "./mega-web-fallback";
|
||||||
import { createStoragePaths, loadSession, loadSettings, normalizeSettings, saveSettings } from "./storage";
|
import { addHistoryEntry, cancelPendingAsyncSaves, clearHistory, createStoragePaths, loadHistory, loadSession, loadSettings, normalizeLoadedSession, normalizeLoadedSessionTransientFields, normalizeSettings, removeHistoryEntry, saveSession, saveSettings } from "./storage";
|
||||||
import { checkGitHubUpdate, installLatestUpdate } from "./update";
|
import { abortActiveUpdateDownload, checkGitHubUpdate, installLatestUpdate } from "./update";
|
||||||
|
import { startDebugServer, stopDebugServer } from "./debug-server";
|
||||||
|
|
||||||
function sanitizeSettingsPatch(partial: Partial<AppSettings>): Partial<AppSettings> {
|
function sanitizeSettingsPatch(partial: Partial<AppSettings>): Partial<AppSettings> {
|
||||||
const entries = Object.entries(partial || {}).filter(([, value]) => value !== undefined);
|
const entries = Object.entries(partial || {}).filter(([, value]) => value !== undefined);
|
||||||
@ -44,8 +50,11 @@ export class AppController {
|
|||||||
|
|
||||||
private onStateHandler: ((snapshot: UiSnapshot) => void) | null = null;
|
private onStateHandler: ((snapshot: UiSnapshot) => void) | null = null;
|
||||||
|
|
||||||
|
private autoResumePending = false;
|
||||||
|
|
||||||
public constructor() {
|
public constructor() {
|
||||||
configureLogger(this.storagePaths.baseDir);
|
configureLogger(this.storagePaths.baseDir);
|
||||||
|
initSessionLog(this.storagePaths.baseDir);
|
||||||
this.settings = loadSettings(this.storagePaths);
|
this.settings = loadSettings(this.storagePaths);
|
||||||
const session = loadSession(this.storagePaths);
|
const session = loadSession(this.storagePaths);
|
||||||
this.megaWebFallback = new MegaWebFallback(() => ({
|
this.megaWebFallback = new MegaWebFallback(() => ({
|
||||||
@ -53,24 +62,40 @@ export class AppController {
|
|||||||
password: this.settings.megaPassword
|
password: this.settings.megaPassword
|
||||||
}));
|
}));
|
||||||
this.manager = new DownloadManager(this.settings, session, this.storagePaths, {
|
this.manager = new DownloadManager(this.settings, session, this.storagePaths, {
|
||||||
megaWebUnrestrict: (link: string) => this.megaWebFallback.unrestrict(link)
|
megaWebUnrestrict: (link: string, signal?: AbortSignal) => this.megaWebFallback.unrestrict(link, signal),
|
||||||
|
invalidateMegaSession: () => this.megaWebFallback.invalidateSession(),
|
||||||
|
onHistoryEntry: (entry: HistoryEntry) => {
|
||||||
|
addHistoryEntry(this.storagePaths, entry);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
this.manager.on("state", (snapshot: UiSnapshot) => {
|
this.manager.on("state", (snapshot: UiSnapshot) => {
|
||||||
this.onStateHandler?.(snapshot);
|
this.onStateHandler?.(snapshot);
|
||||||
});
|
});
|
||||||
logger.info(`App gestartet v${APP_VERSION}`);
|
logger.info(`App gestartet v${APP_VERSION}`);
|
||||||
logger.info(`Log-Datei: ${getLogFilePath()}`);
|
logger.info(`Log-Datei: ${getLogFilePath()}`);
|
||||||
|
startDebugServer(this.manager, this.storagePaths.baseDir);
|
||||||
|
|
||||||
if (this.settings.autoResumeOnStart) {
|
if (this.settings.autoResumeOnStart) {
|
||||||
const snapshot = this.manager.getSnapshot();
|
const snapshot = this.manager.getSnapshot();
|
||||||
const hasPending = Object.values(snapshot.session.items).some((item) => item.status === "queued" || item.status === "reconnect_wait");
|
const hasPending = Object.values(snapshot.session.items).some((item) => item.status === "queued" || item.status === "reconnect_wait");
|
||||||
const hasConflicts = this.manager.getStartConflicts().length > 0;
|
if (hasPending) {
|
||||||
if (hasPending && this.hasAnyProviderToken(this.settings) && !hasConflicts) {
|
void this.manager.getStartConflicts().then((conflicts) => {
|
||||||
this.manager.start();
|
const hasConflicts = conflicts.length > 0;
|
||||||
logger.info("Auto-Resume beim Start aktiviert");
|
if (this.hasAnyProviderToken(this.settings) && !hasConflicts) {
|
||||||
} else if (hasPending && hasConflicts) {
|
// If the onState handler is already set (renderer connected), start immediately.
|
||||||
|
// Otherwise mark as pending so the onState setter triggers the start.
|
||||||
|
if (this.onStateHandler) {
|
||||||
|
logger.info("Auto-Resume beim Start aktiviert (nach Konflikt-Check)");
|
||||||
|
void this.manager.start().catch((err) => logger.warn(`Auto-Resume Start Fehler: ${String(err)}`));
|
||||||
|
} else {
|
||||||
|
this.autoResumePending = true;
|
||||||
|
logger.info("Auto-Resume beim Start vorgemerkt");
|
||||||
|
}
|
||||||
|
} else if (hasConflicts) {
|
||||||
logger.info("Auto-Resume übersprungen: Start-Konflikte erkannt");
|
logger.info("Auto-Resume übersprungen: Start-Konflikte erkannt");
|
||||||
}
|
}
|
||||||
|
}).catch((err) => logger.warn(`getStartConflicts Fehler (constructor): ${String(err)}`));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -80,6 +105,8 @@ export class AppController {
|
|||||||
|| (settings.megaLogin.trim() && settings.megaPassword.trim())
|
|| (settings.megaLogin.trim() && settings.megaPassword.trim())
|
||||||
|| settings.bestToken.trim()
|
|| settings.bestToken.trim()
|
||||||
|| settings.allDebridToken.trim()
|
|| settings.allDebridToken.trim()
|
||||||
|
|| (settings.ddownloadLogin.trim() && settings.ddownloadPassword.trim())
|
||||||
|
|| settings.oneFichierApiKey.trim()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,6 +118,14 @@ export class AppController {
|
|||||||
this.onStateHandler = handler;
|
this.onStateHandler = handler;
|
||||||
if (handler) {
|
if (handler) {
|
||||||
handler(this.manager.getSnapshot());
|
handler(this.manager.getSnapshot());
|
||||||
|
if (this.autoResumePending) {
|
||||||
|
this.autoResumePending = false;
|
||||||
|
void this.manager.start().catch((err) => logger.warn(`Auto-Resume Start Fehler: ${String(err)}`));
|
||||||
|
logger.info("Auto-Resume beim Start aktiviert");
|
||||||
|
} else {
|
||||||
|
// Trigger pending extractions without starting the session
|
||||||
|
this.manager.triggerIdleExtractions();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -117,6 +152,9 @@ export class AppController {
|
|||||||
return this.settings;
|
return this.settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Preserve the live totalDownloadedAllTime from the download manager
|
||||||
|
const liveSettings = this.manager.getSettings();
|
||||||
|
nextSettings.totalDownloadedAllTime = Math.max(nextSettings.totalDownloadedAllTime || 0, liveSettings.totalDownloadedAllTime || 0);
|
||||||
this.settings = nextSettings;
|
this.settings = nextSettings;
|
||||||
saveSettings(this.storagePaths, this.settings);
|
saveSettings(this.storagePaths, this.settings);
|
||||||
this.manager.setSettings(this.settings);
|
this.manager.setSettings(this.settings);
|
||||||
@ -132,12 +170,18 @@ export class AppController {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async installUpdate(): Promise<UpdateInstallResult> {
|
public async installUpdate(onProgress?: (progress: UpdateInstallProgress) => void): Promise<UpdateInstallResult> {
|
||||||
|
// Stop active downloads before installing. Extractions may continue briefly
|
||||||
|
// until prepareForShutdown() is called during app quit.
|
||||||
|
if (this.manager.isSessionRunning()) {
|
||||||
|
this.manager.stop();
|
||||||
|
}
|
||||||
|
|
||||||
const cacheAgeMs = Date.now() - this.lastUpdateCheckAt;
|
const cacheAgeMs = Date.now() - this.lastUpdateCheckAt;
|
||||||
const cached = this.lastUpdateCheck && !this.lastUpdateCheck.error && cacheAgeMs <= 10 * 60 * 1000
|
const cached = this.lastUpdateCheck && !this.lastUpdateCheck.error && cacheAgeMs <= 10 * 60 * 1000
|
||||||
? this.lastUpdateCheck
|
? this.lastUpdateCheck
|
||||||
: undefined;
|
: undefined;
|
||||||
const result = await installLatestUpdate(this.settings.updateRepo, cached);
|
const result = await installLatestUpdate(this.settings.updateRepo, cached, onProgress);
|
||||||
if (result.started) {
|
if (result.started) {
|
||||||
this.lastUpdateCheck = null;
|
this.lastUpdateCheck = null;
|
||||||
this.lastUpdateCheckAt = 0;
|
this.lastUpdateCheckAt = 0;
|
||||||
@ -158,13 +202,14 @@ export class AppController {
|
|||||||
const packages = await importDlcContainers(filePaths);
|
const packages = await importDlcContainers(filePaths);
|
||||||
const merged: ParsedPackageInput[] = packages.map((pkg) => ({
|
const merged: ParsedPackageInput[] = packages.map((pkg) => ({
|
||||||
name: pkg.name,
|
name: pkg.name,
|
||||||
links: pkg.links
|
links: pkg.links,
|
||||||
|
...(pkg.fileNames ? { fileNames: pkg.fileNames } : {})
|
||||||
}));
|
}));
|
||||||
const result = this.manager.addPackages(merged);
|
const result = this.manager.addPackages(merged);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public getStartConflicts(): StartConflictEntry[] {
|
public async getStartConflicts(): Promise<StartConflictEntry[]> {
|
||||||
return this.manager.getStartConflicts();
|
return this.manager.getStartConflicts();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -176,8 +221,16 @@ export class AppController {
|
|||||||
this.manager.clearAll();
|
this.manager.clearAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
public start(): void {
|
public async start(): Promise<void> {
|
||||||
this.manager.start();
|
await this.manager.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async startPackages(packageIds: string[]): Promise<void> {
|
||||||
|
await this.manager.startPackages(packageIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async startItems(itemIds: string[]): Promise<void> {
|
||||||
|
await this.manager.startItems(itemIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
public stop(): void {
|
public stop(): void {
|
||||||
@ -188,6 +241,18 @@ export class AppController {
|
|||||||
return this.manager.togglePause();
|
return this.manager.togglePause();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public retryExtraction(packageId: string): void {
|
||||||
|
this.manager.retryExtraction(packageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public extractNow(packageId: string): void {
|
||||||
|
this.manager.extractNow(packageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public resetPackage(packageId: string): void {
|
||||||
|
this.manager.resetPackage(packageId);
|
||||||
|
}
|
||||||
|
|
||||||
public cancelPackage(packageId: string): void {
|
public cancelPackage(packageId: string): void {
|
||||||
this.manager.cancelPackage(packageId);
|
this.manager.cancelPackage(packageId);
|
||||||
}
|
}
|
||||||
@ -216,9 +281,104 @@ export class AppController {
|
|||||||
return this.manager.importQueue(json);
|
return this.manager.importQueue(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public getSessionStats(): SessionStats {
|
||||||
|
return this.manager.getSessionStats();
|
||||||
|
}
|
||||||
|
|
||||||
|
public exportBackup(): string {
|
||||||
|
const settings = { ...this.settings };
|
||||||
|
const SENSITIVE_KEYS: (keyof AppSettings)[] = ["token", "megaLogin", "megaPassword", "bestToken", "allDebridToken", "ddownloadLogin", "ddownloadPassword", "oneFichierApiKey"];
|
||||||
|
for (const key of SENSITIVE_KEYS) {
|
||||||
|
const val = settings[key];
|
||||||
|
if (typeof val === "string" && val.length > 0) {
|
||||||
|
(settings as Record<string, unknown>)[key] = `***${val.slice(-4)}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const session = this.manager.getSession();
|
||||||
|
return JSON.stringify({ version: 1, settings, session }, null, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public importBackup(json: string): { restored: boolean; message: string } {
|
||||||
|
let parsed: Record<string, unknown>;
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(json) as Record<string, unknown>;
|
||||||
|
} catch {
|
||||||
|
return { restored: false, message: "Ungültiges JSON" };
|
||||||
|
}
|
||||||
|
if (!parsed || typeof parsed !== "object" || !parsed.settings || !parsed.session) {
|
||||||
|
return { restored: false, message: "Kein gültiges Backup (settings/session fehlen)" };
|
||||||
|
}
|
||||||
|
const importedSettings = parsed.settings as AppSettings;
|
||||||
|
const SENSITIVE_KEYS: (keyof AppSettings)[] = ["token", "megaLogin", "megaPassword", "bestToken", "allDebridToken", "ddownloadLogin", "ddownloadPassword", "oneFichierApiKey"];
|
||||||
|
for (const key of SENSITIVE_KEYS) {
|
||||||
|
const val = (importedSettings as Record<string, unknown>)[key];
|
||||||
|
if (typeof val === "string" && val.startsWith("***")) {
|
||||||
|
(importedSettings as Record<string, unknown>)[key] = (this.settings as Record<string, unknown>)[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const restoredSettings = normalizeSettings(importedSettings);
|
||||||
|
this.settings = restoredSettings;
|
||||||
|
saveSettings(this.storagePaths, this.settings);
|
||||||
|
this.manager.setSettings(this.settings);
|
||||||
|
// Full stop including extraction abort — the old session is being replaced,
|
||||||
|
// so no extraction tasks from it should keep running.
|
||||||
|
this.manager.stop();
|
||||||
|
this.manager.abortAllPostProcessing();
|
||||||
|
// Cancel any deferred persist timer and queued async writes so the old
|
||||||
|
// in-memory session does not overwrite the restored session file on disk.
|
||||||
|
this.manager.clearPersistTimer();
|
||||||
|
cancelPendingAsyncSaves();
|
||||||
|
const restoredSession = normalizeLoadedSessionTransientFields(
|
||||||
|
normalizeLoadedSession(parsed.session)
|
||||||
|
);
|
||||||
|
saveSession(this.storagePaths, restoredSession);
|
||||||
|
// Prevent prepareForShutdown from overwriting the restored session file
|
||||||
|
// with the old in-memory session when the app quits after backup restore.
|
||||||
|
this.manager.skipShutdownPersist = true;
|
||||||
|
// Block all persistence (including persistSoon from any IPC operations
|
||||||
|
// the user might trigger before restarting) to protect the restored backup.
|
||||||
|
this.manager.blockAllPersistence = true;
|
||||||
|
return { restored: true, message: "Backup wiederhergestellt. Bitte App neustarten." };
|
||||||
|
}
|
||||||
|
|
||||||
|
public getSessionLogPath(): string | null {
|
||||||
|
return getSessionLogPath();
|
||||||
|
}
|
||||||
|
|
||||||
public shutdown(): void {
|
public shutdown(): void {
|
||||||
|
stopDebugServer();
|
||||||
|
abortActiveUpdateDownload();
|
||||||
this.manager.prepareForShutdown();
|
this.manager.prepareForShutdown();
|
||||||
this.megaWebFallback.dispose();
|
this.megaWebFallback.dispose();
|
||||||
|
shutdownSessionLog();
|
||||||
logger.info("App beendet");
|
logger.info("App beendet");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public getHistory(): HistoryEntry[] {
|
||||||
|
return loadHistory(this.storagePaths);
|
||||||
|
}
|
||||||
|
|
||||||
|
public clearHistory(): void {
|
||||||
|
clearHistory(this.storagePaths);
|
||||||
|
}
|
||||||
|
|
||||||
|
public setPackagePriority(packageId: string, priority: PackagePriority): void {
|
||||||
|
this.manager.setPackagePriority(packageId, priority);
|
||||||
|
}
|
||||||
|
|
||||||
|
public skipItems(itemIds: string[]): void {
|
||||||
|
this.manager.skipItems(itemIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public resetItems(itemIds: string[]): void {
|
||||||
|
this.manager.resetItems(itemIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public removeHistoryEntry(entryId: string): void {
|
||||||
|
removeHistoryEntry(this.storagePaths, entryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public addToHistory(entry: HistoryEntry): void {
|
||||||
|
addHistoryEntry(this.storagePaths, entry);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
66
src/main/backup-crypto.ts
Normal file
66
src/main/backup-crypto.ts
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
import crypto from "node:crypto";
|
||||||
|
|
||||||
|
export const SENSITIVE_KEYS = [
|
||||||
|
"token",
|
||||||
|
"megaLogin",
|
||||||
|
"megaPassword",
|
||||||
|
"bestToken",
|
||||||
|
"allDebridToken",
|
||||||
|
"archivePasswordList"
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type SensitiveKey = (typeof SENSITIVE_KEYS)[number];
|
||||||
|
|
||||||
|
export interface EncryptedCredentials {
|
||||||
|
salt: string;
|
||||||
|
iv: string;
|
||||||
|
tag: string;
|
||||||
|
data: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PBKDF2_ITERATIONS = 100_000;
|
||||||
|
const KEY_LENGTH = 32; // 256 bit
|
||||||
|
const IV_LENGTH = 12; // 96 bit for GCM
|
||||||
|
const SALT_LENGTH = 16;
|
||||||
|
|
||||||
|
function deriveKey(username: string, salt: Buffer): Buffer {
|
||||||
|
return crypto.pbkdf2Sync(username, salt, PBKDF2_ITERATIONS, KEY_LENGTH, "sha256");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encryptCredentials(
|
||||||
|
fields: Record<string, string>,
|
||||||
|
username: string
|
||||||
|
): EncryptedCredentials {
|
||||||
|
const salt = crypto.randomBytes(SALT_LENGTH);
|
||||||
|
const iv = crypto.randomBytes(IV_LENGTH);
|
||||||
|
const key = deriveKey(username, salt);
|
||||||
|
|
||||||
|
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
|
||||||
|
const plaintext = JSON.stringify(fields);
|
||||||
|
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
||||||
|
const tag = cipher.getAuthTag();
|
||||||
|
|
||||||
|
return {
|
||||||
|
salt: salt.toString("hex"),
|
||||||
|
iv: iv.toString("hex"),
|
||||||
|
tag: tag.toString("hex"),
|
||||||
|
data: encrypted.toString("hex")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decryptCredentials(
|
||||||
|
encrypted: EncryptedCredentials,
|
||||||
|
username: string
|
||||||
|
): Record<string, string> {
|
||||||
|
const salt = Buffer.from(encrypted.salt, "hex");
|
||||||
|
const iv = Buffer.from(encrypted.iv, "hex");
|
||||||
|
const tag = Buffer.from(encrypted.tag, "hex");
|
||||||
|
const data = Buffer.from(encrypted.data, "hex");
|
||||||
|
const key = deriveKey(username, salt);
|
||||||
|
|
||||||
|
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
|
||||||
|
decipher.setAuthTag(tag);
|
||||||
|
const decrypted = Buffer.concat([decipher.update(data), decipher.final()]);
|
||||||
|
|
||||||
|
return JSON.parse(decrypted.toString("utf8")) as Record<string, string>;
|
||||||
|
}
|
||||||
@ -28,7 +28,9 @@ export function cleanupCancelledPackageArtifacts(packageDir: string): number {
|
|||||||
const stack = [packageDir];
|
const stack = [packageDir];
|
||||||
while (stack.length > 0) {
|
while (stack.length > 0) {
|
||||||
const current = stack.pop() as string;
|
const current = stack.pop() as string;
|
||||||
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
|
let entries: fs.Dirent[] = [];
|
||||||
|
try { entries = fs.readdirSync(current, { withFileTypes: true }); } catch { continue; }
|
||||||
|
for (const entry of entries) {
|
||||||
const full = path.join(current, entry.name);
|
const full = path.join(current, entry.name);
|
||||||
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
||||||
stack.push(full);
|
stack.push(full);
|
||||||
@ -86,15 +88,19 @@ export async function cleanupCancelledPackageArtifactsAsync(packageDir: string):
|
|||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function removeDownloadLinkArtifacts(extractDir: string): number {
|
export async function removeDownloadLinkArtifacts(extractDir: string): Promise<number> {
|
||||||
if (!fs.existsSync(extractDir)) {
|
try {
|
||||||
|
await fs.promises.access(extractDir);
|
||||||
|
} catch {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
let removed = 0;
|
let removed = 0;
|
||||||
const stack = [extractDir];
|
const stack = [extractDir];
|
||||||
while (stack.length > 0) {
|
while (stack.length > 0) {
|
||||||
const current = stack.pop() as string;
|
const current = stack.pop() as string;
|
||||||
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
|
let entries: fs.Dirent[] = [];
|
||||||
|
try { entries = await fs.promises.readdir(current, { withFileTypes: true }); } catch { continue; }
|
||||||
|
for (const entry of entries) {
|
||||||
const full = path.join(current, entry.name);
|
const full = path.join(current, entry.name);
|
||||||
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
||||||
stack.push(full);
|
stack.push(full);
|
||||||
@ -110,9 +116,9 @@ export function removeDownloadLinkArtifacts(extractDir: string): number {
|
|||||||
if (!shouldDelete && [".txt", ".html", ".htm", ".nfo"].includes(ext)) {
|
if (!shouldDelete && [".txt", ".html", ".htm", ".nfo"].includes(ext)) {
|
||||||
if (/[._\- ](links?|downloads?|urls?|dlc)([._\- ]|$)/i.test(name)) {
|
if (/[._\- ](links?|downloads?|urls?|dlc)([._\- ]|$)/i.test(name)) {
|
||||||
try {
|
try {
|
||||||
const stat = fs.statSync(full);
|
const stat = await fs.promises.stat(full);
|
||||||
if (stat.size <= MAX_LINK_ARTIFACT_BYTES) {
|
if (stat.size <= MAX_LINK_ARTIFACT_BYTES) {
|
||||||
const text = fs.readFileSync(full, "utf8");
|
const text = await fs.promises.readFile(full, "utf8");
|
||||||
shouldDelete = /https?:\/\//i.test(text);
|
shouldDelete = /https?:\/\//i.test(text);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@ -123,7 +129,7 @@ export function removeDownloadLinkArtifacts(extractDir: string): number {
|
|||||||
|
|
||||||
if (shouldDelete) {
|
if (shouldDelete) {
|
||||||
try {
|
try {
|
||||||
fs.rmSync(full, { force: true });
|
await fs.promises.rm(full, { force: true });
|
||||||
removed += 1;
|
removed += 1;
|
||||||
} catch {
|
} catch {
|
||||||
// ignore
|
// ignore
|
||||||
@ -134,8 +140,10 @@ export function removeDownloadLinkArtifacts(extractDir: string): number {
|
|||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function removeSampleArtifacts(extractDir: string): { files: number; dirs: number } {
|
export async function removeSampleArtifacts(extractDir: string): Promise<{ files: number; dirs: number }> {
|
||||||
if (!fs.existsSync(extractDir)) {
|
try {
|
||||||
|
await fs.promises.access(extractDir);
|
||||||
|
} catch {
|
||||||
return { files: 0, dirs: 0 };
|
return { files: 0, dirs: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -144,14 +152,14 @@ export function removeSampleArtifacts(extractDir: string): { files: number; dirs
|
|||||||
const sampleDirs: string[] = [];
|
const sampleDirs: string[] = [];
|
||||||
const stack = [extractDir];
|
const stack = [extractDir];
|
||||||
|
|
||||||
const countFilesRecursive = (rootDir: string): number => {
|
const countFilesRecursive = async (rootDir: string): Promise<number> => {
|
||||||
let count = 0;
|
let count = 0;
|
||||||
const dirs = [rootDir];
|
const dirs = [rootDir];
|
||||||
while (dirs.length > 0) {
|
while (dirs.length > 0) {
|
||||||
const current = dirs.pop() as string;
|
const current = dirs.pop() as string;
|
||||||
let entries: fs.Dirent[] = [];
|
let entries: fs.Dirent[] = [];
|
||||||
try {
|
try {
|
||||||
entries = fs.readdirSync(current, { withFileTypes: true });
|
entries = await fs.promises.readdir(current, { withFileTypes: true });
|
||||||
} catch {
|
} catch {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -159,7 +167,7 @@ export function removeSampleArtifacts(extractDir: string): { files: number; dirs
|
|||||||
const full = path.join(current, entry.name);
|
const full = path.join(current, entry.name);
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
try {
|
try {
|
||||||
const stat = fs.lstatSync(full);
|
const stat = await fs.promises.lstat(full);
|
||||||
if (stat.isSymbolicLink()) {
|
if (stat.isSymbolicLink()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -177,7 +185,9 @@ export function removeSampleArtifacts(extractDir: string): { files: number; dirs
|
|||||||
|
|
||||||
while (stack.length > 0) {
|
while (stack.length > 0) {
|
||||||
const current = stack.pop() as string;
|
const current = stack.pop() as string;
|
||||||
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
|
let entries: fs.Dirent[] = [];
|
||||||
|
try { entries = await fs.promises.readdir(current, { withFileTypes: true }); } catch { continue; }
|
||||||
|
for (const entry of entries) {
|
||||||
const full = path.join(current, entry.name);
|
const full = path.join(current, entry.name);
|
||||||
if (entry.isDirectory() || entry.isSymbolicLink()) {
|
if (entry.isDirectory() || entry.isSymbolicLink()) {
|
||||||
const base = entry.name.toLowerCase();
|
const base = entry.name.toLowerCase();
|
||||||
@ -200,7 +210,7 @@ export function removeSampleArtifacts(extractDir: string): { files: number; dirs
|
|||||||
|
|
||||||
if (isSampleVideo) {
|
if (isSampleVideo) {
|
||||||
try {
|
try {
|
||||||
fs.rmSync(full, { force: true });
|
await fs.promises.rm(full, { force: true });
|
||||||
removedFiles += 1;
|
removedFiles += 1;
|
||||||
} catch {
|
} catch {
|
||||||
// ignore
|
// ignore
|
||||||
@ -212,14 +222,14 @@ export function removeSampleArtifacts(extractDir: string): { files: number; dirs
|
|||||||
sampleDirs.sort((a, b) => b.length - a.length);
|
sampleDirs.sort((a, b) => b.length - a.length);
|
||||||
for (const dir of sampleDirs) {
|
for (const dir of sampleDirs) {
|
||||||
try {
|
try {
|
||||||
const stat = fs.lstatSync(dir);
|
const stat = await fs.promises.lstat(dir);
|
||||||
if (stat.isSymbolicLink()) {
|
if (stat.isSymbolicLink()) {
|
||||||
fs.rmSync(dir, { force: true });
|
await fs.promises.rm(dir, { force: true });
|
||||||
removedDirs += 1;
|
removedDirs += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const filesInDir = countFilesRecursive(dir);
|
const filesInDir = await countFilesRecursive(dir);
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
await fs.promises.rm(dir, { recursive: true, force: true });
|
||||||
removedFiles += filesInDir;
|
removedFiles += filesInDir;
|
||||||
removedDirs += 1;
|
removedDirs += 1;
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@ -3,11 +3,12 @@ import os from "node:os";
|
|||||||
import { AppSettings } from "../shared/types";
|
import { AppSettings } from "../shared/types";
|
||||||
import packageJson from "../../package.json";
|
import packageJson from "../../package.json";
|
||||||
|
|
||||||
export const APP_NAME = "Debrid Download Manager";
|
export const APP_NAME = "Multi Debrid Downloader";
|
||||||
export const APP_VERSION: string = packageJson.version;
|
export const APP_VERSION: string = packageJson.version;
|
||||||
export const API_BASE_URL = "https://api.real-debrid.com/rest/1.0";
|
export const API_BASE_URL = "https://api.real-debrid.com/rest/1.0";
|
||||||
|
|
||||||
export const DCRYPT_UPLOAD_URL = "https://dcrypt.it/decrypt/upload";
|
export const DCRYPT_UPLOAD_URL = "https://dcrypt.it/decrypt/upload";
|
||||||
|
export const DCRYPT_PASTE_URL = "https://dcrypt.it/decrypt/paste";
|
||||||
export const DLC_SERVICE_URL = "https://service.jdownloader.org/dlcrypt/service.php?srcType=dlc&destType=pylo&data={KEY}";
|
export const DLC_SERVICE_URL = "https://service.jdownloader.org/dlcrypt/service.php?srcType=dlc&destType=pylo&data={KEY}";
|
||||||
export const DLC_AES_KEY = Buffer.from("cb99b5cbc24db398", "utf8");
|
export const DLC_AES_KEY = Buffer.from("cb99b5cbc24db398", "utf8");
|
||||||
export const DLC_AES_IV = Buffer.from("9bc24cb995cb8db3", "utf8");
|
export const DLC_AES_IV = Buffer.from("9bc24cb995cb8db3", "utf8");
|
||||||
@ -15,20 +16,26 @@ export const DLC_AES_IV = Buffer.from("9bc24cb995cb8db3", "utf8");
|
|||||||
export const REQUEST_RETRIES = 3;
|
export const REQUEST_RETRIES = 3;
|
||||||
export const CHUNK_SIZE = 512 * 1024;
|
export const CHUNK_SIZE = 512 * 1024;
|
||||||
|
|
||||||
|
export const WRITE_BUFFER_SIZE = 512 * 1024; // 512 KB write buffer (JDownloader: 500 KB)
|
||||||
|
export const WRITE_FLUSH_TIMEOUT_MS = 2000; // 2s flush timeout
|
||||||
|
export const ALLOCATION_UNIT_SIZE = 4096; // 4 KB NTFS alignment
|
||||||
|
export const STREAM_HIGH_WATER_MARK = 512 * 1024; // 512 KB stream buffer — lower than before (2 MB) so backpressure triggers sooner when disk is slow
|
||||||
|
export const DISK_BUSY_THRESHOLD_MS = 300; // Show "Warte auf Festplatte" if writableLength > 0 for this long
|
||||||
|
|
||||||
export const SAMPLE_DIR_NAMES = new Set(["sample", "samples"]);
|
export const SAMPLE_DIR_NAMES = new Set(["sample", "samples"]);
|
||||||
export const SAMPLE_VIDEO_EXTENSIONS = new Set([".mkv", ".mp4", ".avi", ".mov", ".wmv", ".m4v", ".ts", ".m2ts", ".webm"]);
|
export const SAMPLE_VIDEO_EXTENSIONS = new Set([".mkv", ".mp4", ".avi", ".mov", ".wmv", ".m4v", ".ts", ".m2ts", ".webm"]);
|
||||||
export const LINK_ARTIFACT_EXTENSIONS = new Set([".url", ".webloc", ".dlc", ".rsdf", ".ccf"]);
|
export const LINK_ARTIFACT_EXTENSIONS = new Set([".url", ".webloc", ".dlc", ".rsdf", ".ccf"]);
|
||||||
export const SAMPLE_TOKEN_RE = /(^|[._\-\s])sample([._\-\s]|$)/i;
|
export const SAMPLE_TOKEN_RE = /(^|[._\-\s])sample([._\-\s]|$)/i;
|
||||||
|
|
||||||
export const ARCHIVE_TEMP_EXTENSIONS = new Set([".rar", ".zip", ".7z", ".tmp", ".part", ".tar", ".gz", ".bz2", ".xz"]);
|
export const ARCHIVE_TEMP_EXTENSIONS = new Set([".rar", ".zip", ".7z", ".tmp", ".part", ".tar", ".gz", ".bz2", ".xz", ".rev"]);
|
||||||
export const RAR_SPLIT_RE = /\.r\d{2,3}$/i;
|
export const RAR_SPLIT_RE = /\.r\d{2,3}$/i;
|
||||||
|
|
||||||
export const MAX_MANIFEST_FILE_BYTES = 5 * 1024 * 1024;
|
export const MAX_MANIFEST_FILE_BYTES = 5 * 1024 * 1024;
|
||||||
export const MAX_LINK_ARTIFACT_BYTES = 256 * 1024;
|
export const MAX_LINK_ARTIFACT_BYTES = 256 * 1024;
|
||||||
export const SPEED_WINDOW_SECONDS = 3;
|
export const SPEED_WINDOW_SECONDS = 1;
|
||||||
export const CLIPBOARD_POLL_INTERVAL_MS = 2000;
|
export const CLIPBOARD_POLL_INTERVAL_MS = 2000;
|
||||||
|
|
||||||
export const DEFAULT_UPDATE_REPO = "Sucukdeluxe/real-debrid-downloader";
|
export const DEFAULT_UPDATE_REPO = "Administrator/real-debrid-downloader";
|
||||||
|
|
||||||
export function defaultSettings(): AppSettings {
|
export function defaultSettings(): AppSettings {
|
||||||
const baseDir = path.join(os.homedir(), "Downloads", "RealDebrid");
|
const baseDir = path.join(os.homedir(), "Downloads", "RealDebrid");
|
||||||
@ -38,6 +45,9 @@ export function defaultSettings(): AppSettings {
|
|||||||
megaPassword: "",
|
megaPassword: "",
|
||||||
bestToken: "",
|
bestToken: "",
|
||||||
allDebridToken: "",
|
allDebridToken: "",
|
||||||
|
ddownloadLogin: "",
|
||||||
|
ddownloadPassword: "",
|
||||||
|
oneFichierApiKey: "",
|
||||||
archivePasswordList: "",
|
archivePasswordList: "",
|
||||||
rememberToken: true,
|
rememberToken: true,
|
||||||
providerPrimary: "realdebrid",
|
providerPrimary: "realdebrid",
|
||||||
@ -49,6 +59,8 @@ export function defaultSettings(): AppSettings {
|
|||||||
autoExtract: true,
|
autoExtract: true,
|
||||||
autoRename4sf4sj: false,
|
autoRename4sf4sj: false,
|
||||||
extractDir: path.join(baseDir, "_entpackt"),
|
extractDir: path.join(baseDir, "_entpackt"),
|
||||||
|
collectMkvToLibrary: false,
|
||||||
|
mkvLibraryDir: path.join(baseDir, "_mkv"),
|
||||||
createExtractSubfolder: true,
|
createExtractSubfolder: true,
|
||||||
hybridExtract: true,
|
hybridExtract: true,
|
||||||
cleanupMode: "none",
|
cleanupMode: "none",
|
||||||
@ -61,6 +73,8 @@ export function defaultSettings(): AppSettings {
|
|||||||
reconnectWaitSeconds: 45,
|
reconnectWaitSeconds: 45,
|
||||||
completedCleanupPolicy: "never",
|
completedCleanupPolicy: "never",
|
||||||
maxParallel: 4,
|
maxParallel: 4,
|
||||||
|
maxParallelExtract: 2,
|
||||||
|
retryLimit: 0,
|
||||||
speedLimitEnabled: false,
|
speedLimitEnabled: false,
|
||||||
speedLimitKbps: 0,
|
speedLimitKbps: 0,
|
||||||
speedLimitMode: "global",
|
speedLimitMode: "global",
|
||||||
@ -69,6 +83,13 @@ export function defaultSettings(): AppSettings {
|
|||||||
clipboardWatch: false,
|
clipboardWatch: false,
|
||||||
minimizeToTray: false,
|
minimizeToTray: false,
|
||||||
theme: "dark" as const,
|
theme: "dark" as const,
|
||||||
bandwidthSchedules: []
|
collapseNewPackages: true,
|
||||||
|
autoSkipExtracted: false,
|
||||||
|
confirmDeleteSelection: true,
|
||||||
|
totalDownloadedAllTime: 0,
|
||||||
|
bandwidthSchedules: [],
|
||||||
|
columnOrder: ["name", "size", "progress", "hoster", "account", "prio", "status", "speed"],
|
||||||
|
extractCpuPriority: "high",
|
||||||
|
autoExtractWhenStopped: true
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,12 +1,17 @@
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
import { DCRYPT_UPLOAD_URL, DLC_AES_IV, DLC_AES_KEY, DLC_SERVICE_URL } from "./constants";
|
import { DCRYPT_PASTE_URL, DCRYPT_UPLOAD_URL, DLC_AES_IV, DLC_AES_KEY, DLC_SERVICE_URL } from "./constants";
|
||||||
import { compactErrorText, inferPackageNameFromLinks, isHttpLink, sanitizeFilename, uniquePreserveOrder } from "./utils";
|
import { compactErrorText, inferPackageNameFromLinks, isHttpLink, sanitizeFilename, uniquePreserveOrder } from "./utils";
|
||||||
import { ParsedPackageInput } from "../shared/types";
|
import { ParsedPackageInput } from "../shared/types";
|
||||||
|
|
||||||
const MAX_DLC_FILE_BYTES = 8 * 1024 * 1024;
|
const MAX_DLC_FILE_BYTES = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
function isContainerSizeValidationError(error: unknown): boolean {
|
||||||
|
const text = compactErrorText(error);
|
||||||
|
return /zu groß/i.test(text) || /DLC-Datei ungültig oder zu groß/i.test(text);
|
||||||
|
}
|
||||||
|
|
||||||
function decodeDcryptPayload(responseText: string): unknown {
|
function decodeDcryptPayload(responseText: string): unknown {
|
||||||
let text = String(responseText || "").trim();
|
let text = String(responseText || "").trim();
|
||||||
const m = text.match(/<textarea[^>]*>([\s\S]*?)<\/textarea>/i);
|
const m = text.match(/<textarea[^>]*>([\s\S]*?)<\/textarea>/i);
|
||||||
@ -89,6 +94,36 @@ function parsePackagesFromDlcXml(xml: string): ParsedPackageInput[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const links: string[] = [];
|
const links: string[] = [];
|
||||||
|
const fileNames: string[] = [];
|
||||||
|
const fileRegex = /<file>([\s\S]*?)<\/file>/gi;
|
||||||
|
for (let fm = fileRegex.exec(packageBody); fm; fm = fileRegex.exec(packageBody)) {
|
||||||
|
const fileBody = fm[1] || "";
|
||||||
|
const urlMatch = fileBody.match(/<url>(.*?)<\/url>/i);
|
||||||
|
if (!urlMatch) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url = Buffer.from((urlMatch[1] || "").trim(), "base64").toString("utf8").trim();
|
||||||
|
if (!isHttpLink(url)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let fileName = "";
|
||||||
|
const fnMatch = fileBody.match(/<filename>(.*?)<\/filename>/i);
|
||||||
|
if (fnMatch?.[1]) {
|
||||||
|
try {
|
||||||
|
fileName = Buffer.from(fnMatch[1].trim(), "base64").toString("utf8").trim();
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
links.push(url);
|
||||||
|
fileNames.push(sanitizeFilename(fileName));
|
||||||
|
} catch {
|
||||||
|
// skip broken entries
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (links.length === 0) {
|
||||||
const urlRegex = /<url>(.*?)<\/url>/gi;
|
const urlRegex = /<url>(.*?)<\/url>/gi;
|
||||||
for (let um = urlRegex.exec(packageBody); um; um = urlRegex.exec(packageBody)) {
|
for (let um = urlRegex.exec(packageBody); um; um = urlRegex.exec(packageBody)) {
|
||||||
try {
|
try {
|
||||||
@ -100,13 +135,19 @@ function parsePackagesFromDlcXml(xml: string): ParsedPackageInput[] {
|
|||||||
// skip broken entries
|
// skip broken entries
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const uniqueLinks = uniquePreserveOrder(links);
|
const uniqueLinks = uniquePreserveOrder(links);
|
||||||
|
const hasFileNames = fileNames.some((fn) => fn.length > 0);
|
||||||
if (uniqueLinks.length > 0) {
|
if (uniqueLinks.length > 0) {
|
||||||
packages.push({
|
const pkg: ParsedPackageInput = {
|
||||||
name: sanitizeFilename(packageName || inferPackageNameFromLinks(uniqueLinks) || `Paket-${packages.length + 1}`),
|
name: sanitizeFilename(packageName || inferPackageNameFromLinks(uniqueLinks) || `Paket-${packages.length + 1}`),
|
||||||
links: uniqueLinks
|
links: uniqueLinks
|
||||||
});
|
};
|
||||||
|
if (hasFileNames) {
|
||||||
|
pkg.fileNames = fileNames;
|
||||||
|
}
|
||||||
|
packages.push(pkg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -123,7 +164,7 @@ async function decryptDlcLocal(filePath: string): Promise<ParsedPackageInput[]>
|
|||||||
const dlcData = content.slice(0, -88);
|
const dlcData = content.slice(0, -88);
|
||||||
|
|
||||||
const rcUrl = DLC_SERVICE_URL.replace("{KEY}", encodeURIComponent(dlcKey));
|
const rcUrl = DLC_SERVICE_URL.replace("{KEY}", encodeURIComponent(dlcKey));
|
||||||
const rcResponse = await fetch(rcUrl, { method: "GET" });
|
const rcResponse = await fetch(rcUrl, { method: "GET", signal: AbortSignal.timeout(30000) });
|
||||||
if (!rcResponse.ok) {
|
if (!rcResponse.ok) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@ -140,77 +181,139 @@ async function decryptDlcLocal(filePath: string): Promise<ParsedPackageInput[]>
|
|||||||
let decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
|
let decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
|
||||||
|
|
||||||
if (decrypted.length === 0) {
|
if (decrypted.length === 0) {
|
||||||
throw new Error("DLC-Entschlüsselung lieferte keine Daten");
|
return [];
|
||||||
}
|
}
|
||||||
const pad = decrypted[decrypted.length - 1];
|
const pad = decrypted[decrypted.length - 1];
|
||||||
if (pad <= 0 || pad > 16 || pad > decrypted.length) {
|
if (pad > 0 && pad <= 16 && pad <= decrypted.length) {
|
||||||
throw new Error("Ungültiges DLC-Padding");
|
let validPad = true;
|
||||||
}
|
|
||||||
for (let index = 1; index <= pad; index += 1) {
|
for (let index = 1; index <= pad; index += 1) {
|
||||||
if (decrypted[decrypted.length - index] !== pad) {
|
if (decrypted[decrypted.length - index] !== pad) {
|
||||||
throw new Error("Ungültiges DLC-Padding");
|
validPad = false;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (validPad) {
|
||||||
decrypted = decrypted.subarray(0, decrypted.length - pad);
|
decrypted = decrypted.subarray(0, decrypted.length - pad);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const xmlData = Buffer.from(decrypted.toString("utf8"), "base64").toString("utf8");
|
const xmlData = Buffer.from(decrypted.toString("utf8"), "base64").toString("utf8");
|
||||||
return parsePackagesFromDlcXml(xmlData);
|
return parsePackagesFromDlcXml(xmlData);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function decryptDlcViaDcrypt(filePath: string): Promise<ParsedPackageInput[]> {
|
function extractLinksFromResponse(text: string): string[] {
|
||||||
const fileName = path.basename(filePath);
|
const payload = decodeDcryptPayload(text);
|
||||||
const blob = new Blob([new Uint8Array(readDlcFileWithLimit(filePath))]);
|
let links = extractUrlsRecursive(payload);
|
||||||
|
if (links.length === 0) {
|
||||||
|
links = extractUrlsRecursive(text);
|
||||||
|
}
|
||||||
|
return uniquePreserveOrder(links.filter((l) => isHttpLink(l)));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function tryDcryptUpload(fileContent: Buffer, fileName: string): Promise<string[] | null> {
|
||||||
|
const blob = new Blob([new Uint8Array(fileContent)]);
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.set("dlcfile", blob, fileName);
|
form.set("dlcfile", blob, fileName);
|
||||||
|
|
||||||
const response = await fetch(DCRYPT_UPLOAD_URL, {
|
const response = await fetch(DCRYPT_UPLOAD_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: form
|
body: form,
|
||||||
|
signal: AbortSignal.timeout(30000)
|
||||||
});
|
});
|
||||||
|
if (response.status === 413) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(compactErrorText(text));
|
throw new Error(compactErrorText(text));
|
||||||
}
|
}
|
||||||
const payload = decodeDcryptPayload(text);
|
return extractLinksFromResponse(text);
|
||||||
let packages = extractPackagesFromPayload(payload);
|
}
|
||||||
if (packages.length === 1) {
|
|
||||||
const regrouped = groupLinksByName(packages[0].links);
|
async function tryDcryptPaste(fileContent: Buffer): Promise<string[] | null> {
|
||||||
if (regrouped.length > 1) {
|
const form = new FormData();
|
||||||
packages = regrouped;
|
form.set("content", fileContent.toString("ascii"));
|
||||||
|
|
||||||
|
const response = await fetch(DCRYPT_PASTE_URL, {
|
||||||
|
method: "POST",
|
||||||
|
body: form,
|
||||||
|
signal: AbortSignal.timeout(30000)
|
||||||
|
});
|
||||||
|
if (response.status === 413) {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
const text = await response.text();
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(compactErrorText(text));
|
||||||
}
|
}
|
||||||
if (packages.length === 0) {
|
return extractLinksFromResponse(text);
|
||||||
packages = groupLinksByName(extractUrlsRecursive(text));
|
}
|
||||||
|
|
||||||
|
async function decryptDlcViaDcrypt(filePath: string): Promise<ParsedPackageInput[]> {
|
||||||
|
const fileContent = readDlcFileWithLimit(filePath);
|
||||||
|
const fileName = path.basename(filePath);
|
||||||
|
const packageName = sanitizeFilename(path.basename(filePath, ".dlc")) || "Paket";
|
||||||
|
|
||||||
|
let links = await tryDcryptUpload(fileContent, fileName);
|
||||||
|
if (links === null) {
|
||||||
|
links = await tryDcryptPaste(fileContent);
|
||||||
}
|
}
|
||||||
return packages;
|
if (links === null) {
|
||||||
|
throw new Error("DLC-Datei zu groß für dcrypt.it");
|
||||||
|
}
|
||||||
|
if (links.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return [{ name: packageName, links }];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function importDlcContainers(filePaths: string[]): Promise<ParsedPackageInput[]> {
|
export async function importDlcContainers(filePaths: string[]): Promise<ParsedPackageInput[]> {
|
||||||
const out: ParsedPackageInput[] = [];
|
const out: ParsedPackageInput[] = [];
|
||||||
|
const failures: string[] = [];
|
||||||
|
let sawDlc = false;
|
||||||
for (const filePath of filePaths) {
|
for (const filePath of filePaths) {
|
||||||
if (path.extname(filePath).toLowerCase() !== ".dlc") {
|
if (path.extname(filePath).toLowerCase() !== ".dlc") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
sawDlc = true;
|
||||||
let packages: ParsedPackageInput[] = [];
|
let packages: ParsedPackageInput[] = [];
|
||||||
|
let fileFailed = false;
|
||||||
|
let fileFailureReasons: string[] = [];
|
||||||
try {
|
try {
|
||||||
packages = await decryptDlcLocal(filePath);
|
packages = await decryptDlcLocal(filePath);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (/zu groß|ungültig/i.test(compactErrorText(error))) {
|
if (isContainerSizeValidationError(error)) {
|
||||||
throw error;
|
failures.push(`${path.basename(filePath)}: ${compactErrorText(error)}`);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
fileFailed = true;
|
||||||
|
fileFailureReasons.push(`lokal: ${compactErrorText(error)}`);
|
||||||
packages = [];
|
packages = [];
|
||||||
}
|
}
|
||||||
if (packages.length === 0) {
|
if (packages.length === 0) {
|
||||||
try {
|
try {
|
||||||
packages = await decryptDlcViaDcrypt(filePath);
|
packages = await decryptDlcViaDcrypt(filePath);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (/zu groß|ungültig/i.test(compactErrorText(error))) {
|
if (isContainerSizeValidationError(error)) {
|
||||||
throw error;
|
failures.push(`${path.basename(filePath)}: ${compactErrorText(error)}`);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
fileFailed = true;
|
||||||
|
fileFailureReasons.push(`dcrypt: ${compactErrorText(error)}`);
|
||||||
packages = [];
|
packages = [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (packages.length === 0 && fileFailed) {
|
||||||
|
failures.push(`${path.basename(filePath)}: ${fileFailureReasons.join("; ")}`);
|
||||||
|
}
|
||||||
out.push(...packages);
|
out.push(...packages);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (out.length === 0 && sawDlc && failures.length > 0) {
|
||||||
|
const details = failures.slice(0, 2).join(" | ");
|
||||||
|
const suffix = failures.length > 2 ? ` (+${failures.length - 2} weitere)` : "";
|
||||||
|
throw new Error(`DLC konnte nicht importiert werden: ${details}${suffix}`);
|
||||||
|
}
|
||||||
|
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
279
src/main/debug-server.ts
Normal file
279
src/main/debug-server.ts
Normal file
@ -0,0 +1,279 @@
|
|||||||
|
import http from "node:http";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { logger, getLogFilePath } from "./logger";
|
||||||
|
import type { DownloadManager } from "./download-manager";
|
||||||
|
|
||||||
|
const DEFAULT_PORT = 9868;
|
||||||
|
const MAX_LOG_LINES = 10000;
|
||||||
|
|
||||||
|
let server: http.Server | null = null;
|
||||||
|
let manager: DownloadManager | null = null;
|
||||||
|
let authToken = "";
|
||||||
|
|
||||||
|
function loadToken(baseDir: string): string {
|
||||||
|
const tokenPath = path.join(baseDir, "debug_token.txt");
|
||||||
|
try {
|
||||||
|
return fs.readFileSync(tokenPath, "utf8").trim();
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getPort(baseDir: string): number {
|
||||||
|
const portPath = path.join(baseDir, "debug_port.txt");
|
||||||
|
try {
|
||||||
|
const n = Number(fs.readFileSync(portPath, "utf8").trim());
|
||||||
|
if (Number.isFinite(n) && n >= 1024 && n <= 65535) {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return DEFAULT_PORT;
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkAuth(req: http.IncomingMessage): boolean {
|
||||||
|
if (!authToken) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const header = req.headers.authorization || "";
|
||||||
|
if (header === `Bearer ${authToken}`) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const url = new URL(req.url || "/", "http://localhost");
|
||||||
|
return url.searchParams.get("token") === authToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonResponse(res: http.ServerResponse, status: number, data: unknown): void {
|
||||||
|
const body = JSON.stringify(data, null, 2);
|
||||||
|
res.writeHead(status, {
|
||||||
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
|
"Access-Control-Allow-Origin": "*",
|
||||||
|
"Cache-Control": "no-cache"
|
||||||
|
});
|
||||||
|
res.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readLogTail(lines: number): string[] {
|
||||||
|
const logPath = getLogFilePath();
|
||||||
|
try {
|
||||||
|
const content = fs.readFileSync(logPath, "utf8");
|
||||||
|
const allLines = content.split("\n").filter((l) => l.trim().length > 0);
|
||||||
|
return allLines.slice(-Math.min(lines, MAX_LOG_LINES));
|
||||||
|
} catch {
|
||||||
|
return ["(Log-Datei nicht lesbar)"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleRequest(req: http.IncomingMessage, res: http.ServerResponse): void {
|
||||||
|
if (req.method === "OPTIONS") {
|
||||||
|
res.writeHead(204, {
|
||||||
|
"Access-Control-Allow-Origin": "*",
|
||||||
|
"Access-Control-Allow-Headers": "Authorization"
|
||||||
|
});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!checkAuth(req)) {
|
||||||
|
jsonResponse(res, 401, { error: "Unauthorized" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL(req.url || "/", "http://localhost");
|
||||||
|
const pathname = url.pathname;
|
||||||
|
|
||||||
|
if (pathname === "/health") {
|
||||||
|
jsonResponse(res, 200, {
|
||||||
|
status: "ok",
|
||||||
|
uptime: Math.floor(process.uptime()),
|
||||||
|
memoryMB: Math.round(process.memoryUsage().rss / 1024 / 1024)
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathname === "/log") {
|
||||||
|
const count = Math.min(Number(url.searchParams.get("lines") || "100"), MAX_LOG_LINES);
|
||||||
|
const grep = url.searchParams.get("grep") || "";
|
||||||
|
let lines = readLogTail(count);
|
||||||
|
if (grep) {
|
||||||
|
const pattern = grep.toLowerCase();
|
||||||
|
lines = lines.filter((l) => l.toLowerCase().includes(pattern));
|
||||||
|
}
|
||||||
|
jsonResponse(res, 200, { lines, count: lines.length });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathname === "/status") {
|
||||||
|
if (!manager) {
|
||||||
|
jsonResponse(res, 503, { error: "Manager not initialized" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const snapshot = manager.getSnapshot();
|
||||||
|
const items = Object.values(snapshot.session.items);
|
||||||
|
const packages = Object.values(snapshot.session.packages);
|
||||||
|
|
||||||
|
const byStatus: Record<string, number> = {};
|
||||||
|
for (const item of items) {
|
||||||
|
byStatus[item.status] = (byStatus[item.status] || 0) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeItems = items
|
||||||
|
.filter((i) => i.status === "downloading" || i.status === "validating")
|
||||||
|
.map((i) => ({
|
||||||
|
id: i.id,
|
||||||
|
fileName: i.fileName,
|
||||||
|
status: i.status,
|
||||||
|
fullStatus: i.fullStatus,
|
||||||
|
provider: i.provider,
|
||||||
|
progress: i.progressPercent,
|
||||||
|
speedMBs: +(i.speedBps / 1024 / 1024).toFixed(2),
|
||||||
|
downloadedMB: +(i.downloadedBytes / 1024 / 1024).toFixed(1),
|
||||||
|
totalMB: i.totalBytes ? +(i.totalBytes / 1024 / 1024).toFixed(1) : null,
|
||||||
|
retries: i.retries,
|
||||||
|
lastError: i.lastError
|
||||||
|
}));
|
||||||
|
|
||||||
|
const failedItems = items
|
||||||
|
.filter((i) => i.status === "failed")
|
||||||
|
.map((i) => ({
|
||||||
|
fileName: i.fileName,
|
||||||
|
lastError: i.lastError,
|
||||||
|
retries: i.retries,
|
||||||
|
provider: i.provider
|
||||||
|
}));
|
||||||
|
|
||||||
|
jsonResponse(res, 200, {
|
||||||
|
running: snapshot.session.running,
|
||||||
|
paused: snapshot.session.paused,
|
||||||
|
speed: snapshot.speedText,
|
||||||
|
eta: snapshot.etaText,
|
||||||
|
itemCounts: byStatus,
|
||||||
|
totalItems: items.length,
|
||||||
|
packages: packages.map((p) => ({
|
||||||
|
name: p.name,
|
||||||
|
status: p.status,
|
||||||
|
items: p.itemIds.length
|
||||||
|
})),
|
||||||
|
activeItems,
|
||||||
|
failedItems: failedItems.length > 0 ? failedItems : undefined
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathname === "/items") {
|
||||||
|
if (!manager) {
|
||||||
|
jsonResponse(res, 503, { error: "Manager not initialized" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const snapshot = manager.getSnapshot();
|
||||||
|
const filter = url.searchParams.get("status");
|
||||||
|
const pkg = url.searchParams.get("package");
|
||||||
|
let items = Object.values(snapshot.session.items);
|
||||||
|
if (filter) {
|
||||||
|
items = items.filter((i) => i.status === filter);
|
||||||
|
}
|
||||||
|
if (pkg) {
|
||||||
|
const pkgLower = pkg.toLowerCase();
|
||||||
|
const matchedPkg = Object.values(snapshot.session.packages)
|
||||||
|
.find((p) => p.name.toLowerCase().includes(pkgLower));
|
||||||
|
if (matchedPkg) {
|
||||||
|
const ids = new Set(matchedPkg.itemIds);
|
||||||
|
items = items.filter((i) => ids.has(i.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
jsonResponse(res, 200, {
|
||||||
|
count: items.length,
|
||||||
|
items: items.map((i) => ({
|
||||||
|
fileName: i.fileName,
|
||||||
|
status: i.status,
|
||||||
|
fullStatus: i.fullStatus,
|
||||||
|
provider: i.provider,
|
||||||
|
progress: i.progressPercent,
|
||||||
|
speedMBs: +(i.speedBps / 1024 / 1024).toFixed(2),
|
||||||
|
downloadedMB: +(i.downloadedBytes / 1024 / 1024).toFixed(1),
|
||||||
|
totalMB: i.totalBytes ? +(i.totalBytes / 1024 / 1024).toFixed(1) : null,
|
||||||
|
retries: i.retries,
|
||||||
|
lastError: i.lastError
|
||||||
|
}))
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathname === "/session") {
|
||||||
|
if (!manager) {
|
||||||
|
jsonResponse(res, 503, { error: "Manager not initialized" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const snapshot = manager.getSnapshot();
|
||||||
|
const pkg = url.searchParams.get("package");
|
||||||
|
if (pkg) {
|
||||||
|
const pkgLower = pkg.toLowerCase();
|
||||||
|
const matchedPkg = Object.values(snapshot.session.packages)
|
||||||
|
.find((p) => p.name.toLowerCase().includes(pkgLower));
|
||||||
|
if (matchedPkg) {
|
||||||
|
const ids = new Set(matchedPkg.itemIds);
|
||||||
|
const pkgItems = Object.values(snapshot.session.items)
|
||||||
|
.filter((i) => ids.has(i.id));
|
||||||
|
jsonResponse(res, 200, {
|
||||||
|
package: matchedPkg,
|
||||||
|
items: pkgItems
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
jsonResponse(res, 200, {
|
||||||
|
running: snapshot.session.running,
|
||||||
|
paused: snapshot.session.paused,
|
||||||
|
packageCount: Object.keys(snapshot.session.packages).length,
|
||||||
|
itemCount: Object.keys(snapshot.session.items).length,
|
||||||
|
packages: Object.values(snapshot.session.packages).map((p) => ({
|
||||||
|
id: p.id,
|
||||||
|
name: p.name,
|
||||||
|
status: p.status,
|
||||||
|
items: p.itemIds.length
|
||||||
|
}))
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonResponse(res, 404, {
|
||||||
|
error: "Not found",
|
||||||
|
endpoints: [
|
||||||
|
"GET /health",
|
||||||
|
"GET /log?lines=100&grep=keyword",
|
||||||
|
"GET /status",
|
||||||
|
"GET /items?status=downloading&package=Bloodline",
|
||||||
|
"GET /session?package=Criminal"
|
||||||
|
]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startDebugServer(mgr: DownloadManager, baseDir: string): void {
|
||||||
|
authToken = loadToken(baseDir);
|
||||||
|
if (!authToken) {
|
||||||
|
logger.info("Debug-Server: Kein Token in debug_token.txt, Server wird nicht gestartet");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
manager = mgr;
|
||||||
|
const port = getPort(baseDir);
|
||||||
|
|
||||||
|
server = http.createServer(handleRequest);
|
||||||
|
server.listen(port, "127.0.0.1", () => {
|
||||||
|
logger.info(`Debug-Server gestartet auf Port ${port}`);
|
||||||
|
});
|
||||||
|
server.on("error", (err) => {
|
||||||
|
logger.warn(`Debug-Server Fehler: ${String(err)}`);
|
||||||
|
server = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stopDebugServer(): void {
|
||||||
|
if (server) {
|
||||||
|
server.close();
|
||||||
|
server = null;
|
||||||
|
logger.info("Debug-Server gestoppt");
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -4,6 +4,17 @@ import crypto from "node:crypto";
|
|||||||
import { ParsedHashEntry } from "../shared/types";
|
import { ParsedHashEntry } from "../shared/types";
|
||||||
import { MAX_MANIFEST_FILE_BYTES } from "./constants";
|
import { MAX_MANIFEST_FILE_BYTES } from "./constants";
|
||||||
|
|
||||||
|
const manifestCache = new Map<string, { at: number; entries: Map<string, ParsedHashEntry> }>();
|
||||||
|
const MANIFEST_CACHE_TTL_MS = 15000;
|
||||||
|
|
||||||
|
function normalizeManifestKey(value: string): string {
|
||||||
|
return String(value || "")
|
||||||
|
.replace(/\\/g, "/")
|
||||||
|
.replace(/^\.\//, "")
|
||||||
|
.trim()
|
||||||
|
.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
export function parseHashLine(line: string): ParsedHashEntry | null {
|
export function parseHashLine(line: string): ParsedHashEntry | null {
|
||||||
const text = String(line || "").trim();
|
const text = String(line || "").trim();
|
||||||
if (!text || text.startsWith(";")) {
|
if (!text || text.startsWith(";")) {
|
||||||
@ -30,6 +41,12 @@ export function parseHashLine(line: string): ParsedHashEntry | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function readHashManifest(packageDir: string): Map<string, ParsedHashEntry> {
|
export function readHashManifest(packageDir: string): Map<string, ParsedHashEntry> {
|
||||||
|
const cacheKey = path.resolve(packageDir);
|
||||||
|
const cached = manifestCache.get(cacheKey);
|
||||||
|
if (cached && Date.now() - cached.at <= MANIFEST_CACHE_TTL_MS) {
|
||||||
|
return new Map(cached.entries);
|
||||||
|
}
|
||||||
|
|
||||||
const map = new Map<string, ParsedHashEntry>();
|
const map = new Map<string, ParsedHashEntry>();
|
||||||
const patterns: Array<[string, "crc32" | "md5" | "sha1"]> = [
|
const patterns: Array<[string, "crc32" | "md5" | "sha1"]> = [
|
||||||
[".sfv", "crc32"],
|
[".sfv", "crc32"],
|
||||||
@ -80,24 +97,28 @@ export function readHashManifest(packageDir: string): Map<string, ParsedHashEntr
|
|||||||
...parsed,
|
...parsed,
|
||||||
algorithm: hit[1]
|
algorithm: hit[1]
|
||||||
};
|
};
|
||||||
const key = parsed.fileName.toLowerCase();
|
const key = normalizeManifestKey(parsed.fileName);
|
||||||
if (map.has(key)) {
|
if (map.has(key)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
map.set(key, normalized);
|
map.set(key, normalized);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
manifestCache.set(cacheKey, { at: Date.now(), entries: new Map(map) });
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const crcTable = new Int32Array(256);
|
||||||
|
for (let i = 0; i < 256; i++) {
|
||||||
|
let c = i;
|
||||||
|
for (let j = 0; j < 8; j++) c = c & 1 ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
|
||||||
|
crcTable[i] = c;
|
||||||
|
}
|
||||||
|
|
||||||
function crc32Buffer(data: Buffer, seed = 0): number {
|
function crc32Buffer(data: Buffer, seed = 0): number {
|
||||||
let crc = seed ^ -1;
|
let crc = seed ^ -1;
|
||||||
for (let i = 0; i < data.length; i += 1) {
|
for (let i = 0; i < data.length; i++) {
|
||||||
let c = (crc ^ data[i]) & 0xff;
|
crc = (crc >>> 8) ^ crcTable[(crc ^ data[i]) & 0xff];
|
||||||
for (let j = 0; j < 8; j += 1) {
|
|
||||||
c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
|
|
||||||
}
|
|
||||||
crc = (crc >>> 8) ^ c;
|
|
||||||
}
|
}
|
||||||
return crc ^ -1;
|
return crc ^ -1;
|
||||||
}
|
}
|
||||||
@ -105,15 +126,12 @@ function crc32Buffer(data: Buffer, seed = 0): number {
|
|||||||
async function hashFile(filePath: string, algorithm: "crc32" | "md5" | "sha1"): Promise<string> {
|
async function hashFile(filePath: string, algorithm: "crc32" | "md5" | "sha1"): Promise<string> {
|
||||||
if (algorithm === "crc32") {
|
if (algorithm === "crc32") {
|
||||||
const stream = fs.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
|
const stream = fs.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
|
||||||
return await new Promise<string>((resolve, reject) => {
|
|
||||||
let crc = 0;
|
let crc = 0;
|
||||||
stream.on("data", (chunk: string | Buffer) => {
|
for await (const chunk of stream) {
|
||||||
const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
crc = crc32Buffer(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk), crc);
|
||||||
crc = crc32Buffer(buffer, crc);
|
await new Promise(r => setImmediate(r));
|
||||||
});
|
}
|
||||||
stream.on("error", reject);
|
return (crc >>> 0).toString(16).padStart(8, "0").toLowerCase();
|
||||||
stream.on("end", () => resolve(((crc >>> 0).toString(16)).padStart(8, "0").toLowerCase()));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const hash = crypto.createHash(algorithm);
|
const hash = crypto.createHash(algorithm);
|
||||||
@ -130,8 +148,9 @@ export async function validateFileAgainstManifest(filePath: string, packageDir:
|
|||||||
if (manifest.size === 0) {
|
if (manifest.size === 0) {
|
||||||
return { ok: true, message: "Kein Hash verfügbar" };
|
return { ok: true, message: "Kein Hash verfügbar" };
|
||||||
}
|
}
|
||||||
const key = path.basename(filePath).toLowerCase();
|
const keyByBaseName = normalizeManifestKey(path.basename(filePath));
|
||||||
const entry = manifest.get(key);
|
const keyByRelativePath = normalizeManifestKey(path.relative(packageDir, filePath));
|
||||||
|
const entry = manifest.get(keyByRelativePath) || manifest.get(keyByBaseName);
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
return { ok: true, message: "Kein Hash für Datei" };
|
return { ok: true, message: "Kein Hash für Datei" };
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,7 +6,9 @@ export function mergePackageInputs(packages: ParsedPackageInput[]): ParsedPackag
|
|||||||
for (const pkg of packages) {
|
for (const pkg of packages) {
|
||||||
const name = sanitizeFilename(pkg.name || inferPackageNameFromLinks(pkg.links));
|
const name = sanitizeFilename(pkg.name || inferPackageNameFromLinks(pkg.links));
|
||||||
const list = grouped.get(name) ?? [];
|
const list = grouped.get(name) ?? [];
|
||||||
list.push(...pkg.links);
|
for (const link of pkg.links) {
|
||||||
|
list.push(link);
|
||||||
|
}
|
||||||
grouped.set(name, list);
|
grouped.set(name, list);
|
||||||
}
|
}
|
||||||
return Array.from(grouped.entries()).map(([name, links]) => ({
|
return Array.from(grouped.entries()).map(([name, links]) => ({
|
||||||
|
|||||||
@ -6,7 +6,10 @@ let fallbackLogFilePath: string | null = null;
|
|||||||
const LOG_FLUSH_INTERVAL_MS = 120;
|
const LOG_FLUSH_INTERVAL_MS = 120;
|
||||||
const LOG_BUFFER_LIMIT_CHARS = 1_000_000;
|
const LOG_BUFFER_LIMIT_CHARS = 1_000_000;
|
||||||
const LOG_MAX_FILE_BYTES = 10 * 1024 * 1024;
|
const LOG_MAX_FILE_BYTES = 10 * 1024 * 1024;
|
||||||
let lastRotateCheckAt = 0;
|
const rotateCheckAtByFile = new Map<string, number>();
|
||||||
|
|
||||||
|
type LogListener = (line: string) => void;
|
||||||
|
let logListener: LogListener | null = null;
|
||||||
|
|
||||||
let pendingLines: string[] = [];
|
let pendingLines: string[] = [];
|
||||||
let pendingChars = 0;
|
let pendingChars = 0;
|
||||||
@ -14,6 +17,10 @@ let flushTimer: NodeJS.Timeout | null = null;
|
|||||||
let flushInFlight = false;
|
let flushInFlight = false;
|
||||||
let exitHookAttached = false;
|
let exitHookAttached = false;
|
||||||
|
|
||||||
|
export function setLogListener(listener: LogListener | null): void {
|
||||||
|
logListener = listener;
|
||||||
|
}
|
||||||
|
|
||||||
export function configureLogger(baseDir: string): void {
|
export function configureLogger(baseDir: string): void {
|
||||||
logFilePath = path.join(baseDir, "rd_downloader.log");
|
logFilePath = path.join(baseDir, "rd_downloader.log");
|
||||||
const cwdLogPath = path.resolve(process.cwd(), "rd_downloader.log");
|
const cwdLogPath = path.resolve(process.cwd(), "rd_downloader.log");
|
||||||
@ -97,10 +104,11 @@ function scheduleFlush(immediate = false): void {
|
|||||||
function rotateIfNeeded(filePath: string): void {
|
function rotateIfNeeded(filePath: string): void {
|
||||||
try {
|
try {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
const lastRotateCheckAt = rotateCheckAtByFile.get(filePath) || 0;
|
||||||
if (now - lastRotateCheckAt < 60_000) {
|
if (now - lastRotateCheckAt < 60_000) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
lastRotateCheckAt = now;
|
rotateCheckAtByFile.set(filePath, now);
|
||||||
const stat = fs.statSync(filePath);
|
const stat = fs.statSync(filePath);
|
||||||
if (stat.size < LOG_MAX_FILE_BYTES) {
|
if (stat.size < LOG_MAX_FILE_BYTES) {
|
||||||
return;
|
return;
|
||||||
@ -117,31 +125,57 @@ function rotateIfNeeded(filePath: string): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function rotateIfNeededAsync(filePath: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const now = Date.now();
|
||||||
|
const lastRotateCheckAt = rotateCheckAtByFile.get(filePath) || 0;
|
||||||
|
if (now - lastRotateCheckAt < 60_000) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rotateCheckAtByFile.set(filePath, now);
|
||||||
|
const stat = await fs.promises.stat(filePath);
|
||||||
|
if (stat.size < LOG_MAX_FILE_BYTES) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const backup = `${filePath}.old`;
|
||||||
|
await fs.promises.rm(backup, { force: true }).catch(() => {});
|
||||||
|
await fs.promises.rename(filePath, backup);
|
||||||
|
} catch {
|
||||||
|
// ignore - file may not exist yet
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function flushAsync(): Promise<void> {
|
async function flushAsync(): Promise<void> {
|
||||||
if (flushInFlight || pendingLines.length === 0) {
|
if (flushInFlight || pendingLines.length === 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
flushInFlight = true;
|
flushInFlight = true;
|
||||||
const chunk = pendingLines.join("");
|
const linesSnapshot = pendingLines.slice();
|
||||||
pendingLines = [];
|
const chunk = linesSnapshot.join("");
|
||||||
pendingChars = 0;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
rotateIfNeeded(logFilePath);
|
await rotateIfNeededAsync(logFilePath);
|
||||||
const primary = await appendChunk(logFilePath, chunk);
|
const primary = await appendChunk(logFilePath, chunk);
|
||||||
|
let wroteAny = primary.ok;
|
||||||
if (fallbackLogFilePath) {
|
if (fallbackLogFilePath) {
|
||||||
|
await rotateIfNeededAsync(fallbackLogFilePath);
|
||||||
const fallback = await appendChunk(fallbackLogFilePath, chunk);
|
const fallback = await appendChunk(fallbackLogFilePath, chunk);
|
||||||
|
wroteAny = wroteAny || fallback.ok;
|
||||||
if (!primary.ok && !fallback.ok) {
|
if (!primary.ok && !fallback.ok) {
|
||||||
writeStderr(`LOGGER write failed (primary+fallback): ${primary.errorText} | ${fallback.errorText}\n`);
|
writeStderr(`LOGGER write failed (primary+fallback): ${primary.errorText} | ${fallback.errorText}\n`);
|
||||||
}
|
}
|
||||||
} else if (!primary.ok) {
|
} else if (!primary.ok) {
|
||||||
writeStderr(`LOGGER write failed: ${primary.errorText}\n`);
|
writeStderr(`LOGGER write failed: ${primary.errorText}\n`);
|
||||||
}
|
}
|
||||||
|
if (wroteAny) {
|
||||||
|
pendingLines = pendingLines.slice(linesSnapshot.length);
|
||||||
|
pendingChars = Math.max(0, pendingChars - chunk.length);
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
flushInFlight = false;
|
flushInFlight = false;
|
||||||
if (pendingLines.length > 0) {
|
if (pendingLines.length > 0) {
|
||||||
scheduleFlush(true);
|
scheduleFlush();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -161,6 +195,10 @@ function write(level: "INFO" | "WARN" | "ERROR", message: string): void {
|
|||||||
pendingLines.push(line);
|
pendingLines.push(line);
|
||||||
pendingChars += line.length;
|
pendingChars += line.length;
|
||||||
|
|
||||||
|
if (logListener) {
|
||||||
|
try { logListener(line); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
while (pendingChars > LOG_BUFFER_LIMIT_CHARS && pendingLines.length > 1) {
|
while (pendingChars > LOG_BUFFER_LIMIT_CHARS && pendingLines.length > 1) {
|
||||||
const removed = pendingLines.shift();
|
const removed = pendingLines.shift();
|
||||||
if (!removed) {
|
if (!removed) {
|
||||||
|
|||||||
203
src/main/main.ts
203
src/main/main.ts
@ -1,11 +1,13 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { app, BrowserWindow, clipboard, dialog, ipcMain, IpcMainInvokeEvent, Menu, shell, Tray } from "electron";
|
import { app, BrowserWindow, clipboard, dialog, ipcMain, IpcMainInvokeEvent, Menu, shell, Tray } from "electron";
|
||||||
import { AddLinksPayload, AppSettings } from "../shared/types";
|
import { AddLinksPayload, AppSettings, UpdateInstallProgress } from "../shared/types";
|
||||||
import { AppController } from "./app-controller";
|
import { AppController } from "./app-controller";
|
||||||
import { IPC_CHANNELS } from "../shared/ipc";
|
import { IPC_CHANNELS } from "../shared/ipc";
|
||||||
import { logger } from "./logger";
|
import { getLogFilePath, logger } from "./logger";
|
||||||
import { APP_NAME } from "./constants";
|
import { APP_NAME } from "./constants";
|
||||||
import { extractHttpLinksFromText } from "./utils";
|
import { extractHttpLinksFromText } from "./utils";
|
||||||
|
import { cleanupStaleSubstDrives, shutdownDaemon } from "./extractor";
|
||||||
|
|
||||||
/* ── IPC validation helpers ────────────────────────────────────── */
|
/* ── IPC validation helpers ────────────────────────────────────── */
|
||||||
function validateString(value: unknown, name: string): string {
|
function validateString(value: unknown, name: string): string {
|
||||||
@ -34,7 +36,8 @@ function validateStringArray(value: unknown, name: string): string[] {
|
|||||||
/* ── Single Instance Lock ───────────────────────────────────────── */
|
/* ── Single Instance Lock ───────────────────────────────────────── */
|
||||||
const gotLock = app.requestSingleInstanceLock();
|
const gotLock = app.requestSingleInstanceLock();
|
||||||
if (!gotLock) {
|
if (!gotLock) {
|
||||||
app.quit();
|
app.exit(0);
|
||||||
|
process.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Unhandled error protection ─────────────────────────────────── */
|
/* ── Unhandled error protection ─────────────────────────────────── */
|
||||||
@ -48,6 +51,7 @@ process.on("unhandledRejection", (reason) => {
|
|||||||
let mainWindow: BrowserWindow | null = null;
|
let mainWindow: BrowserWindow | null = null;
|
||||||
let tray: Tray | null = null;
|
let tray: Tray | null = null;
|
||||||
let clipboardTimer: ReturnType<typeof setInterval> | null = null;
|
let clipboardTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let updateQuitTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
let lastClipboardText = "";
|
let lastClipboardText = "";
|
||||||
const controller = new AppController();
|
const controller = new AppController();
|
||||||
const CLIPBOARD_MAX_TEXT_CHARS = 50_000;
|
const CLIPBOARD_MAX_TEXT_CHARS = 50_000;
|
||||||
@ -63,7 +67,8 @@ function createWindow(): BrowserWindow {
|
|||||||
minWidth: 1120,
|
minWidth: 1120,
|
||||||
minHeight: 760,
|
minHeight: 760,
|
||||||
backgroundColor: "#070b14",
|
backgroundColor: "#070b14",
|
||||||
title: `${APP_NAME} v${controller.getVersion()}`,
|
title: `${APP_NAME} - v${controller.getVersion()}`,
|
||||||
|
icon: path.join(app.getAppPath(), "assets", "app_icon.ico"),
|
||||||
webPreferences: {
|
webPreferences: {
|
||||||
contextIsolation: true,
|
contextIsolation: true,
|
||||||
nodeIntegration: false,
|
nodeIntegration: false,
|
||||||
@ -77,13 +82,16 @@ function createWindow(): BrowserWindow {
|
|||||||
responseHeaders: {
|
responseHeaders: {
|
||||||
...details.responseHeaders,
|
...details.responseHeaders,
|
||||||
"Content-Security-Policy": [
|
"Content-Security-Policy": [
|
||||||
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' https://api.real-debrid.com https://api.github.com https://bestdebrid.com https://api.alldebrid.com https://www.mega-debrid.eu"
|
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' https://api.real-debrid.com https://codeberg.org https://bestdebrid.com https://api.alldebrid.com https://www.mega-debrid.eu https://git.24-music.de https://ddownload.com https://ddl.to"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
window.setMenuBarVisibility(false);
|
||||||
|
window.setAutoHideMenuBar(true);
|
||||||
|
|
||||||
if (isDevMode()) {
|
if (isDevMode()) {
|
||||||
void window.loadURL("http://localhost:5173");
|
void window.loadURL("http://localhost:5173");
|
||||||
} else {
|
} else {
|
||||||
@ -93,6 +101,22 @@ function createWindow(): BrowserWindow {
|
|||||||
return window;
|
return window;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function bindMainWindowLifecycle(window: BrowserWindow): void {
|
||||||
|
window.on("close", (event) => {
|
||||||
|
const settings = controller.getSettings();
|
||||||
|
if (settings.minimizeToTray && tray) {
|
||||||
|
event.preventDefault();
|
||||||
|
window.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.on("closed", () => {
|
||||||
|
if (mainWindow === window) {
|
||||||
|
mainWindow = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function createTray(): void {
|
function createTray(): void {
|
||||||
if (tray) {
|
if (tray) {
|
||||||
return;
|
return;
|
||||||
@ -107,7 +131,7 @@ function createTray(): void {
|
|||||||
const contextMenu = Menu.buildFromTemplate([
|
const contextMenu = Menu.buildFromTemplate([
|
||||||
{ label: "Anzeigen", click: () => { mainWindow?.show(); mainWindow?.focus(); } },
|
{ label: "Anzeigen", click: () => { mainWindow?.show(); mainWindow?.focus(); } },
|
||||||
{ type: "separator" },
|
{ type: "separator" },
|
||||||
{ label: "Start", click: () => { controller.start(); } },
|
{ label: "Start", click: () => { void controller.start().catch((err) => logger.warn(`Tray Start Fehler: ${String(err)}`)); } },
|
||||||
{ label: "Stop", click: () => { controller.stop(); } },
|
{ label: "Stop", click: () => { controller.stop(); } },
|
||||||
{ type: "separator" },
|
{ type: "separator" },
|
||||||
{ label: "Beenden", click: () => { app.quit(); } }
|
{ label: "Beenden", click: () => { app.quit(); } }
|
||||||
@ -131,11 +155,22 @@ function extractLinksFromText(text: string): string[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function normalizeClipboardText(text: string): string {
|
function normalizeClipboardText(text: string): string {
|
||||||
|
const truncateUnicodeSafe = (value: string, maxChars: number): string => {
|
||||||
|
if (value.length <= maxChars) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
const points = Array.from(value);
|
||||||
|
if (points.length <= maxChars) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return points.slice(0, maxChars).join("");
|
||||||
|
};
|
||||||
|
|
||||||
const normalized = String(text || "");
|
const normalized = String(text || "");
|
||||||
if (normalized.length <= CLIPBOARD_MAX_TEXT_CHARS) {
|
if (normalized.length <= CLIPBOARD_MAX_TEXT_CHARS) {
|
||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
const truncated = normalized.slice(0, CLIPBOARD_MAX_TEXT_CHARS);
|
const truncated = truncateUnicodeSafe(normalized, CLIPBOARD_MAX_TEXT_CHARS);
|
||||||
const lastBreak = Math.max(
|
const lastBreak = Math.max(
|
||||||
truncated.lastIndexOf("\n"),
|
truncated.lastIndexOf("\n"),
|
||||||
truncated.lastIndexOf("\r"),
|
truncated.lastIndexOf("\r"),
|
||||||
@ -154,7 +189,12 @@ function startClipboardWatcher(): void {
|
|||||||
}
|
}
|
||||||
lastClipboardText = normalizeClipboardText(clipboard.readText());
|
lastClipboardText = normalizeClipboardText(clipboard.readText());
|
||||||
clipboardTimer = setInterval(() => {
|
clipboardTimer = setInterval(() => {
|
||||||
const text = normalizeClipboardText(clipboard.readText());
|
let text: string;
|
||||||
|
try {
|
||||||
|
text = normalizeClipboardText(clipboard.readText());
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (text === lastClipboardText || !text.trim()) {
|
if (text === lastClipboardText || !text.trim()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -196,11 +236,16 @@ function registerIpcHandlers(): void {
|
|||||||
ipcMain.handle(IPC_CHANNELS.GET_VERSION, () => controller.getVersion());
|
ipcMain.handle(IPC_CHANNELS.GET_VERSION, () => controller.getVersion());
|
||||||
ipcMain.handle(IPC_CHANNELS.CHECK_UPDATES, async () => controller.checkUpdates());
|
ipcMain.handle(IPC_CHANNELS.CHECK_UPDATES, async () => controller.checkUpdates());
|
||||||
ipcMain.handle(IPC_CHANNELS.INSTALL_UPDATE, async () => {
|
ipcMain.handle(IPC_CHANNELS.INSTALL_UPDATE, async () => {
|
||||||
const result = await controller.installUpdate();
|
const result = await controller.installUpdate((progress: UpdateInstallProgress) => {
|
||||||
|
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
mainWindow.webContents.send(IPC_CHANNELS.UPDATE_INSTALL_PROGRESS, progress);
|
||||||
|
});
|
||||||
if (result.started) {
|
if (result.started) {
|
||||||
setTimeout(() => {
|
updateQuitTimer = setTimeout(() => {
|
||||||
app.quit();
|
app.quit();
|
||||||
}, 800);
|
}, 2500);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
@ -236,7 +281,7 @@ function registerIpcHandlers(): void {
|
|||||||
});
|
});
|
||||||
ipcMain.handle(IPC_CHANNELS.ADD_CONTAINERS, async (_event: IpcMainInvokeEvent, filePaths: string[]) => {
|
ipcMain.handle(IPC_CHANNELS.ADD_CONTAINERS, async (_event: IpcMainInvokeEvent, filePaths: string[]) => {
|
||||||
const validPaths = validateStringArray(filePaths ?? [], "filePaths");
|
const validPaths = validateStringArray(filePaths ?? [], "filePaths");
|
||||||
const safePaths = validPaths.filter((p) => path.isAbsolute(p) && !p.includes(".."));
|
const safePaths = validPaths.filter((p) => path.isAbsolute(p));
|
||||||
return controller.addContainers(safePaths);
|
return controller.addContainers(safePaths);
|
||||||
});
|
});
|
||||||
ipcMain.handle(IPC_CHANNELS.GET_START_CONFLICTS, () => controller.getStartConflicts());
|
ipcMain.handle(IPC_CHANNELS.GET_START_CONFLICTS, () => controller.getStartConflicts());
|
||||||
@ -250,6 +295,14 @@ function registerIpcHandlers(): void {
|
|||||||
});
|
});
|
||||||
ipcMain.handle(IPC_CHANNELS.CLEAR_ALL, () => controller.clearAll());
|
ipcMain.handle(IPC_CHANNELS.CLEAR_ALL, () => controller.clearAll());
|
||||||
ipcMain.handle(IPC_CHANNELS.START, () => controller.start());
|
ipcMain.handle(IPC_CHANNELS.START, () => controller.start());
|
||||||
|
ipcMain.handle(IPC_CHANNELS.START_PACKAGES, (_event: IpcMainInvokeEvent, packageIds: string[]) => {
|
||||||
|
validateStringArray(packageIds ?? [], "packageIds");
|
||||||
|
return controller.startPackages(packageIds ?? []);
|
||||||
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.START_ITEMS, (_event: IpcMainInvokeEvent, itemIds: string[]) => {
|
||||||
|
validateStringArray(itemIds ?? [], "itemIds");
|
||||||
|
return controller.startItems(itemIds ?? []);
|
||||||
|
});
|
||||||
ipcMain.handle(IPC_CHANNELS.STOP, () => controller.stop());
|
ipcMain.handle(IPC_CHANNELS.STOP, () => controller.stop());
|
||||||
ipcMain.handle(IPC_CHANNELS.TOGGLE_PAUSE, () => controller.togglePause());
|
ipcMain.handle(IPC_CHANNELS.TOGGLE_PAUSE, () => controller.togglePause());
|
||||||
ipcMain.handle(IPC_CHANNELS.CANCEL_PACKAGE, (_event: IpcMainInvokeEvent, packageId: string) => {
|
ipcMain.handle(IPC_CHANNELS.CANCEL_PACKAGE, (_event: IpcMainInvokeEvent, packageId: string) => {
|
||||||
@ -276,7 +329,53 @@ function registerIpcHandlers(): void {
|
|||||||
validateString(packageId, "packageId");
|
validateString(packageId, "packageId");
|
||||||
return controller.togglePackage(packageId);
|
return controller.togglePackage(packageId);
|
||||||
});
|
});
|
||||||
ipcMain.handle(IPC_CHANNELS.EXPORT_QUEUE, () => controller.exportQueue());
|
ipcMain.handle(IPC_CHANNELS.RETRY_EXTRACTION, (_event: IpcMainInvokeEvent, packageId: string) => {
|
||||||
|
validateString(packageId, "packageId");
|
||||||
|
return controller.retryExtraction(packageId);
|
||||||
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.EXTRACT_NOW, (_event: IpcMainInvokeEvent, packageId: string) => {
|
||||||
|
validateString(packageId, "packageId");
|
||||||
|
return controller.extractNow(packageId);
|
||||||
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.RESET_PACKAGE, (_event: IpcMainInvokeEvent, packageId: string) => {
|
||||||
|
validateString(packageId, "packageId");
|
||||||
|
return controller.resetPackage(packageId);
|
||||||
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.SET_PACKAGE_PRIORITY, (_event: IpcMainInvokeEvent, packageId: string, priority: string) => {
|
||||||
|
validateString(packageId, "packageId");
|
||||||
|
validateString(priority, "priority");
|
||||||
|
if (priority !== "high" && priority !== "normal" && priority !== "low") {
|
||||||
|
throw new Error("priority muss 'high', 'normal' oder 'low' sein");
|
||||||
|
}
|
||||||
|
return controller.setPackagePriority(packageId, priority);
|
||||||
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.SKIP_ITEMS, (_event: IpcMainInvokeEvent, itemIds: string[]) => {
|
||||||
|
validateStringArray(itemIds ?? [], "itemIds");
|
||||||
|
return controller.skipItems(itemIds ?? []);
|
||||||
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.RESET_ITEMS, (_event: IpcMainInvokeEvent, itemIds: string[]) => {
|
||||||
|
validateStringArray(itemIds ?? [], "itemIds");
|
||||||
|
return controller.resetItems(itemIds ?? []);
|
||||||
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.GET_HISTORY, () => controller.getHistory());
|
||||||
|
ipcMain.handle(IPC_CHANNELS.CLEAR_HISTORY, () => controller.clearHistory());
|
||||||
|
ipcMain.handle(IPC_CHANNELS.REMOVE_HISTORY_ENTRY, (_event: IpcMainInvokeEvent, entryId: string) => {
|
||||||
|
validateString(entryId, "entryId");
|
||||||
|
return controller.removeHistoryEntry(entryId);
|
||||||
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.EXPORT_QUEUE, async () => {
|
||||||
|
const options = {
|
||||||
|
defaultPath: `rd-queue-export.json`,
|
||||||
|
filters: [{ name: "Queue Export", extensions: ["json"] }]
|
||||||
|
};
|
||||||
|
const result = mainWindow ? await dialog.showSaveDialog(mainWindow, options) : await dialog.showSaveDialog(options);
|
||||||
|
if (result.canceled || !result.filePath) {
|
||||||
|
return { saved: false };
|
||||||
|
}
|
||||||
|
const json = controller.exportQueue();
|
||||||
|
await fs.promises.writeFile(result.filePath, json, "utf8");
|
||||||
|
return { saved: true };
|
||||||
|
});
|
||||||
ipcMain.handle(IPC_CHANNELS.IMPORT_QUEUE, (_event: IpcMainInvokeEvent, json: string) => {
|
ipcMain.handle(IPC_CHANNELS.IMPORT_QUEUE, (_event: IpcMainInvokeEvent, json: string) => {
|
||||||
validateString(json, "json");
|
validateString(json, "json");
|
||||||
const bytes = Buffer.byteLength(json, "utf8");
|
const bytes = Buffer.byteLength(json, "utf8");
|
||||||
@ -310,6 +409,64 @@ function registerIpcHandlers(): void {
|
|||||||
const result = mainWindow ? await dialog.showOpenDialog(mainWindow, options) : await dialog.showOpenDialog(options);
|
const result = mainWindow ? await dialog.showOpenDialog(mainWindow, options) : await dialog.showOpenDialog(options);
|
||||||
return result.canceled ? [] : result.filePaths;
|
return result.canceled ? [] : result.filePaths;
|
||||||
});
|
});
|
||||||
|
ipcMain.handle(IPC_CHANNELS.GET_SESSION_STATS, () => controller.getSessionStats());
|
||||||
|
|
||||||
|
ipcMain.handle(IPC_CHANNELS.RESTART, () => {
|
||||||
|
app.relaunch();
|
||||||
|
app.quit();
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC_CHANNELS.QUIT, () => {
|
||||||
|
app.quit();
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC_CHANNELS.EXPORT_BACKUP, async () => {
|
||||||
|
const options = {
|
||||||
|
defaultPath: `mdd-backup-${new Date().toISOString().slice(0, 10)}.json`,
|
||||||
|
filters: [{ name: "Backup", extensions: ["json"] }]
|
||||||
|
};
|
||||||
|
const result = mainWindow ? await dialog.showSaveDialog(mainWindow, options) : await dialog.showSaveDialog(options);
|
||||||
|
if (result.canceled || !result.filePath) {
|
||||||
|
return { saved: false };
|
||||||
|
}
|
||||||
|
const json = controller.exportBackup();
|
||||||
|
await fs.promises.writeFile(result.filePath, json, "utf8");
|
||||||
|
return { saved: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC_CHANNELS.OPEN_LOG, async () => {
|
||||||
|
const logPath = getLogFilePath();
|
||||||
|
await shell.openPath(logPath);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC_CHANNELS.OPEN_SESSION_LOG, async () => {
|
||||||
|
const logPath = controller.getSessionLogPath();
|
||||||
|
if (logPath) {
|
||||||
|
await shell.openPath(logPath);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC_CHANNELS.IMPORT_BACKUP, async () => {
|
||||||
|
const options = {
|
||||||
|
properties: ["openFile"] as Array<"openFile">,
|
||||||
|
filters: [
|
||||||
|
{ name: "Backup", extensions: ["json"] },
|
||||||
|
{ name: "Alle Dateien", extensions: ["*"] }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
const result = mainWindow ? await dialog.showOpenDialog(mainWindow, options) : await dialog.showOpenDialog(options);
|
||||||
|
if (result.canceled || result.filePaths.length === 0) {
|
||||||
|
return { restored: false, message: "Abgebrochen" };
|
||||||
|
}
|
||||||
|
const filePath = result.filePaths[0];
|
||||||
|
const stat = await fs.promises.stat(filePath);
|
||||||
|
const BACKUP_MAX_BYTES = 50 * 1024 * 1024;
|
||||||
|
if (stat.size > BACKUP_MAX_BYTES) {
|
||||||
|
return { restored: false, message: `Backup-Datei zu groß (max 50 MB, Datei hat ${(stat.size / 1024 / 1024).toFixed(1)} MB)` };
|
||||||
|
}
|
||||||
|
const json = await fs.promises.readFile(filePath, "utf8");
|
||||||
|
return controller.importBackup(json);
|
||||||
|
});
|
||||||
|
|
||||||
controller.onState = (snapshot) => {
|
controller.onState = (snapshot) => {
|
||||||
if (!mainWindow || mainWindow.isDestroyed()) {
|
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||||
@ -330,28 +487,22 @@ app.on("second-instance", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.whenReady().then(() => {
|
app.whenReady().then(() => {
|
||||||
|
cleanupStaleSubstDrives();
|
||||||
registerIpcHandlers();
|
registerIpcHandlers();
|
||||||
mainWindow = createWindow();
|
mainWindow = createWindow();
|
||||||
|
bindMainWindowLifecycle(mainWindow);
|
||||||
updateClipboardWatcher();
|
updateClipboardWatcher();
|
||||||
updateTray();
|
updateTray();
|
||||||
|
|
||||||
mainWindow.on("close", (event) => {
|
|
||||||
const settings = controller.getSettings();
|
|
||||||
if (settings.minimizeToTray && tray) {
|
|
||||||
event.preventDefault();
|
|
||||||
mainWindow?.hide();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
mainWindow.on("closed", () => {
|
|
||||||
mainWindow = null;
|
|
||||||
});
|
|
||||||
|
|
||||||
app.on("activate", () => {
|
app.on("activate", () => {
|
||||||
if (BrowserWindow.getAllWindows().length === 0) {
|
if (BrowserWindow.getAllWindows().length === 0) {
|
||||||
mainWindow = createWindow();
|
mainWindow = createWindow();
|
||||||
|
bindMainWindowLifecycle(mainWindow);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}).catch((error) => {
|
||||||
|
console.error("App startup failed:", error);
|
||||||
|
app.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
app.on("window-all-closed", () => {
|
app.on("window-all-closed", () => {
|
||||||
@ -361,8 +512,10 @@ app.on("window-all-closed", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.on("before-quit", () => {
|
app.on("before-quit", () => {
|
||||||
|
if (updateQuitTimer) { clearTimeout(updateQuitTimer); updateQuitTimer = null; }
|
||||||
stopClipboardWatcher();
|
stopClipboardWatcher();
|
||||||
destroyTray();
|
destroyTray();
|
||||||
|
shutdownDaemon();
|
||||||
try {
|
try {
|
||||||
controller.shutdown();
|
controller.shutdown();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@ -42,6 +42,45 @@ function parseSetCookieFromHeaders(headers: Headers): string {
|
|||||||
.join("; ");
|
.join("; ");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const PERMANENT_HOSTER_ERRORS = [
|
||||||
|
"hosternotavailable",
|
||||||
|
"filenotfound",
|
||||||
|
"file_unavailable",
|
||||||
|
"file not found",
|
||||||
|
"link is dead",
|
||||||
|
"file has been removed",
|
||||||
|
"file has been deleted",
|
||||||
|
"file was deleted",
|
||||||
|
"file was removed",
|
||||||
|
"not available",
|
||||||
|
"file is no longer available"
|
||||||
|
];
|
||||||
|
|
||||||
|
function parsePageErrors(html: string): string[] {
|
||||||
|
const errors: string[] = [];
|
||||||
|
const errorRegex = /class=["'][^"']*\berror\b[^"']*["'][^>]*>([^<]+)</gi;
|
||||||
|
let m: RegExpExecArray | null;
|
||||||
|
while ((m = errorRegex.exec(html)) !== null) {
|
||||||
|
const text = m[1].replace(/^Fehler:\s*/i, "").trim();
|
||||||
|
if (text) {
|
||||||
|
errors.push(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPermanentHosterError(errors: string[]): string | null {
|
||||||
|
for (const err of errors) {
|
||||||
|
const lower = err.toLowerCase();
|
||||||
|
for (const pattern of PERMANENT_HOSTER_ERRORS) {
|
||||||
|
if (lower.includes(pattern)) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
function parseCodes(html: string): CodeEntry[] {
|
function parseCodes(html: string): CodeEntry[] {
|
||||||
const entries: CodeEntry[] = [];
|
const entries: CodeEntry[] = [];
|
||||||
const cardRegex = /<div[^>]*class=['"][^'"]*acp-box[^'"]*['"][^>]*>[\s\S]*?<\/div>/gi;
|
const cardRegex = /<div[^>]*class=['"][^'"]*acp-box[^'"]*['"][^>]*>[\s\S]*?<\/div>/gi;
|
||||||
@ -88,6 +127,93 @@ function parseDebridJson(text: string): { link: string; text: string } | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function abortError(): Error {
|
||||||
|
return new Error("aborted:mega-web");
|
||||||
|
}
|
||||||
|
|
||||||
|
function withTimeoutSignal(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
|
||||||
|
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
||||||
|
if (!signal) {
|
||||||
|
return timeoutSignal;
|
||||||
|
}
|
||||||
|
return AbortSignal.any([signal, timeoutSignal]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function throwIfAborted(signal?: AbortSignal): void {
|
||||||
|
if (signal?.aborted) {
|
||||||
|
throw abortError();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sleepWithSignal(ms: number, signal?: AbortSignal): Promise<void> {
|
||||||
|
if (!signal) {
|
||||||
|
await sleep(ms);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (signal.aborted) {
|
||||||
|
throw abortError();
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
let timer: NodeJS.Timeout | null = setTimeout(() => {
|
||||||
|
timer = null;
|
||||||
|
signal.removeEventListener("abort", onAbort);
|
||||||
|
resolve();
|
||||||
|
}, Math.max(0, ms));
|
||||||
|
|
||||||
|
const onAbort = (): void => {
|
||||||
|
if (timer) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = null;
|
||||||
|
}
|
||||||
|
signal.removeEventListener("abort", onAbort);
|
||||||
|
reject(abortError());
|
||||||
|
};
|
||||||
|
|
||||||
|
signal.addEventListener("abort", onAbort, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function raceWithAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||||
|
if (!signal) {
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
if (signal.aborted) {
|
||||||
|
throw abortError();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
let settled = false;
|
||||||
|
|
||||||
|
const onAbort = (): void => {
|
||||||
|
if (settled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
settled = true;
|
||||||
|
signal.removeEventListener("abort", onAbort);
|
||||||
|
reject(abortError());
|
||||||
|
};
|
||||||
|
|
||||||
|
signal.addEventListener("abort", onAbort, { once: true });
|
||||||
|
|
||||||
|
promise.then((value) => {
|
||||||
|
if (settled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
settled = true;
|
||||||
|
signal.removeEventListener("abort", onAbort);
|
||||||
|
resolve(value);
|
||||||
|
}, (error) => {
|
||||||
|
if (settled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
settled = true;
|
||||||
|
signal.removeEventListener("abort", onAbort);
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export class MegaWebFallback {
|
export class MegaWebFallback {
|
||||||
private queue: Promise<unknown> = Promise.resolve();
|
private queue: Promise<unknown> = Promise.resolve();
|
||||||
|
|
||||||
@ -101,22 +227,24 @@ export class MegaWebFallback {
|
|||||||
this.getCredentials = getCredentials;
|
this.getCredentials = getCredentials;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async unrestrict(link: string): Promise<UnrestrictedLink | null> {
|
public async unrestrict(link: string, signal?: AbortSignal): Promise<UnrestrictedLink | null> {
|
||||||
|
const overallSignal = withTimeoutSignal(signal, 180000);
|
||||||
return this.runExclusive(async () => {
|
return this.runExclusive(async () => {
|
||||||
|
throwIfAborted(overallSignal);
|
||||||
const creds = this.getCredentials();
|
const creds = this.getCredentials();
|
||||||
if (!creds.login.trim() || !creds.password.trim()) {
|
if (!creds.login.trim() || !creds.password.trim()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.cookie || Date.now() - this.cookieSetAt > 20 * 60 * 1000) {
|
if (!this.cookie || Date.now() - this.cookieSetAt > 20 * 60 * 1000) {
|
||||||
await this.login(creds.login, creds.password);
|
await this.login(creds.login, creds.password, overallSignal);
|
||||||
}
|
}
|
||||||
|
|
||||||
const generated = await this.generate(link);
|
const generated = await this.generate(link, overallSignal);
|
||||||
if (!generated) {
|
if (!generated) {
|
||||||
this.cookie = "";
|
this.cookie = "";
|
||||||
await this.login(creds.login, creds.password);
|
await this.login(creds.login, creds.password, overallSignal);
|
||||||
const retry = await this.generate(link);
|
const retry = await this.generate(link, overallSignal);
|
||||||
if (!retry) {
|
if (!retry) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -134,16 +262,32 @@ export class MegaWebFallback {
|
|||||||
fileSize: null,
|
fileSize: null,
|
||||||
retriesUsed: 0
|
retriesUsed: 0
|
||||||
};
|
};
|
||||||
});
|
}, overallSignal);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async runExclusive<T>(job: () => Promise<T>): Promise<T> {
|
public invalidateSession(): void {
|
||||||
const run = this.queue.then(job, job);
|
this.cookie = "";
|
||||||
|
this.cookieSetAt = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async runExclusive<T>(job: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||||
|
const queuedAt = Date.now();
|
||||||
|
const QUEUE_WAIT_TIMEOUT_MS = 90000;
|
||||||
|
const guardedJob = async (): Promise<T> => {
|
||||||
|
throwIfAborted(signal);
|
||||||
|
const waited = Date.now() - queuedAt;
|
||||||
|
if (waited > QUEUE_WAIT_TIMEOUT_MS) {
|
||||||
|
throw new Error(`Mega-Web Queue-Timeout (${Math.floor(waited / 1000)}s gewartet)`);
|
||||||
|
}
|
||||||
|
return job();
|
||||||
|
};
|
||||||
|
const run = this.queue.then(guardedJob, guardedJob);
|
||||||
this.queue = run.then(() => undefined, () => undefined);
|
this.queue = run.then(() => undefined, () => undefined);
|
||||||
return run;
|
return raceWithAbort(run, signal);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async login(login: string, password: string): Promise<void> {
|
private async login(login: string, password: string, signal?: AbortSignal): Promise<void> {
|
||||||
|
throwIfAborted(signal);
|
||||||
const response = await fetch(LOGIN_URL, {
|
const response = await fetch(LOGIN_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@ -156,7 +300,7 @@ export class MegaWebFallback {
|
|||||||
remember: "on"
|
remember: "on"
|
||||||
}),
|
}),
|
||||||
redirect: "manual",
|
redirect: "manual",
|
||||||
signal: AbortSignal.timeout(30000)
|
signal: withTimeoutSignal(signal, 30000)
|
||||||
});
|
});
|
||||||
|
|
||||||
const cookie = parseSetCookieFromHeaders(response.headers);
|
const cookie = parseSetCookieFromHeaders(response.headers);
|
||||||
@ -171,7 +315,7 @@ export class MegaWebFallback {
|
|||||||
Cookie: cookie,
|
Cookie: cookie,
|
||||||
Referer: DEBRID_REFERER
|
Referer: DEBRID_REFERER
|
||||||
},
|
},
|
||||||
signal: AbortSignal.timeout(30000)
|
signal: withTimeoutSignal(signal, 30000)
|
||||||
});
|
});
|
||||||
const verifyHtml = await verify.text();
|
const verifyHtml = await verify.text();
|
||||||
const hasDebridForm = /id=["']debridForm["']/i.test(verifyHtml) || /name=["']links["']/i.test(verifyHtml);
|
const hasDebridForm = /id=["']debridForm["']/i.test(verifyHtml) || /name=["']links["']/i.test(verifyHtml);
|
||||||
@ -183,7 +327,8 @@ export class MegaWebFallback {
|
|||||||
this.cookieSetAt = Date.now();
|
this.cookieSetAt = Date.now();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async generate(link: string): Promise<{ directUrl: string; fileName: string } | null> {
|
private async generate(link: string, signal?: AbortSignal): Promise<{ directUrl: string; fileName: string } | null> {
|
||||||
|
throwIfAborted(signal);
|
||||||
const page = await fetch(DEBRID_URL, {
|
const page = await fetch(DEBRID_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@ -197,16 +342,25 @@ export class MegaWebFallback {
|
|||||||
password: "",
|
password: "",
|
||||||
showLinks: "1"
|
showLinks: "1"
|
||||||
}),
|
}),
|
||||||
signal: AbortSignal.timeout(30000)
|
signal: withTimeoutSignal(signal, 30000)
|
||||||
});
|
});
|
||||||
|
|
||||||
const html = await page.text();
|
const html = await page.text();
|
||||||
|
|
||||||
|
// Check for permanent hoster errors before looking for debrid codes
|
||||||
|
const pageErrors = parsePageErrors(html);
|
||||||
|
const permanentError = isPermanentHosterError(pageErrors);
|
||||||
|
if (permanentError) {
|
||||||
|
throw new Error(`Mega-Web: Link permanent ungültig (${permanentError})`);
|
||||||
|
}
|
||||||
|
|
||||||
const code = pickCode(parseCodes(html), link);
|
const code = pickCode(parseCodes(html), link);
|
||||||
if (!code) {
|
if (!code) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let attempt = 1; attempt <= 60; attempt += 1) {
|
for (let attempt = 1; attempt <= 60; attempt += 1) {
|
||||||
|
throwIfAborted(signal);
|
||||||
const res = await fetch(DEBRID_AJAX_URL, {
|
const res = await fetch(DEBRID_AJAX_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@ -219,12 +373,12 @@ export class MegaWebFallback {
|
|||||||
code,
|
code,
|
||||||
autodl: "0"
|
autodl: "0"
|
||||||
}),
|
}),
|
||||||
signal: AbortSignal.timeout(15000)
|
signal: withTimeoutSignal(signal, 15000)
|
||||||
});
|
});
|
||||||
|
|
||||||
const text = (await res.text()).trim();
|
const text = (await res.text()).trim();
|
||||||
if (text === "reload") {
|
if (text === "reload") {
|
||||||
await sleep(650);
|
await sleepWithSignal(650, signal);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (text === "false") {
|
if (text === "false") {
|
||||||
@ -238,7 +392,7 @@ export class MegaWebFallback {
|
|||||||
|
|
||||||
if (!parsed.link) {
|
if (!parsed.link) {
|
||||||
if (/hoster does not respond correctly|could not be done for this moment/i.test(parsed.text || "")) {
|
if (/hoster does not respond correctly|could not be done for this moment/i.test(parsed.text || "")) {
|
||||||
await sleep(1200);
|
await sleepWithSignal(1200, signal);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@ -1,13 +1,14 @@
|
|||||||
import { API_BASE_URL, REQUEST_RETRIES } from "./constants";
|
import { API_BASE_URL, APP_VERSION, REQUEST_RETRIES } from "./constants";
|
||||||
import { compactErrorText, sleep } from "./utils";
|
import { compactErrorText, sleep } from "./utils";
|
||||||
|
|
||||||
const DEBRID_USER_AGENT = "RD-Node-Downloader/1.4.28";
|
const DEBRID_USER_AGENT = `RD-Node-Downloader/${APP_VERSION}`;
|
||||||
|
|
||||||
export interface UnrestrictedLink {
|
export interface UnrestrictedLink {
|
||||||
fileName: string;
|
fileName: string;
|
||||||
directUrl: string;
|
directUrl: string;
|
||||||
fileSize: number | null;
|
fileSize: number | null;
|
||||||
retriesUsed: number;
|
retriesUsed: number;
|
||||||
|
skipTlsVerify?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function shouldRetryStatus(status: number): boolean {
|
function shouldRetryStatus(status: number): boolean {
|
||||||
@ -18,6 +19,33 @@ function retryDelay(attempt: number): number {
|
|||||||
return Math.min(5000, 400 * 2 ** attempt);
|
return Math.min(5000, 400 * 2 ** attempt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseRetryAfterMs(value: string | null): number {
|
||||||
|
const text = String(value || "").trim();
|
||||||
|
if (!text) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const asSeconds = Number(text);
|
||||||
|
if (Number.isFinite(asSeconds) && asSeconds >= 0) {
|
||||||
|
return Math.min(120000, Math.floor(asSeconds * 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
const asDate = Date.parse(text);
|
||||||
|
if (Number.isFinite(asDate)) {
|
||||||
|
return Math.min(120000, Math.max(0, asDate - Date.now()));
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function retryDelayForResponse(response: Response, attempt: number): number {
|
||||||
|
if (response.status !== 429) {
|
||||||
|
return retryDelay(attempt);
|
||||||
|
}
|
||||||
|
const fromHeader = parseRetryAfterMs(response.headers.get("retry-after"));
|
||||||
|
return fromHeader > 0 ? fromHeader : retryDelay(attempt);
|
||||||
|
}
|
||||||
|
|
||||||
function readHttpStatusFromErrorText(text: string): number {
|
function readHttpStatusFromErrorText(text: string): number {
|
||||||
const match = String(text || "").match(/HTTP\s+(\d{3})/i);
|
const match = String(text || "").match(/HTTP\s+(\d{3})/i);
|
||||||
return match ? Number(match[1]) : 0;
|
return match ? Number(match[1]) : 0;
|
||||||
@ -35,7 +63,8 @@ function isRetryableErrorText(text: string): boolean {
|
|||||||
|| lower.includes("aborted")
|
|| lower.includes("aborted")
|
||||||
|| lower.includes("econnreset")
|
|| lower.includes("econnreset")
|
||||||
|| lower.includes("enotfound")
|
|| lower.includes("enotfound")
|
||||||
|| lower.includes("etimedout");
|
|| lower.includes("etimedout")
|
||||||
|
|| lower.includes("html statt json");
|
||||||
}
|
}
|
||||||
|
|
||||||
function withTimeoutSignal(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
|
function withTimeoutSignal(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
|
||||||
@ -45,6 +74,36 @@ function withTimeoutSignal(signal: AbortSignal | undefined, timeoutMs: number):
|
|||||||
return AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
|
return AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function sleepWithSignal(ms: number, signal?: AbortSignal): Promise<void> {
|
||||||
|
if (!signal) {
|
||||||
|
await sleep(ms);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Check before entering the Promise constructor to avoid a race where the timer
|
||||||
|
// resolves before the aborted check runs (especially when ms=0).
|
||||||
|
if (signal.aborted) {
|
||||||
|
throw new Error("aborted");
|
||||||
|
}
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
let timer: NodeJS.Timeout | null = setTimeout(() => {
|
||||||
|
timer = null;
|
||||||
|
signal.removeEventListener("abort", onAbort);
|
||||||
|
resolve();
|
||||||
|
}, Math.max(0, ms));
|
||||||
|
|
||||||
|
const onAbort = (): void => {
|
||||||
|
if (timer) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = null;
|
||||||
|
}
|
||||||
|
signal.removeEventListener("abort", onAbort);
|
||||||
|
reject(new Error("aborted"));
|
||||||
|
};
|
||||||
|
|
||||||
|
signal.addEventListener("abort", onAbort, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function looksLikeHtmlResponse(contentType: string, body: string): boolean {
|
function looksLikeHtmlResponse(contentType: string, body: string): boolean {
|
||||||
const type = String(contentType || "").toLowerCase();
|
const type = String(contentType || "").toLowerCase();
|
||||||
if (type.includes("text/html") || type.includes("application/xhtml+xml")) {
|
if (type.includes("text/html") || type.includes("application/xhtml+xml")) {
|
||||||
@ -89,7 +148,7 @@ export class RealDebridClient {
|
|||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const parsed = parseErrorBody(response.status, text, contentType);
|
const parsed = parseErrorBody(response.status, text, contentType);
|
||||||
if (shouldRetryStatus(response.status) && attempt < REQUEST_RETRIES) {
|
if (shouldRetryStatus(response.status) && attempt < REQUEST_RETRIES) {
|
||||||
await sleep(retryDelay(attempt));
|
await sleepWithSignal(retryDelayForResponse(response, attempt), signal);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
throw new Error(parsed);
|
throw new Error(parsed);
|
||||||
@ -109,6 +168,15 @@ export class RealDebridClient {
|
|||||||
if (!directUrl) {
|
if (!directUrl) {
|
||||||
throw new Error("Unrestrict ohne Download-URL");
|
throw new Error("Unrestrict ohne Download-URL");
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
const parsedUrl = new URL(directUrl);
|
||||||
|
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
|
||||||
|
throw new Error(`Ungültiges Download-URL-Protokoll (${parsedUrl.protocol})`);
|
||||||
|
}
|
||||||
|
} catch (urlError) {
|
||||||
|
if (urlError instanceof Error && urlError.message.includes("Protokoll")) throw urlError;
|
||||||
|
throw new Error("Real-Debrid Antwort enthält keine gültige Download-URL");
|
||||||
|
}
|
||||||
|
|
||||||
const fileName = String(payload.filename || "download.bin").trim() || "download.bin";
|
const fileName = String(payload.filename || "download.bin").trim() || "download.bin";
|
||||||
const fileSizeRaw = Number(payload.filesize ?? NaN);
|
const fileSizeRaw = Number(payload.filesize ?? NaN);
|
||||||
@ -120,16 +188,16 @@ export class RealDebridClient {
|
|||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = compactErrorText(error);
|
lastError = compactErrorText(error);
|
||||||
if (signal?.aborted || /aborted/i.test(lastError)) {
|
if (signal?.aborted || (/aborted/i.test(lastError) && !/timeout/i.test(lastError))) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (attempt >= REQUEST_RETRIES || !isRetryableErrorText(lastError)) {
|
if (attempt >= REQUEST_RETRIES || !isRetryableErrorText(lastError)) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
await sleep(retryDelay(attempt));
|
await sleepWithSignal(retryDelay(attempt), signal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new Error(lastError || "Unrestrict fehlgeschlagen");
|
throw new Error(String(lastError || "Unrestrict fehlgeschlagen").replace(/^Error:\s*/i, ""));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
128
src/main/session-log.ts
Normal file
128
src/main/session-log.ts
Normal file
@ -0,0 +1,128 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { setLogListener } from "./logger";
|
||||||
|
|
||||||
|
const SESSION_LOG_FLUSH_INTERVAL_MS = 200;
|
||||||
|
|
||||||
|
let sessionLogPath: string | null = null;
|
||||||
|
let sessionLogsDir: string | null = null;
|
||||||
|
let pendingLines: string[] = [];
|
||||||
|
let flushTimer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
function formatTimestamp(): string {
|
||||||
|
const now = new Date();
|
||||||
|
const y = now.getFullYear();
|
||||||
|
const mo = String(now.getMonth() + 1).padStart(2, "0");
|
||||||
|
const d = String(now.getDate()).padStart(2, "0");
|
||||||
|
const h = String(now.getHours()).padStart(2, "0");
|
||||||
|
const mi = String(now.getMinutes()).padStart(2, "0");
|
||||||
|
const s = String(now.getSeconds()).padStart(2, "0");
|
||||||
|
return `${y}-${mo}-${d}_${h}-${mi}-${s}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function flushPending(): void {
|
||||||
|
if (pendingLines.length === 0 || !sessionLogPath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const chunk = pendingLines.join("");
|
||||||
|
pendingLines = [];
|
||||||
|
try {
|
||||||
|
fs.appendFileSync(sessionLogPath, chunk, "utf8");
|
||||||
|
} catch {
|
||||||
|
// ignore write errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleFlush(): void {
|
||||||
|
if (flushTimer) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
flushTimer = setTimeout(() => {
|
||||||
|
flushTimer = null;
|
||||||
|
flushPending();
|
||||||
|
}, SESSION_LOG_FLUSH_INTERVAL_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendToSessionLog(line: string): void {
|
||||||
|
if (!sessionLogPath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pendingLines.push(line);
|
||||||
|
scheduleFlush();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cleanupOldSessionLogs(dir: string, maxAgeDays: number): Promise<void> {
|
||||||
|
try {
|
||||||
|
const files = await fs.promises.readdir(dir);
|
||||||
|
const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
|
||||||
|
for (const file of files) {
|
||||||
|
if (!file.startsWith("session_") || !file.endsWith(".txt")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const filePath = path.join(dir, file);
|
||||||
|
try {
|
||||||
|
const stat = await fs.promises.stat(filePath);
|
||||||
|
if (stat.mtimeMs < cutoff) {
|
||||||
|
await fs.promises.unlink(filePath);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore - file may be locked
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore - dir may not exist
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initSessionLog(baseDir: string): void {
|
||||||
|
sessionLogsDir = path.join(baseDir, "session-logs");
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(sessionLogsDir, { recursive: true });
|
||||||
|
} catch {
|
||||||
|
sessionLogsDir = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const timestamp = formatTimestamp();
|
||||||
|
sessionLogPath = path.join(sessionLogsDir, `session_${timestamp}.txt`);
|
||||||
|
|
||||||
|
const isoTimestamp = new Date().toISOString();
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(sessionLogPath, `=== Session gestartet: ${isoTimestamp} ===\n`, "utf8");
|
||||||
|
} catch {
|
||||||
|
sessionLogPath = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLogListener((line) => appendToSessionLog(line));
|
||||||
|
|
||||||
|
void cleanupOldSessionLogs(sessionLogsDir, 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSessionLogPath(): string | null {
|
||||||
|
return sessionLogPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shutdownSessionLog(): void {
|
||||||
|
if (!sessionLogPath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush any pending lines
|
||||||
|
if (flushTimer) {
|
||||||
|
clearTimeout(flushTimer);
|
||||||
|
flushTimer = null;
|
||||||
|
}
|
||||||
|
flushPending();
|
||||||
|
|
||||||
|
// Write closing line
|
||||||
|
const isoTimestamp = new Date().toISOString();
|
||||||
|
try {
|
||||||
|
fs.appendFileSync(sessionLogPath, `=== Session beendet: ${isoTimestamp} ===\n`, "utf8");
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
|
||||||
|
setLogListener(null);
|
||||||
|
sessionLogPath = null;
|
||||||
|
}
|
||||||
@ -1,21 +1,24 @@
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import fsp from "node:fs/promises";
|
import fsp from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { AppSettings, BandwidthScheduleEntry, DebridProvider, DownloadItem, DownloadStatus, PackageEntry, SessionState } from "../shared/types";
|
import { AppSettings, BandwidthScheduleEntry, DebridProvider, DownloadItem, DownloadStatus, HistoryEntry, PackageEntry, PackagePriority, SessionState } from "../shared/types";
|
||||||
import { defaultSettings } from "./constants";
|
import { defaultSettings } from "./constants";
|
||||||
import { logger } from "./logger";
|
import { logger } from "./logger";
|
||||||
|
|
||||||
const VALID_PRIMARY_PROVIDERS = new Set(["realdebrid", "megadebrid", "bestdebrid", "alldebrid"]);
|
const VALID_PRIMARY_PROVIDERS = new Set(["realdebrid", "megadebrid", "bestdebrid", "alldebrid", "ddownload", "onefichier"]);
|
||||||
const VALID_FALLBACK_PROVIDERS = new Set(["none", "realdebrid", "megadebrid", "bestdebrid", "alldebrid"]);
|
const VALID_FALLBACK_PROVIDERS = new Set(["none", "realdebrid", "megadebrid", "bestdebrid", "alldebrid", "ddownload", "onefichier"]);
|
||||||
const VALID_CLEANUP_MODES = new Set(["none", "trash", "delete"]);
|
const VALID_CLEANUP_MODES = new Set(["none", "trash", "delete"]);
|
||||||
const VALID_CONFLICT_MODES = new Set(["overwrite", "skip", "rename", "ask"]);
|
const VALID_CONFLICT_MODES = new Set(["overwrite", "skip", "rename", "ask"]);
|
||||||
const VALID_FINISHED_POLICIES = new Set(["never", "immediate", "on_start", "package_done"]);
|
const VALID_FINISHED_POLICIES = new Set(["never", "immediate", "on_start", "package_done"]);
|
||||||
const VALID_SPEED_MODES = new Set(["global", "per_download"]);
|
const VALID_SPEED_MODES = new Set(["global", "per_download"]);
|
||||||
const VALID_THEMES = new Set(["dark", "light"]);
|
const VALID_THEMES = new Set(["dark", "light"]);
|
||||||
|
const VALID_EXTRACT_CPU_PRIORITIES = new Set(["high", "middle", "low"]);
|
||||||
|
const VALID_PACKAGE_PRIORITIES = new Set<string>(["high", "normal", "low"]);
|
||||||
const VALID_DOWNLOAD_STATUSES = new Set<DownloadStatus>([
|
const VALID_DOWNLOAD_STATUSES = new Set<DownloadStatus>([
|
||||||
"queued", "validating", "downloading", "paused", "reconnect_wait", "extracting", "integrity_check", "completed", "failed", "cancelled"
|
"queued", "validating", "downloading", "paused", "reconnect_wait", "extracting", "integrity_check", "completed", "failed", "cancelled"
|
||||||
]);
|
]);
|
||||||
const VALID_ITEM_PROVIDERS = new Set<DebridProvider>(["realdebrid", "megadebrid", "bestdebrid", "alldebrid"]);
|
const VALID_ITEM_PROVIDERS = new Set<DebridProvider>(["realdebrid", "megadebrid", "bestdebrid", "alldebrid", "ddownload", "onefichier"]);
|
||||||
|
const VALID_ONLINE_STATUSES = new Set(["online", "offline", "checking"]);
|
||||||
|
|
||||||
function asText(value: unknown): string {
|
function asText(value: unknown): string {
|
||||||
return String(value ?? "").trim();
|
return String(value ?? "").trim();
|
||||||
@ -59,15 +62,47 @@ function normalizeBandwidthSchedules(raw: unknown): BandwidthScheduleEntry[] {
|
|||||||
|
|
||||||
function normalizeAbsoluteDir(value: unknown, fallback: string): string {
|
function normalizeAbsoluteDir(value: unknown, fallback: string): string {
|
||||||
const text = asText(value);
|
const text = asText(value);
|
||||||
if (/^\/[\s\S]+/.test(text)) {
|
|
||||||
return text.replace(/\\/g, "/");
|
|
||||||
}
|
|
||||||
if (!text || !path.isAbsolute(text)) {
|
if (!text || !path.isAbsolute(text)) {
|
||||||
return path.resolve(fallback);
|
return path.resolve(fallback);
|
||||||
}
|
}
|
||||||
return path.resolve(text);
|
return path.resolve(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DEFAULT_COLUMN_ORDER = ["name", "size", "progress", "hoster", "account", "prio", "status", "speed"];
|
||||||
|
const ALL_VALID_COLUMNS = new Set([...DEFAULT_COLUMN_ORDER, "added"]);
|
||||||
|
|
||||||
|
function normalizeColumnOrder(raw: unknown): string[] {
|
||||||
|
if (!Array.isArray(raw) || raw.length === 0) {
|
||||||
|
return [...DEFAULT_COLUMN_ORDER];
|
||||||
|
}
|
||||||
|
const valid = ALL_VALID_COLUMNS;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const result: string[] = [];
|
||||||
|
for (const col of raw) {
|
||||||
|
if (typeof col === "string" && valid.has(col) && !seen.has(col)) {
|
||||||
|
seen.add(col);
|
||||||
|
result.push(col);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// "name" is mandatory — ensure it's always present
|
||||||
|
if (!seen.has("name")) {
|
||||||
|
result.unshift("name");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEPRECATED_UPDATE_REPOS = new Set([
|
||||||
|
"sucukdeluxe/real-debrid-downloader"
|
||||||
|
]);
|
||||||
|
|
||||||
|
function migrateUpdateRepo(raw: string, fallback: string): string {
|
||||||
|
const trimmed = raw.trim();
|
||||||
|
if (!trimmed || DEPRECATED_UPDATE_REPOS.has(trimmed.toLowerCase())) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizeSettings(settings: AppSettings): AppSettings {
|
export function normalizeSettings(settings: AppSettings): AppSettings {
|
||||||
const defaults = defaultSettings();
|
const defaults = defaultSettings();
|
||||||
const normalized: AppSettings = {
|
const normalized: AppSettings = {
|
||||||
@ -76,7 +111,10 @@ export function normalizeSettings(settings: AppSettings): AppSettings {
|
|||||||
megaPassword: asText(settings.megaPassword),
|
megaPassword: asText(settings.megaPassword),
|
||||||
bestToken: asText(settings.bestToken),
|
bestToken: asText(settings.bestToken),
|
||||||
allDebridToken: asText(settings.allDebridToken),
|
allDebridToken: asText(settings.allDebridToken),
|
||||||
archivePasswordList: String(settings.archivePasswordList ?? "").replace(/\r\n/g, "\n"),
|
ddownloadLogin: asText(settings.ddownloadLogin),
|
||||||
|
ddownloadPassword: asText(settings.ddownloadPassword),
|
||||||
|
oneFichierApiKey: asText(settings.oneFichierApiKey),
|
||||||
|
archivePasswordList: String(settings.archivePasswordList ?? "").replace(/\r\n|\r/g, "\n"),
|
||||||
rememberToken: Boolean(settings.rememberToken),
|
rememberToken: Boolean(settings.rememberToken),
|
||||||
providerPrimary: settings.providerPrimary,
|
providerPrimary: settings.providerPrimary,
|
||||||
providerSecondary: settings.providerSecondary,
|
providerSecondary: settings.providerSecondary,
|
||||||
@ -87,6 +125,8 @@ export function normalizeSettings(settings: AppSettings): AppSettings {
|
|||||||
autoExtract: Boolean(settings.autoExtract),
|
autoExtract: Boolean(settings.autoExtract),
|
||||||
autoRename4sf4sj: Boolean(settings.autoRename4sf4sj),
|
autoRename4sf4sj: Boolean(settings.autoRename4sf4sj),
|
||||||
extractDir: normalizeAbsoluteDir(settings.extractDir, defaults.extractDir),
|
extractDir: normalizeAbsoluteDir(settings.extractDir, defaults.extractDir),
|
||||||
|
collectMkvToLibrary: Boolean(settings.collectMkvToLibrary),
|
||||||
|
mkvLibraryDir: normalizeAbsoluteDir(settings.mkvLibraryDir, defaults.mkvLibraryDir),
|
||||||
createExtractSubfolder: Boolean(settings.createExtractSubfolder),
|
createExtractSubfolder: Boolean(settings.createExtractSubfolder),
|
||||||
hybridExtract: Boolean(settings.hybridExtract),
|
hybridExtract: Boolean(settings.hybridExtract),
|
||||||
cleanupMode: settings.cleanupMode,
|
cleanupMode: settings.cleanupMode,
|
||||||
@ -97,17 +137,26 @@ export function normalizeSettings(settings: AppSettings): AppSettings {
|
|||||||
autoResumeOnStart: Boolean(settings.autoResumeOnStart),
|
autoResumeOnStart: Boolean(settings.autoResumeOnStart),
|
||||||
autoReconnect: Boolean(settings.autoReconnect),
|
autoReconnect: Boolean(settings.autoReconnect),
|
||||||
maxParallel: clampNumber(settings.maxParallel, defaults.maxParallel, 1, 50),
|
maxParallel: clampNumber(settings.maxParallel, defaults.maxParallel, 1, 50),
|
||||||
|
maxParallelExtract: clampNumber(settings.maxParallelExtract, defaults.maxParallelExtract, 1, 8),
|
||||||
|
retryLimit: clampNumber(settings.retryLimit, defaults.retryLimit, 0, 99),
|
||||||
reconnectWaitSeconds: clampNumber(settings.reconnectWaitSeconds, defaults.reconnectWaitSeconds, 10, 600),
|
reconnectWaitSeconds: clampNumber(settings.reconnectWaitSeconds, defaults.reconnectWaitSeconds, 10, 600),
|
||||||
completedCleanupPolicy: settings.completedCleanupPolicy,
|
completedCleanupPolicy: settings.completedCleanupPolicy,
|
||||||
speedLimitEnabled: Boolean(settings.speedLimitEnabled),
|
speedLimitEnabled: Boolean(settings.speedLimitEnabled),
|
||||||
speedLimitKbps: clampNumber(settings.speedLimitKbps, defaults.speedLimitKbps, 0, 500000),
|
speedLimitKbps: clampNumber(settings.speedLimitKbps, defaults.speedLimitKbps, 0, 500000),
|
||||||
speedLimitMode: settings.speedLimitMode,
|
speedLimitMode: settings.speedLimitMode,
|
||||||
autoUpdateCheck: Boolean(settings.autoUpdateCheck),
|
autoUpdateCheck: Boolean(settings.autoUpdateCheck),
|
||||||
updateRepo: asText(settings.updateRepo) || defaults.updateRepo,
|
updateRepo: migrateUpdateRepo(asText(settings.updateRepo), defaults.updateRepo),
|
||||||
clipboardWatch: Boolean(settings.clipboardWatch),
|
clipboardWatch: Boolean(settings.clipboardWatch),
|
||||||
minimizeToTray: Boolean(settings.minimizeToTray),
|
minimizeToTray: Boolean(settings.minimizeToTray),
|
||||||
|
collapseNewPackages: settings.collapseNewPackages !== undefined ? Boolean(settings.collapseNewPackages) : defaults.collapseNewPackages,
|
||||||
|
autoSkipExtracted: settings.autoSkipExtracted !== undefined ? Boolean(settings.autoSkipExtracted) : defaults.autoSkipExtracted,
|
||||||
|
confirmDeleteSelection: settings.confirmDeleteSelection !== undefined ? Boolean(settings.confirmDeleteSelection) : defaults.confirmDeleteSelection,
|
||||||
|
totalDownloadedAllTime: typeof settings.totalDownloadedAllTime === "number" && settings.totalDownloadedAllTime >= 0 ? settings.totalDownloadedAllTime : defaults.totalDownloadedAllTime,
|
||||||
theme: VALID_THEMES.has(settings.theme) ? settings.theme : defaults.theme,
|
theme: VALID_THEMES.has(settings.theme) ? settings.theme : defaults.theme,
|
||||||
bandwidthSchedules: normalizeBandwidthSchedules(settings.bandwidthSchedules)
|
bandwidthSchedules: normalizeBandwidthSchedules(settings.bandwidthSchedules),
|
||||||
|
columnOrder: normalizeColumnOrder(settings.columnOrder),
|
||||||
|
extractCpuPriority: settings.extractCpuPriority,
|
||||||
|
autoExtractWhenStopped: settings.autoExtractWhenStopped !== undefined ? Boolean(settings.autoExtractWhenStopped) : defaults.autoExtractWhenStopped
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!VALID_PRIMARY_PROVIDERS.has(normalized.providerPrimary)) {
|
if (!VALID_PRIMARY_PROVIDERS.has(normalized.providerPrimary)) {
|
||||||
@ -137,6 +186,9 @@ export function normalizeSettings(settings: AppSettings): AppSettings {
|
|||||||
if (!VALID_SPEED_MODES.has(normalized.speedLimitMode)) {
|
if (!VALID_SPEED_MODES.has(normalized.speedLimitMode)) {
|
||||||
normalized.speedLimitMode = defaults.speedLimitMode;
|
normalized.speedLimitMode = defaults.speedLimitMode;
|
||||||
}
|
}
|
||||||
|
if (!VALID_EXTRACT_CPU_PRIORITIES.has(normalized.extractCpuPriority)) {
|
||||||
|
normalized.extractCpuPriority = defaults.extractCpuPriority;
|
||||||
|
}
|
||||||
|
|
||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
@ -152,7 +204,9 @@ function sanitizeCredentialPersistence(settings: AppSettings): AppSettings {
|
|||||||
megaPassword: "",
|
megaPassword: "",
|
||||||
bestToken: "",
|
bestToken: "",
|
||||||
allDebridToken: "",
|
allDebridToken: "",
|
||||||
archivePasswordList: ""
|
ddownloadLogin: "",
|
||||||
|
ddownloadPassword: "",
|
||||||
|
oneFichierApiKey: ""
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -160,13 +214,15 @@ export interface StoragePaths {
|
|||||||
baseDir: string;
|
baseDir: string;
|
||||||
configFile: string;
|
configFile: string;
|
||||||
sessionFile: string;
|
sessionFile: string;
|
||||||
|
historyFile: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createStoragePaths(baseDir: string): StoragePaths {
|
export function createStoragePaths(baseDir: string): StoragePaths {
|
||||||
return {
|
return {
|
||||||
baseDir,
|
baseDir,
|
||||||
configFile: path.join(baseDir, "rd_downloader_config.json"),
|
configFile: path.join(baseDir, "rd_downloader_config.json"),
|
||||||
sessionFile: path.join(baseDir, "rd_session_state.json")
|
sessionFile: path.join(baseDir, "rd_session_state.json"),
|
||||||
|
historyFile: path.join(baseDir, "rd_history.json")
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -194,7 +250,7 @@ function readSettingsFile(filePath: string): AppSettings | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeLoadedSession(raw: unknown): SessionState {
|
export function normalizeLoadedSession(raw: unknown): SessionState {
|
||||||
const fallback = emptySession();
|
const fallback = emptySession();
|
||||||
const parsed = asRecord(raw);
|
const parsed = asRecord(raw);
|
||||||
if (!parsed) {
|
if (!parsed) {
|
||||||
@ -220,6 +276,8 @@ function normalizeLoadedSession(raw: unknown): SessionState {
|
|||||||
const status: DownloadStatus = VALID_DOWNLOAD_STATUSES.has(statusRaw) ? statusRaw : "queued";
|
const status: DownloadStatus = VALID_DOWNLOAD_STATUSES.has(statusRaw) ? statusRaw : "queued";
|
||||||
const providerRaw = asText(item.provider) as DebridProvider;
|
const providerRaw = asText(item.provider) as DebridProvider;
|
||||||
|
|
||||||
|
const onlineStatusRaw = asText(item.onlineStatus);
|
||||||
|
|
||||||
itemsById[id] = {
|
itemsById[id] = {
|
||||||
id,
|
id,
|
||||||
packageId,
|
packageId,
|
||||||
@ -237,6 +295,7 @@ function normalizeLoadedSession(raw: unknown): SessionState {
|
|||||||
attempts: clampNumber(item.attempts, 0, 0, 10_000),
|
attempts: clampNumber(item.attempts, 0, 0, 10_000),
|
||||||
lastError: asText(item.lastError),
|
lastError: asText(item.lastError),
|
||||||
fullStatus: asText(item.fullStatus),
|
fullStatus: asText(item.fullStatus),
|
||||||
|
onlineStatus: VALID_ONLINE_STATUSES.has(onlineStatusRaw) ? onlineStatusRaw as "online" | "offline" | "checking" : undefined,
|
||||||
createdAt: clampNumber(item.createdAt, now, 0, Number.MAX_SAFE_INTEGER),
|
createdAt: clampNumber(item.createdAt, now, 0, Number.MAX_SAFE_INTEGER),
|
||||||
updatedAt: clampNumber(item.updatedAt, now, 0, Number.MAX_SAFE_INTEGER)
|
updatedAt: clampNumber(item.updatedAt, now, 0, Number.MAX_SAFE_INTEGER)
|
||||||
};
|
};
|
||||||
@ -267,6 +326,7 @@ function normalizeLoadedSession(raw: unknown): SessionState {
|
|||||||
.filter((value) => value.length > 0),
|
.filter((value) => value.length > 0),
|
||||||
cancelled: Boolean(pkg.cancelled),
|
cancelled: Boolean(pkg.cancelled),
|
||||||
enabled: pkg.enabled === undefined ? true : Boolean(pkg.enabled),
|
enabled: pkg.enabled === undefined ? true : Boolean(pkg.enabled),
|
||||||
|
priority: VALID_PACKAGE_PRIORITIES.has(asText(pkg.priority)) ? asText(pkg.priority) as PackagePriority : "normal",
|
||||||
createdAt: clampNumber(pkg.createdAt, now, 0, Number.MAX_SAFE_INTEGER),
|
createdAt: clampNumber(pkg.createdAt, now, 0, Number.MAX_SAFE_INTEGER),
|
||||||
updatedAt: clampNumber(pkg.updatedAt, now, 0, Number.MAX_SAFE_INTEGER)
|
updatedAt: clampNumber(pkg.updatedAt, now, 0, Number.MAX_SAFE_INTEGER)
|
||||||
};
|
};
|
||||||
@ -297,7 +357,8 @@ function normalizeLoadedSession(raw: unknown): SessionState {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
for (const packageId of Object.keys(packagesById)) {
|
for (const packageId of Object.keys(packagesById)) {
|
||||||
if (!packageOrder.includes(packageId)) {
|
if (!seenOrder.has(packageId)) {
|
||||||
|
seenOrder.add(packageId);
|
||||||
packageOrder.push(packageId);
|
packageOrder.push(packageId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -365,6 +426,47 @@ function sessionTempPath(sessionFile: string, kind: "sync" | "async"): string {
|
|||||||
return `${sessionFile}.${kind}.tmp`;
|
return `${sessionFile}.${kind}.tmp`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sessionBackupPath(sessionFile: string): string {
|
||||||
|
return `${sessionFile}.bak`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeLoadedSessionTransientFields(session: SessionState): SessionState {
|
||||||
|
// Reset transient fields that may be stale from a previous crash
|
||||||
|
const ACTIVE_STATUSES = new Set(["downloading", "validating", "extracting", "integrity_check", "paused", "reconnect_wait"]);
|
||||||
|
for (const item of Object.values(session.items)) {
|
||||||
|
if (ACTIVE_STATUSES.has(item.status)) {
|
||||||
|
item.status = "queued";
|
||||||
|
item.lastError = "";
|
||||||
|
}
|
||||||
|
// Always clear stale speed values
|
||||||
|
item.speedBps = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset package-level active statuses to queued (mirrors item reset above)
|
||||||
|
const ACTIVE_PKG_STATUSES = new Set(["downloading", "validating", "extracting", "integrity_check", "paused", "reconnect_wait"]);
|
||||||
|
for (const pkg of Object.values(session.packages)) {
|
||||||
|
if (ACTIVE_PKG_STATUSES.has(pkg.status)) {
|
||||||
|
pkg.status = "queued";
|
||||||
|
}
|
||||||
|
pkg.postProcessLabel = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear stale session-level running/paused flags
|
||||||
|
session.running = false;
|
||||||
|
session.paused = false;
|
||||||
|
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readSessionFile(filePath: string): SessionState | null {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8")) as unknown;
|
||||||
|
return normalizeLoadedSessionTransientFields(normalizeLoadedSession(parsed));
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function saveSettings(paths: StoragePaths, settings: AppSettings): void {
|
export function saveSettings(paths: StoragePaths, settings: AppSettings): void {
|
||||||
ensureBaseDir(paths.baseDir);
|
ensureBaseDir(paths.baseDir);
|
||||||
// Create a backup of the existing config before overwriting
|
// Create a backup of the existing config before overwriting
|
||||||
@ -378,8 +480,56 @@ export function saveSettings(paths: StoragePaths, settings: AppSettings): void {
|
|||||||
const persisted = sanitizeCredentialPersistence(normalizeSettings(settings));
|
const persisted = sanitizeCredentialPersistence(normalizeSettings(settings));
|
||||||
const payload = JSON.stringify(persisted, null, 2);
|
const payload = JSON.stringify(persisted, null, 2);
|
||||||
const tempPath = `${paths.configFile}.tmp`;
|
const tempPath = `${paths.configFile}.tmp`;
|
||||||
|
try {
|
||||||
fs.writeFileSync(tempPath, payload, "utf8");
|
fs.writeFileSync(tempPath, payload, "utf8");
|
||||||
syncRenameWithExdevFallback(tempPath, paths.configFile);
|
syncRenameWithExdevFallback(tempPath, paths.configFile);
|
||||||
|
} catch (error) {
|
||||||
|
try { fs.rmSync(tempPath, { force: true }); } catch { /* ignore */ }
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let asyncSettingsSaveRunning = false;
|
||||||
|
let asyncSettingsSaveQueued: { paths: StoragePaths; settings: AppSettings } | null = null;
|
||||||
|
|
||||||
|
async function writeSettingsPayload(paths: StoragePaths, payload: string): Promise<void> {
|
||||||
|
await fs.promises.mkdir(paths.baseDir, { recursive: true });
|
||||||
|
await fsp.copyFile(paths.configFile, `${paths.configFile}.bak`).catch(() => {});
|
||||||
|
const tempPath = `${paths.configFile}.settings.tmp`;
|
||||||
|
await fsp.writeFile(tempPath, payload, "utf8");
|
||||||
|
try {
|
||||||
|
await fsp.rename(tempPath, paths.configFile);
|
||||||
|
} catch (renameError: unknown) {
|
||||||
|
if (renameError && typeof renameError === "object" && "code" in renameError && (renameError as NodeJS.ErrnoException).code === "EXDEV") {
|
||||||
|
await fsp.copyFile(tempPath, paths.configFile);
|
||||||
|
await fsp.rm(tempPath, { force: true }).catch(() => {});
|
||||||
|
} else {
|
||||||
|
await fsp.rm(tempPath, { force: true }).catch(() => {});
|
||||||
|
throw renameError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveSettingsAsync(paths: StoragePaths, settings: AppSettings): Promise<void> {
|
||||||
|
const persisted = sanitizeCredentialPersistence(normalizeSettings(settings));
|
||||||
|
const payload = JSON.stringify(persisted, null, 2);
|
||||||
|
if (asyncSettingsSaveRunning) {
|
||||||
|
asyncSettingsSaveQueued = { paths, settings };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
asyncSettingsSaveRunning = true;
|
||||||
|
try {
|
||||||
|
await writeSettingsPayload(paths, payload);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Async Settings-Save fehlgeschlagen: ${String(error)}`);
|
||||||
|
} finally {
|
||||||
|
asyncSettingsSaveRunning = false;
|
||||||
|
if (asyncSettingsSaveQueued) {
|
||||||
|
const queued = asyncSettingsSaveQueued;
|
||||||
|
asyncSettingsSaveQueued = null;
|
||||||
|
void saveSettingsAsync(queued.paths, queued.settings);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function emptySession(): SessionState {
|
export function emptySession(): SessionState {
|
||||||
@ -404,50 +554,78 @@ export function loadSession(paths: StoragePaths): SessionState {
|
|||||||
if (!fs.existsSync(paths.sessionFile)) {
|
if (!fs.existsSync(paths.sessionFile)) {
|
||||||
return emptySession();
|
return emptySession();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const primary = readSessionFile(paths.sessionFile);
|
||||||
|
if (primary) {
|
||||||
|
return primary;
|
||||||
|
}
|
||||||
|
|
||||||
|
const backupFile = sessionBackupPath(paths.sessionFile);
|
||||||
|
const backup = fs.existsSync(backupFile) ? readSessionFile(backupFile) : null;
|
||||||
|
if (backup) {
|
||||||
|
logger.warn("Session defekt, Backup-Datei wird verwendet");
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(fs.readFileSync(paths.sessionFile, "utf8")) as unknown;
|
const payload = JSON.stringify({ ...backup, updatedAt: Date.now() });
|
||||||
const session = normalizeLoadedSession(parsed);
|
|
||||||
|
|
||||||
// Reset transient fields that may be stale from a previous crash
|
|
||||||
const ACTIVE_STATUSES = new Set(["downloading", "validating", "extracting", "integrity_check", "paused", "reconnect_wait"]);
|
|
||||||
for (const item of Object.values(session.items)) {
|
|
||||||
if (ACTIVE_STATUSES.has(item.status)) {
|
|
||||||
item.status = "queued";
|
|
||||||
item.lastError = "";
|
|
||||||
}
|
|
||||||
// Always clear stale speed values
|
|
||||||
item.speedBps = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
return session;
|
|
||||||
} catch (error) {
|
|
||||||
logger.error(`Session konnte nicht geladen werden: ${String(error)}`);
|
|
||||||
return emptySession();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function saveSession(paths: StoragePaths, session: SessionState): void {
|
|
||||||
ensureBaseDir(paths.baseDir);
|
|
||||||
const payload = JSON.stringify({ ...session, updatedAt: Date.now() });
|
|
||||||
const tempPath = sessionTempPath(paths.sessionFile, "sync");
|
const tempPath = sessionTempPath(paths.sessionFile, "sync");
|
||||||
fs.writeFileSync(tempPath, payload, "utf8");
|
fs.writeFileSync(tempPath, payload, "utf8");
|
||||||
syncRenameWithExdevFallback(tempPath, paths.sessionFile);
|
syncRenameWithExdevFallback(tempPath, paths.sessionFile);
|
||||||
|
} catch {
|
||||||
|
// ignore restore write failure
|
||||||
|
}
|
||||||
|
return backup;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.error("Session konnte nicht geladen werden (auch Backup fehlgeschlagen)");
|
||||||
|
return emptySession();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSession(paths: StoragePaths, session: SessionState): void {
|
||||||
|
syncSaveGeneration += 1;
|
||||||
|
ensureBaseDir(paths.baseDir);
|
||||||
|
if (fs.existsSync(paths.sessionFile)) {
|
||||||
|
try {
|
||||||
|
fs.copyFileSync(paths.sessionFile, sessionBackupPath(paths.sessionFile));
|
||||||
|
} catch {
|
||||||
|
// Best-effort backup; proceed even if it fails
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const payload = JSON.stringify({ ...session, updatedAt: Date.now() });
|
||||||
|
const tempPath = sessionTempPath(paths.sessionFile, "sync");
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(tempPath, payload, "utf8");
|
||||||
|
syncRenameWithExdevFallback(tempPath, paths.sessionFile);
|
||||||
|
} catch (error) {
|
||||||
|
try { fs.rmSync(tempPath, { force: true }); } catch { /* ignore */ }
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let asyncSaveRunning = false;
|
let asyncSaveRunning = false;
|
||||||
let asyncSaveQueued: { paths: StoragePaths; payload: string } | null = null;
|
let asyncSaveQueued: { paths: StoragePaths; payload: string } | null = null;
|
||||||
|
let syncSaveGeneration = 0;
|
||||||
|
|
||||||
async function writeSessionPayload(paths: StoragePaths, payload: string): Promise<void> {
|
async function writeSessionPayload(paths: StoragePaths, payload: string, generation: number): Promise<void> {
|
||||||
await fs.promises.mkdir(paths.baseDir, { recursive: true });
|
await fs.promises.mkdir(paths.baseDir, { recursive: true });
|
||||||
|
await fsp.copyFile(paths.sessionFile, sessionBackupPath(paths.sessionFile)).catch(() => {});
|
||||||
const tempPath = sessionTempPath(paths.sessionFile, "async");
|
const tempPath = sessionTempPath(paths.sessionFile, "async");
|
||||||
await fsp.writeFile(tempPath, payload, "utf8");
|
await fsp.writeFile(tempPath, payload, "utf8");
|
||||||
|
// If a synchronous save occurred after this async save started, discard the stale write
|
||||||
|
if (generation < syncSaveGeneration) {
|
||||||
|
await fsp.rm(tempPath, { force: true }).catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
await fsp.rename(tempPath, paths.sessionFile);
|
await fsp.rename(tempPath, paths.sessionFile);
|
||||||
} catch (renameError: unknown) {
|
} catch (renameError: unknown) {
|
||||||
if (renameError && typeof renameError === "object" && "code" in renameError && (renameError as NodeJS.ErrnoException).code === "EXDEV") {
|
if (renameError && typeof renameError === "object" && "code" in renameError && (renameError as NodeJS.ErrnoException).code === "EXDEV") {
|
||||||
|
if (generation < syncSaveGeneration) {
|
||||||
|
await fsp.rm(tempPath, { force: true }).catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
await fsp.copyFile(tempPath, paths.sessionFile);
|
await fsp.copyFile(tempPath, paths.sessionFile);
|
||||||
await fsp.rm(tempPath, { force: true }).catch(() => {});
|
await fsp.rm(tempPath, { force: true }).catch(() => {});
|
||||||
} else {
|
} else {
|
||||||
|
await fsp.rm(tempPath, { force: true }).catch(() => {});
|
||||||
throw renameError;
|
throw renameError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -459,8 +637,9 @@ async function saveSessionPayloadAsync(paths: StoragePaths, payload: string): Pr
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
asyncSaveRunning = true;
|
asyncSaveRunning = true;
|
||||||
|
const gen = syncSaveGeneration;
|
||||||
try {
|
try {
|
||||||
await writeSessionPayload(paths, payload);
|
await writeSessionPayload(paths, payload, gen);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`Async Session-Save fehlgeschlagen: ${String(error)}`);
|
logger.error(`Async Session-Save fehlgeschlagen: ${String(error)}`);
|
||||||
} finally {
|
} finally {
|
||||||
@ -473,7 +652,98 @@ async function saveSessionPayloadAsync(paths: StoragePaths, payload: string): Pr
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function cancelPendingAsyncSaves(): void {
|
||||||
|
asyncSaveQueued = null;
|
||||||
|
asyncSettingsSaveQueued = null;
|
||||||
|
syncSaveGeneration += 1;
|
||||||
|
}
|
||||||
|
|
||||||
export async function saveSessionAsync(paths: StoragePaths, session: SessionState): Promise<void> {
|
export async function saveSessionAsync(paths: StoragePaths, session: SessionState): Promise<void> {
|
||||||
const payload = JSON.stringify({ ...session, updatedAt: Date.now() });
|
const payload = JSON.stringify({ ...session, updatedAt: Date.now() });
|
||||||
await saveSessionPayloadAsync(paths, payload);
|
await saveSessionPayloadAsync(paths, payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MAX_HISTORY_ENTRIES = 500;
|
||||||
|
|
||||||
|
function normalizeHistoryEntry(raw: unknown, index: number): HistoryEntry | null {
|
||||||
|
const entry = asRecord(raw);
|
||||||
|
if (!entry) return null;
|
||||||
|
|
||||||
|
const id = asText(entry.id) || `hist-${Date.now().toString(36)}-${index}`;
|
||||||
|
const name = asText(entry.name) || "Unbenannt";
|
||||||
|
const providerRaw = asText(entry.provider);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
totalBytes: clampNumber(entry.totalBytes, 0, 0, Number.MAX_SAFE_INTEGER),
|
||||||
|
downloadedBytes: clampNumber(entry.downloadedBytes, 0, 0, Number.MAX_SAFE_INTEGER),
|
||||||
|
fileCount: clampNumber(entry.fileCount, 0, 0, 100000),
|
||||||
|
provider: VALID_ITEM_PROVIDERS.has(providerRaw as DebridProvider) ? providerRaw as DebridProvider : null,
|
||||||
|
completedAt: clampNumber(entry.completedAt, Date.now(), 0, Number.MAX_SAFE_INTEGER),
|
||||||
|
durationSeconds: clampNumber(entry.durationSeconds, 0, 0, Number.MAX_SAFE_INTEGER),
|
||||||
|
status: entry.status === "deleted" ? "deleted" : "completed",
|
||||||
|
outputDir: asText(entry.outputDir),
|
||||||
|
urls: Array.isArray(entry.urls) ? (entry.urls as unknown[]).map(String).filter(Boolean) : undefined
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadHistory(paths: StoragePaths): HistoryEntry[] {
|
||||||
|
ensureBaseDir(paths.baseDir);
|
||||||
|
if (!fs.existsSync(paths.historyFile)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const raw = JSON.parse(fs.readFileSync(paths.historyFile, "utf8")) as unknown;
|
||||||
|
if (!Array.isArray(raw)) return [];
|
||||||
|
|
||||||
|
const entries: HistoryEntry[] = [];
|
||||||
|
for (let i = 0; i < raw.length && entries.length < MAX_HISTORY_ENTRIES; i++) {
|
||||||
|
const normalized = normalizeHistoryEntry(raw[i], i);
|
||||||
|
if (normalized) entries.push(normalized);
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveHistory(paths: StoragePaths, entries: HistoryEntry[]): void {
|
||||||
|
ensureBaseDir(paths.baseDir);
|
||||||
|
const trimmed = entries.slice(0, MAX_HISTORY_ENTRIES);
|
||||||
|
const payload = JSON.stringify(trimmed, null, 2);
|
||||||
|
const tempPath = `${paths.historyFile}.tmp`;
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(tempPath, payload, "utf8");
|
||||||
|
syncRenameWithExdevFallback(tempPath, paths.historyFile);
|
||||||
|
} catch (error) {
|
||||||
|
try { fs.rmSync(tempPath, { force: true }); } catch { /* ignore */ }
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addHistoryEntry(paths: StoragePaths, entry: HistoryEntry): HistoryEntry[] {
|
||||||
|
const existing = loadHistory(paths);
|
||||||
|
const updated = [entry, ...existing].slice(0, MAX_HISTORY_ENTRIES);
|
||||||
|
saveHistory(paths, updated);
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeHistoryEntry(paths: StoragePaths, entryId: string): HistoryEntry[] {
|
||||||
|
const existing = loadHistory(paths);
|
||||||
|
const updated = existing.filter(e => e.id !== entryId);
|
||||||
|
saveHistory(paths, updated);
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearHistory(paths: StoragePaths): void {
|
||||||
|
ensureBaseDir(paths.baseDir);
|
||||||
|
if (fs.existsSync(paths.historyFile)) {
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(paths.historyFile);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -20,10 +20,11 @@ export function compactErrorText(message: unknown, maxLen = 220): string {
|
|||||||
if (!raw) {
|
if (!raw) {
|
||||||
return "Unbekannter Fehler";
|
return "Unbekannter Fehler";
|
||||||
}
|
}
|
||||||
if (raw.length <= maxLen) {
|
const safeMaxLen = Number.isFinite(maxLen) ? Math.max(4, Math.floor(maxLen)) : 220;
|
||||||
|
if (raw.length <= safeMaxLen) {
|
||||||
return raw;
|
return raw;
|
||||||
}
|
}
|
||||||
return `${raw.slice(0, maxLen - 3)}...`;
|
return `${raw.slice(0, safeMaxLen - 3)}...`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sanitizeFilename(name: string): string {
|
export function sanitizeFilename(name: string): string {
|
||||||
@ -71,25 +72,41 @@ export function extractHttpLinksFromText(text: string): string[] {
|
|||||||
|
|
||||||
for (const match of matches) {
|
for (const match of matches) {
|
||||||
let candidate = String(match || "").trim();
|
let candidate = String(match || "").trim();
|
||||||
|
let openParen = 0;
|
||||||
|
let closeParen = 0;
|
||||||
|
let openBracket = 0;
|
||||||
|
let closeBracket = 0;
|
||||||
|
for (const char of candidate) {
|
||||||
|
if (char === "(") {
|
||||||
|
openParen += 1;
|
||||||
|
} else if (char === ")") {
|
||||||
|
closeParen += 1;
|
||||||
|
} else if (char === "[") {
|
||||||
|
openBracket += 1;
|
||||||
|
} else if (char === "]") {
|
||||||
|
closeBracket += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
while (candidate.length > 0) {
|
while (candidate.length > 0) {
|
||||||
const lastChar = candidate[candidate.length - 1];
|
const lastChar = candidate[candidate.length - 1];
|
||||||
if (![")", "]", ",", ".", "!", "?", ";", ":"].includes(lastChar)) {
|
if (![")", "]", ",", ".", "!", "?", ";", ":"].includes(lastChar)) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (lastChar === ")") {
|
if (lastChar === ")") {
|
||||||
const openCount = (candidate.match(/\(/g) || []).length;
|
if (closeParen <= openParen) {
|
||||||
const closeCount = (candidate.match(/\)/g) || []).length;
|
|
||||||
if (closeCount <= openCount) {
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (lastChar === "]") {
|
if (lastChar === "]") {
|
||||||
const openCount = (candidate.match(/\[/g) || []).length;
|
if (closeBracket <= openBracket) {
|
||||||
const closeCount = (candidate.match(/\]/g) || []).length;
|
|
||||||
if (closeCount <= openCount) {
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (lastChar === ")") {
|
||||||
|
closeParen = Math.max(0, closeParen - 1);
|
||||||
|
} else if (lastChar === "]") {
|
||||||
|
closeBracket = Math.max(0, closeBracket - 1);
|
||||||
|
}
|
||||||
candidate = candidate.slice(0, -1);
|
candidate = candidate.slice(0, -1);
|
||||||
}
|
}
|
||||||
if (!candidate || !isHttpLink(candidate) || seen.has(candidate)) {
|
if (!candidate || !isHttpLink(candidate) || seen.has(candidate)) {
|
||||||
@ -182,14 +199,17 @@ export function uniquePreserveOrder(items: string[]): string[] {
|
|||||||
export function parsePackagesFromLinksText(rawText: string, defaultPackageName: string): ParsedPackageInput[] {
|
export function parsePackagesFromLinksText(rawText: string, defaultPackageName: string): ParsedPackageInput[] {
|
||||||
const lines = String(rawText || "").split(/\r?\n/);
|
const lines = String(rawText || "").split(/\r?\n/);
|
||||||
const packages: ParsedPackageInput[] = [];
|
const packages: ParsedPackageInput[] = [];
|
||||||
let currentName = sanitizeFilename(defaultPackageName || "Paket");
|
let currentName = String(defaultPackageName || "").trim();
|
||||||
let currentLinks: string[] = [];
|
let currentLinks: string[] = [];
|
||||||
|
|
||||||
const flush = (): void => {
|
const flush = (): void => {
|
||||||
const links = uniquePreserveOrder(currentLinks.filter((line) => isHttpLink(line)));
|
const links = uniquePreserveOrder(currentLinks.filter((line) => isHttpLink(line)));
|
||||||
if (links.length > 0) {
|
if (links.length > 0) {
|
||||||
|
const normalizedCurrentName = String(currentName || "").trim();
|
||||||
packages.push({
|
packages.push({
|
||||||
name: sanitizeFilename(currentName || inferPackageNameFromLinks(links)),
|
name: normalizedCurrentName
|
||||||
|
? sanitizeFilename(normalizedCurrentName)
|
||||||
|
: inferPackageNameFromLinks(links),
|
||||||
links
|
links
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -204,7 +224,7 @@ export function parsePackagesFromLinksText(rawText: string, defaultPackageName:
|
|||||||
const marker = text.match(/^#\s*package\s*:\s*(.+)$/i);
|
const marker = text.match(/^#\s*package\s*:\s*(.+)$/i);
|
||||||
if (marker) {
|
if (marker) {
|
||||||
flush();
|
flush();
|
||||||
currentName = sanitizeFilename(marker[1]);
|
currentName = String(marker[1] || "").trim();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
currentLinks.push(text);
|
currentLinks.push(text);
|
||||||
|
|||||||
@ -1,5 +1,17 @@
|
|||||||
import { contextBridge, ipcRenderer } from "electron";
|
import { contextBridge, ipcRenderer } from "electron";
|
||||||
import { AddLinksPayload, AppSettings, DuplicatePolicy, StartConflictEntry, StartConflictResolutionResult, UiSnapshot, UpdateCheckResult } from "../shared/types";
|
import {
|
||||||
|
AddLinksPayload,
|
||||||
|
AppSettings,
|
||||||
|
DuplicatePolicy,
|
||||||
|
HistoryEntry,
|
||||||
|
PackagePriority,
|
||||||
|
SessionStats,
|
||||||
|
StartConflictEntry,
|
||||||
|
StartConflictResolutionResult,
|
||||||
|
UiSnapshot,
|
||||||
|
UpdateCheckResult,
|
||||||
|
UpdateInstallProgress
|
||||||
|
} from "../shared/types";
|
||||||
import { IPC_CHANNELS } from "../shared/ipc";
|
import { IPC_CHANNELS } from "../shared/ipc";
|
||||||
import { ElectronApi } from "../shared/preload-api";
|
import { ElectronApi } from "../shared/preload-api";
|
||||||
|
|
||||||
@ -19,6 +31,7 @@ const api: ElectronApi = {
|
|||||||
ipcRenderer.invoke(IPC_CHANNELS.RESOLVE_START_CONFLICT, packageId, policy),
|
ipcRenderer.invoke(IPC_CHANNELS.RESOLVE_START_CONFLICT, packageId, policy),
|
||||||
clearAll: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.CLEAR_ALL),
|
clearAll: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.CLEAR_ALL),
|
||||||
start: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.START),
|
start: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.START),
|
||||||
|
startPackages: (packageIds: string[]): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.START_PACKAGES, packageIds),
|
||||||
stop: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.STOP),
|
stop: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.STOP),
|
||||||
togglePause: (): Promise<boolean> => ipcRenderer.invoke(IPC_CHANNELS.TOGGLE_PAUSE),
|
togglePause: (): Promise<boolean> => ipcRenderer.invoke(IPC_CHANNELS.TOGGLE_PAUSE),
|
||||||
cancelPackage: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.CANCEL_PACKAGE, packageId),
|
cancelPackage: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.CANCEL_PACKAGE, packageId),
|
||||||
@ -26,11 +39,28 @@ const api: ElectronApi = {
|
|||||||
reorderPackages: (packageIds: string[]): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.REORDER_PACKAGES, packageIds),
|
reorderPackages: (packageIds: string[]): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.REORDER_PACKAGES, packageIds),
|
||||||
removeItem: (itemId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.REMOVE_ITEM, itemId),
|
removeItem: (itemId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.REMOVE_ITEM, itemId),
|
||||||
togglePackage: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.TOGGLE_PACKAGE, packageId),
|
togglePackage: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.TOGGLE_PACKAGE, packageId),
|
||||||
exportQueue: (): Promise<string> => ipcRenderer.invoke(IPC_CHANNELS.EXPORT_QUEUE),
|
exportQueue: (): Promise<{ saved: boolean }> => ipcRenderer.invoke(IPC_CHANNELS.EXPORT_QUEUE),
|
||||||
importQueue: (json: string): Promise<{ addedPackages: number; addedLinks: number }> => ipcRenderer.invoke(IPC_CHANNELS.IMPORT_QUEUE, json),
|
importQueue: (json: string): Promise<{ addedPackages: number; addedLinks: number }> => ipcRenderer.invoke(IPC_CHANNELS.IMPORT_QUEUE, json),
|
||||||
toggleClipboard: (): Promise<boolean> => ipcRenderer.invoke(IPC_CHANNELS.TOGGLE_CLIPBOARD),
|
toggleClipboard: (): Promise<boolean> => ipcRenderer.invoke(IPC_CHANNELS.TOGGLE_CLIPBOARD),
|
||||||
pickFolder: (): Promise<string | null> => ipcRenderer.invoke(IPC_CHANNELS.PICK_FOLDER),
|
pickFolder: (): Promise<string | null> => ipcRenderer.invoke(IPC_CHANNELS.PICK_FOLDER),
|
||||||
pickContainers: (): Promise<string[]> => ipcRenderer.invoke(IPC_CHANNELS.PICK_CONTAINERS),
|
pickContainers: (): Promise<string[]> => ipcRenderer.invoke(IPC_CHANNELS.PICK_CONTAINERS),
|
||||||
|
getSessionStats: (): Promise<SessionStats> => ipcRenderer.invoke(IPC_CHANNELS.GET_SESSION_STATS),
|
||||||
|
restart: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.RESTART),
|
||||||
|
quit: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.QUIT),
|
||||||
|
exportBackup: (): Promise<{ saved: boolean }> => ipcRenderer.invoke(IPC_CHANNELS.EXPORT_BACKUP),
|
||||||
|
importBackup: (): Promise<{ restored: boolean; message: string }> => ipcRenderer.invoke(IPC_CHANNELS.IMPORT_BACKUP),
|
||||||
|
openLog: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.OPEN_LOG),
|
||||||
|
openSessionLog: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.OPEN_SESSION_LOG),
|
||||||
|
retryExtraction: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.RETRY_EXTRACTION, packageId),
|
||||||
|
extractNow: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.EXTRACT_NOW, packageId),
|
||||||
|
resetPackage: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.RESET_PACKAGE, packageId),
|
||||||
|
getHistory: (): Promise<HistoryEntry[]> => ipcRenderer.invoke(IPC_CHANNELS.GET_HISTORY),
|
||||||
|
clearHistory: (): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.CLEAR_HISTORY),
|
||||||
|
removeHistoryEntry: (entryId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.REMOVE_HISTORY_ENTRY, entryId),
|
||||||
|
setPackagePriority: (packageId: string, priority: PackagePriority): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.SET_PACKAGE_PRIORITY, packageId, priority),
|
||||||
|
skipItems: (itemIds: string[]): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.SKIP_ITEMS, itemIds),
|
||||||
|
resetItems: (itemIds: string[]): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.RESET_ITEMS, itemIds),
|
||||||
|
startItems: (itemIds: string[]): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.START_ITEMS, itemIds),
|
||||||
onStateUpdate: (callback: (snapshot: UiSnapshot) => void): (() => void) => {
|
onStateUpdate: (callback: (snapshot: UiSnapshot) => void): (() => void) => {
|
||||||
const listener = (_event: unknown, snapshot: UiSnapshot): void => callback(snapshot);
|
const listener = (_event: unknown, snapshot: UiSnapshot): void => callback(snapshot);
|
||||||
ipcRenderer.on(IPC_CHANNELS.STATE_UPDATE, listener);
|
ipcRenderer.on(IPC_CHANNELS.STATE_UPDATE, listener);
|
||||||
@ -44,6 +74,13 @@ const api: ElectronApi = {
|
|||||||
return () => {
|
return () => {
|
||||||
ipcRenderer.removeListener(IPC_CHANNELS.CLIPBOARD_DETECTED, listener);
|
ipcRenderer.removeListener(IPC_CHANNELS.CLIPBOARD_DETECTED, listener);
|
||||||
};
|
};
|
||||||
|
},
|
||||||
|
onUpdateInstallProgress: (callback: (progress: UpdateInstallProgress) => void): (() => void) => {
|
||||||
|
const listener = (_event: unknown, progress: UpdateInstallProgress): void => callback(progress);
|
||||||
|
ipcRenderer.on(IPC_CHANNELS.UPDATE_INSTALL_PROGRESS, listener);
|
||||||
|
return () => {
|
||||||
|
ipcRenderer.removeListener(IPC_CHANNELS.UPDATE_INSTALL_PROGRESS, listener);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
2712
src/renderer/App.tsx
2712
src/renderer/App.tsx
File diff suppressed because it is too large
Load Diff
@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Debrid Download Manager</title>
|
<title>Multi Debrid Downloader</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
25
src/renderer/package-order.ts
Normal file
25
src/renderer/package-order.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import type { PackageEntry } from "../shared/types";
|
||||||
|
|
||||||
|
export function reorderPackageOrderByDrop(order: string[], draggedPackageId: string, targetPackageId: string): string[] {
|
||||||
|
const fromIndex = order.indexOf(draggedPackageId);
|
||||||
|
const toIndex = order.indexOf(targetPackageId);
|
||||||
|
if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) {
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
const next = [...order];
|
||||||
|
const [dragged] = next.splice(fromIndex, 1);
|
||||||
|
const insertIndex = Math.max(0, Math.min(next.length, toIndex));
|
||||||
|
next.splice(insertIndex, 0, dragged);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortPackageOrderByName(order: string[], packages: Record<string, PackageEntry>, descending: boolean): string[] {
|
||||||
|
const sorted = [...order];
|
||||||
|
sorted.sort((a, b) => {
|
||||||
|
const nameA = (packages[a]?.name ?? "").toLowerCase();
|
||||||
|
const nameB = (packages[b]?.name ?? "").toLowerCase();
|
||||||
|
const cmp = nameA.localeCompare(nameB, undefined, { numeric: true, sensitivity: "base" });
|
||||||
|
return descending ? -cmp : cmp;
|
||||||
|
});
|
||||||
|
return sorted;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@ -3,6 +3,7 @@ export const IPC_CHANNELS = {
|
|||||||
GET_VERSION: "app:get-version",
|
GET_VERSION: "app:get-version",
|
||||||
CHECK_UPDATES: "app:check-updates",
|
CHECK_UPDATES: "app:check-updates",
|
||||||
INSTALL_UPDATE: "app:install-update",
|
INSTALL_UPDATE: "app:install-update",
|
||||||
|
UPDATE_INSTALL_PROGRESS: "app:update-install-progress",
|
||||||
OPEN_EXTERNAL: "app:open-external",
|
OPEN_EXTERNAL: "app:open-external",
|
||||||
UPDATE_SETTINGS: "app:update-settings",
|
UPDATE_SETTINGS: "app:update-settings",
|
||||||
ADD_LINKS: "queue:add-links",
|
ADD_LINKS: "queue:add-links",
|
||||||
@ -11,6 +12,7 @@ export const IPC_CHANNELS = {
|
|||||||
RESOLVE_START_CONFLICT: "queue:resolve-start-conflict",
|
RESOLVE_START_CONFLICT: "queue:resolve-start-conflict",
|
||||||
CLEAR_ALL: "queue:clear-all",
|
CLEAR_ALL: "queue:clear-all",
|
||||||
START: "queue:start",
|
START: "queue:start",
|
||||||
|
START_PACKAGES: "queue:start-packages",
|
||||||
STOP: "queue:stop",
|
STOP: "queue:stop",
|
||||||
TOGGLE_PAUSE: "queue:toggle-pause",
|
TOGGLE_PAUSE: "queue:toggle-pause",
|
||||||
CANCEL_PACKAGE: "queue:cancel-package",
|
CANCEL_PACKAGE: "queue:cancel-package",
|
||||||
@ -24,5 +26,22 @@ export const IPC_CHANNELS = {
|
|||||||
PICK_CONTAINERS: "dialog:pick-containers",
|
PICK_CONTAINERS: "dialog:pick-containers",
|
||||||
STATE_UPDATE: "state:update",
|
STATE_UPDATE: "state:update",
|
||||||
CLIPBOARD_DETECTED: "clipboard:detected",
|
CLIPBOARD_DETECTED: "clipboard:detected",
|
||||||
TOGGLE_CLIPBOARD: "clipboard:toggle"
|
TOGGLE_CLIPBOARD: "clipboard:toggle",
|
||||||
|
GET_SESSION_STATS: "stats:get-session-stats",
|
||||||
|
RESTART: "app:restart",
|
||||||
|
QUIT: "app:quit",
|
||||||
|
EXPORT_BACKUP: "app:export-backup",
|
||||||
|
IMPORT_BACKUP: "app:import-backup",
|
||||||
|
OPEN_LOG: "app:open-log",
|
||||||
|
OPEN_SESSION_LOG: "app:open-session-log",
|
||||||
|
RETRY_EXTRACTION: "queue:retry-extraction",
|
||||||
|
EXTRACT_NOW: "queue:extract-now",
|
||||||
|
RESET_PACKAGE: "queue:reset-package",
|
||||||
|
GET_HISTORY: "history:get",
|
||||||
|
CLEAR_HISTORY: "history:clear",
|
||||||
|
REMOVE_HISTORY_ENTRY: "history:remove-entry",
|
||||||
|
SET_PACKAGE_PRIORITY: "queue:set-package-priority",
|
||||||
|
SKIP_ITEMS: "queue:skip-items",
|
||||||
|
RESET_ITEMS: "queue:reset-items",
|
||||||
|
START_ITEMS: "queue:start-items"
|
||||||
} as const;
|
} as const;
|
||||||
|
|||||||
@ -2,10 +2,14 @@ import type {
|
|||||||
AddLinksPayload,
|
AddLinksPayload,
|
||||||
AppSettings,
|
AppSettings,
|
||||||
DuplicatePolicy,
|
DuplicatePolicy,
|
||||||
|
HistoryEntry,
|
||||||
|
PackagePriority,
|
||||||
|
SessionStats,
|
||||||
StartConflictEntry,
|
StartConflictEntry,
|
||||||
StartConflictResolutionResult,
|
StartConflictResolutionResult,
|
||||||
UiSnapshot,
|
UiSnapshot,
|
||||||
UpdateCheckResult,
|
UpdateCheckResult,
|
||||||
|
UpdateInstallProgress,
|
||||||
UpdateInstallResult
|
UpdateInstallResult
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
@ -22,6 +26,7 @@ export interface ElectronApi {
|
|||||||
resolveStartConflict: (packageId: string, policy: DuplicatePolicy) => Promise<StartConflictResolutionResult>;
|
resolveStartConflict: (packageId: string, policy: DuplicatePolicy) => Promise<StartConflictResolutionResult>;
|
||||||
clearAll: () => Promise<void>;
|
clearAll: () => Promise<void>;
|
||||||
start: () => Promise<void>;
|
start: () => Promise<void>;
|
||||||
|
startPackages: (packageIds: string[]) => Promise<void>;
|
||||||
stop: () => Promise<void>;
|
stop: () => Promise<void>;
|
||||||
togglePause: () => Promise<boolean>;
|
togglePause: () => Promise<boolean>;
|
||||||
cancelPackage: (packageId: string) => Promise<void>;
|
cancelPackage: (packageId: string) => Promise<void>;
|
||||||
@ -29,11 +34,29 @@ export interface ElectronApi {
|
|||||||
reorderPackages: (packageIds: string[]) => Promise<void>;
|
reorderPackages: (packageIds: string[]) => Promise<void>;
|
||||||
removeItem: (itemId: string) => Promise<void>;
|
removeItem: (itemId: string) => Promise<void>;
|
||||||
togglePackage: (packageId: string) => Promise<void>;
|
togglePackage: (packageId: string) => Promise<void>;
|
||||||
exportQueue: () => Promise<string>;
|
exportQueue: () => Promise<{ saved: boolean }>;
|
||||||
importQueue: (json: string) => Promise<{ addedPackages: number; addedLinks: number }>;
|
importQueue: (json: string) => Promise<{ addedPackages: number; addedLinks: number }>;
|
||||||
toggleClipboard: () => Promise<boolean>;
|
toggleClipboard: () => Promise<boolean>;
|
||||||
pickFolder: () => Promise<string | null>;
|
pickFolder: () => Promise<string | null>;
|
||||||
pickContainers: () => Promise<string[]>;
|
pickContainers: () => Promise<string[]>;
|
||||||
|
getSessionStats: () => Promise<SessionStats>;
|
||||||
|
restart: () => Promise<void>;
|
||||||
|
quit: () => Promise<void>;
|
||||||
|
exportBackup: () => Promise<{ saved: boolean }>;
|
||||||
|
importBackup: () => Promise<{ restored: boolean; message: string }>;
|
||||||
|
openLog: () => Promise<void>;
|
||||||
|
openSessionLog: () => Promise<void>;
|
||||||
|
retryExtraction: (packageId: string) => Promise<void>;
|
||||||
|
extractNow: (packageId: string) => Promise<void>;
|
||||||
|
resetPackage: (packageId: string) => Promise<void>;
|
||||||
|
getHistory: () => Promise<HistoryEntry[]>;
|
||||||
|
clearHistory: () => Promise<void>;
|
||||||
|
removeHistoryEntry: (entryId: string) => Promise<void>;
|
||||||
|
setPackagePriority: (packageId: string, priority: PackagePriority) => Promise<void>;
|
||||||
|
skipItems: (itemIds: string[]) => Promise<void>;
|
||||||
|
resetItems: (itemIds: string[]) => Promise<void>;
|
||||||
|
startItems: (itemIds: string[]) => Promise<void>;
|
||||||
onStateUpdate: (callback: (snapshot: UiSnapshot) => void) => () => void;
|
onStateUpdate: (callback: (snapshot: UiSnapshot) => void) => () => void;
|
||||||
onClipboardDetected: (callback: (links: string[]) => void) => () => void;
|
onClipboardDetected: (callback: (links: string[]) => void) => () => void;
|
||||||
|
onUpdateInstallProgress: (callback: (progress: UpdateInstallProgress) => void) => () => void;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -14,9 +14,11 @@ export type CleanupMode = "none" | "trash" | "delete";
|
|||||||
export type ConflictMode = "overwrite" | "skip" | "rename" | "ask";
|
export type ConflictMode = "overwrite" | "skip" | "rename" | "ask";
|
||||||
export type SpeedMode = "global" | "per_download";
|
export type SpeedMode = "global" | "per_download";
|
||||||
export type FinishedCleanupPolicy = "never" | "immediate" | "on_start" | "package_done";
|
export type FinishedCleanupPolicy = "never" | "immediate" | "on_start" | "package_done";
|
||||||
export type DebridProvider = "realdebrid" | "megadebrid" | "bestdebrid" | "alldebrid";
|
export type DebridProvider = "realdebrid" | "megadebrid" | "bestdebrid" | "alldebrid" | "ddownload" | "onefichier";
|
||||||
export type DebridFallbackProvider = DebridProvider | "none";
|
export type DebridFallbackProvider = DebridProvider | "none";
|
||||||
export type AppTheme = "dark" | "light";
|
export type AppTheme = "dark" | "light";
|
||||||
|
export type PackagePriority = "high" | "normal" | "low";
|
||||||
|
export type ExtractCpuPriority = "high" | "middle" | "low";
|
||||||
|
|
||||||
export interface BandwidthScheduleEntry {
|
export interface BandwidthScheduleEntry {
|
||||||
id: string;
|
id: string;
|
||||||
@ -28,6 +30,7 @@ export interface BandwidthScheduleEntry {
|
|||||||
|
|
||||||
export interface DownloadStats {
|
export interface DownloadStats {
|
||||||
totalDownloaded: number;
|
totalDownloaded: number;
|
||||||
|
totalDownloadedAllTime: number;
|
||||||
totalFiles: number;
|
totalFiles: number;
|
||||||
totalPackages: number;
|
totalPackages: number;
|
||||||
sessionStartedAt: number;
|
sessionStartedAt: number;
|
||||||
@ -39,6 +42,9 @@ export interface AppSettings {
|
|||||||
megaPassword: string;
|
megaPassword: string;
|
||||||
bestToken: string;
|
bestToken: string;
|
||||||
allDebridToken: string;
|
allDebridToken: string;
|
||||||
|
ddownloadLogin: string;
|
||||||
|
ddownloadPassword: string;
|
||||||
|
oneFichierApiKey: string;
|
||||||
archivePasswordList: string;
|
archivePasswordList: string;
|
||||||
rememberToken: boolean;
|
rememberToken: boolean;
|
||||||
providerPrimary: DebridProvider;
|
providerPrimary: DebridProvider;
|
||||||
@ -50,6 +56,8 @@ export interface AppSettings {
|
|||||||
autoExtract: boolean;
|
autoExtract: boolean;
|
||||||
autoRename4sf4sj: boolean;
|
autoRename4sf4sj: boolean;
|
||||||
extractDir: string;
|
extractDir: string;
|
||||||
|
collectMkvToLibrary: boolean;
|
||||||
|
mkvLibraryDir: string;
|
||||||
createExtractSubfolder: boolean;
|
createExtractSubfolder: boolean;
|
||||||
hybridExtract: boolean;
|
hybridExtract: boolean;
|
||||||
cleanupMode: CleanupMode;
|
cleanupMode: CleanupMode;
|
||||||
@ -62,6 +70,8 @@ export interface AppSettings {
|
|||||||
reconnectWaitSeconds: number;
|
reconnectWaitSeconds: number;
|
||||||
completedCleanupPolicy: FinishedCleanupPolicy;
|
completedCleanupPolicy: FinishedCleanupPolicy;
|
||||||
maxParallel: number;
|
maxParallel: number;
|
||||||
|
maxParallelExtract: number;
|
||||||
|
retryLimit: number;
|
||||||
speedLimitEnabled: boolean;
|
speedLimitEnabled: boolean;
|
||||||
speedLimitKbps: number;
|
speedLimitKbps: number;
|
||||||
speedLimitMode: SpeedMode;
|
speedLimitMode: SpeedMode;
|
||||||
@ -70,7 +80,14 @@ export interface AppSettings {
|
|||||||
clipboardWatch: boolean;
|
clipboardWatch: boolean;
|
||||||
minimizeToTray: boolean;
|
minimizeToTray: boolean;
|
||||||
theme: AppTheme;
|
theme: AppTheme;
|
||||||
|
collapseNewPackages: boolean;
|
||||||
|
autoSkipExtracted: boolean;
|
||||||
|
confirmDeleteSelection: boolean;
|
||||||
|
totalDownloadedAllTime: number;
|
||||||
bandwidthSchedules: BandwidthScheduleEntry[];
|
bandwidthSchedules: BandwidthScheduleEntry[];
|
||||||
|
columnOrder: string[];
|
||||||
|
extractCpuPriority: ExtractCpuPriority;
|
||||||
|
autoExtractWhenStopped: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DownloadItem {
|
export interface DownloadItem {
|
||||||
@ -92,6 +109,7 @@ export interface DownloadItem {
|
|||||||
fullStatus: string;
|
fullStatus: string;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
updatedAt: number;
|
updatedAt: number;
|
||||||
|
onlineStatus?: "online" | "offline" | "checking";
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PackageEntry {
|
export interface PackageEntry {
|
||||||
@ -103,6 +121,8 @@ export interface PackageEntry {
|
|||||||
itemIds: string[];
|
itemIds: string[];
|
||||||
cancelled: boolean;
|
cancelled: boolean;
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
|
priority: PackagePriority;
|
||||||
|
postProcessLabel?: string;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
updatedAt: number;
|
updatedAt: number;
|
||||||
}
|
}
|
||||||
@ -135,6 +155,7 @@ export interface DownloadSummary {
|
|||||||
export interface ParsedPackageInput {
|
export interface ParsedPackageInput {
|
||||||
name: string;
|
name: string;
|
||||||
links: string[];
|
links: string[];
|
||||||
|
fileNames?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ContainerImportResult {
|
export interface ContainerImportResult {
|
||||||
@ -154,6 +175,7 @@ export interface UiSnapshot {
|
|||||||
canPause: boolean;
|
canPause: boolean;
|
||||||
clipboardActive: boolean;
|
clipboardActive: boolean;
|
||||||
reconnectSeconds: number;
|
reconnectSeconds: number;
|
||||||
|
packageSpeedBps: Record<string, number>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AddLinksPayload {
|
export interface AddLinksPayload {
|
||||||
@ -201,6 +223,7 @@ export interface UpdateCheckResult {
|
|||||||
setupAssetUrl?: string;
|
setupAssetUrl?: string;
|
||||||
setupAssetName?: string;
|
setupAssetName?: string;
|
||||||
setupAssetDigest?: string;
|
setupAssetDigest?: string;
|
||||||
|
releaseNotes?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -209,8 +232,58 @@ export interface UpdateInstallResult {
|
|||||||
message: string;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UpdateInstallProgress {
|
||||||
|
stage: "starting" | "downloading" | "verifying" | "launching" | "done" | "error";
|
||||||
|
percent: number | null;
|
||||||
|
downloadedBytes: number;
|
||||||
|
totalBytes: number | null;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ParsedHashEntry {
|
export interface ParsedHashEntry {
|
||||||
fileName: string;
|
fileName: string;
|
||||||
algorithm: "crc32" | "md5" | "sha1";
|
algorithm: "crc32" | "md5" | "sha1";
|
||||||
digest: string;
|
digest: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BandwidthSample {
|
||||||
|
timestamp: number;
|
||||||
|
speedBps: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BandwidthStats {
|
||||||
|
samples: BandwidthSample[];
|
||||||
|
currentSpeedBps: number;
|
||||||
|
averageSpeedBps: number;
|
||||||
|
maxSpeedBps: number;
|
||||||
|
totalBytesSession: number;
|
||||||
|
sessionDurationSeconds: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionStats {
|
||||||
|
bandwidth: BandwidthStats;
|
||||||
|
totalDownloads: number;
|
||||||
|
completedDownloads: number;
|
||||||
|
failedDownloads: number;
|
||||||
|
activeDownloads: number;
|
||||||
|
queuedDownloads: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HistoryEntry {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
totalBytes: number;
|
||||||
|
downloadedBytes: number;
|
||||||
|
fileCount: number;
|
||||||
|
provider: DebridProvider | null;
|
||||||
|
completedAt: number;
|
||||||
|
durationSeconds: number;
|
||||||
|
status: "completed" | "deleted";
|
||||||
|
outputDir: string;
|
||||||
|
urls?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HistoryState {
|
||||||
|
entries: HistoryEntry[];
|
||||||
|
maxEntries: number;
|
||||||
|
}
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { reorderPackageOrderByDrop, sortPackageOrderByName } from "../src/renderer/App";
|
import { reorderPackageOrderByDrop, sortPackageOrderByName } from "../src/renderer/package-order";
|
||||||
|
|
||||||
describe("reorderPackageOrderByDrop", () => {
|
describe("reorderPackageOrderByDrop", () => {
|
||||||
it("moves adjacent package down by one on drop", () => {
|
it("moves adjacent package down by one on drop", () => {
|
||||||
@ -25,9 +25,9 @@ describe("sortPackageOrderByName", () => {
|
|||||||
const sorted = sortPackageOrderByName(
|
const sorted = sortPackageOrderByName(
|
||||||
["pkg3", "pkg1", "pkg2"],
|
["pkg3", "pkg1", "pkg2"],
|
||||||
{
|
{
|
||||||
pkg1: { id: "pkg1", name: "Alpha", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, createdAt: 0, updatedAt: 0 },
|
pkg1: { id: "pkg1", name: "Alpha", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, priority: "normal", createdAt: 0, updatedAt: 0 },
|
||||||
pkg2: { id: "pkg2", name: "beta", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, createdAt: 0, updatedAt: 0 },
|
pkg2: { id: "pkg2", name: "beta", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, priority: "normal", createdAt: 0, updatedAt: 0 },
|
||||||
pkg3: { id: "pkg3", name: "Gamma", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, createdAt: 0, updatedAt: 0 }
|
pkg3: { id: "pkg3", name: "Gamma", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, priority: "normal", createdAt: 0, updatedAt: 0 }
|
||||||
},
|
},
|
||||||
false
|
false
|
||||||
);
|
);
|
||||||
@ -38,9 +38,9 @@ describe("sortPackageOrderByName", () => {
|
|||||||
const sorted = sortPackageOrderByName(
|
const sorted = sortPackageOrderByName(
|
||||||
["pkg1", "pkg2", "pkg3"],
|
["pkg1", "pkg2", "pkg3"],
|
||||||
{
|
{
|
||||||
pkg1: { id: "pkg1", name: "Alpha", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, createdAt: 0, updatedAt: 0 },
|
pkg1: { id: "pkg1", name: "Alpha", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, priority: "normal", createdAt: 0, updatedAt: 0 },
|
||||||
pkg2: { id: "pkg2", name: "beta", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, createdAt: 0, updatedAt: 0 },
|
pkg2: { id: "pkg2", name: "beta", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, priority: "normal", createdAt: 0, updatedAt: 0 },
|
||||||
pkg3: { id: "pkg3", name: "Gamma", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, createdAt: 0, updatedAt: 0 }
|
pkg3: { id: "pkg3", name: "Gamma", outputDir: "", extractDir: "", status: "queued", itemIds: [], cancelled: false, enabled: true, priority: "normal", createdAt: 0, updatedAt: 0 }
|
||||||
},
|
},
|
||||||
true
|
true
|
||||||
);
|
);
|
||||||
|
|||||||
@ -4,7 +4,9 @@ import {
|
|||||||
applyEpisodeTokenToFolderName,
|
applyEpisodeTokenToFolderName,
|
||||||
sourceHasRpToken,
|
sourceHasRpToken,
|
||||||
ensureRepackToken,
|
ensureRepackToken,
|
||||||
buildAutoRenameBaseName
|
buildAutoRenameBaseName,
|
||||||
|
buildAutoRenameBaseNameFromFolders,
|
||||||
|
buildAutoRenameBaseNameFromFoldersWithOptions
|
||||||
} from "../src/main/download-manager";
|
} from "../src/main/download-manager";
|
||||||
|
|
||||||
describe("extractEpisodeToken", () => {
|
describe("extractEpisodeToken", () => {
|
||||||
@ -60,6 +62,22 @@ describe("extractEpisodeToken", () => {
|
|||||||
it("extracts from episode token at end of string", () => {
|
it("extracts from episode token at end of string", () => {
|
||||||
expect(extractEpisodeToken("show.s02e03")).toBe("S02E03");
|
expect(extractEpisodeToken("show.s02e03")).toBe("S02E03");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("extracts double episode token s01e01e02", () => {
|
||||||
|
expect(extractEpisodeToken("tvr-mammon-s01e01e02-720p")).toBe("S01E01E02");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("extracts double episode with dot separators", () => {
|
||||||
|
expect(extractEpisodeToken("Show.S01E03E04.720p")).toBe("S01E03E04");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("extracts double episode at end of string", () => {
|
||||||
|
expect(extractEpisodeToken("show.s02e05e06")).toBe("S02E05E06");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("extracts double episode with single-digit numbers", () => {
|
||||||
|
expect(extractEpisodeToken("show-s1e1e2-720p")).toBe("S01E01E02");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("applyEpisodeTokenToFolderName", () => {
|
describe("applyEpisodeTokenToFolderName", () => {
|
||||||
@ -94,6 +112,21 @@ describe("applyEpisodeTokenToFolderName", () => {
|
|||||||
it("is case-insensitive for -4SF/-4SJ suffix", () => {
|
it("is case-insensitive for -4SF/-4SJ suffix", () => {
|
||||||
expect(applyEpisodeTokenToFolderName("Show.720p-4SF", "S01E01")).toBe("Show.720p.S01E01-4SF");
|
expect(applyEpisodeTokenToFolderName("Show.720p-4SF", "S01E01")).toBe("Show.720p.S01E01-4SF");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("applies double episode token to season-only folder", () => {
|
||||||
|
expect(applyEpisodeTokenToFolderName("Mammon.S01.German.1080P.Bluray.x264-SMAHD", "S01E01E02"))
|
||||||
|
.toBe("Mammon.S01E01E02.German.1080P.Bluray.x264-SMAHD");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replaces existing double episode in folder with new token", () => {
|
||||||
|
expect(applyEpisodeTokenToFolderName("Show.S01E01E02.720p-4sf", "S01E03E04"))
|
||||||
|
.toBe("Show.S01E03E04.720p-4sf");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replaces existing single episode in folder with double episode token", () => {
|
||||||
|
expect(applyEpisodeTokenToFolderName("Show.S01E01.720p-4sf", "S01E01E02"))
|
||||||
|
.toBe("Show.S01E01E02.720p-4sf");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("sourceHasRpToken", () => {
|
describe("sourceHasRpToken", () => {
|
||||||
@ -171,9 +204,9 @@ describe("buildAutoRenameBaseName", () => {
|
|||||||
expect(result).toBe("Show.S01E03.720p-4sj");
|
expect(result).toBe("Show.S01E03.720p-4sj");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns null for non-4sf/4sj folder", () => {
|
it("renames generic scene folder with group suffix", () => {
|
||||||
const result = buildAutoRenameBaseName("Show.S01.720p-GROUP", "show.s01e05.720p.mkv");
|
const result = buildAutoRenameBaseName("Show.S01.720p-GROUP", "show.s01e05.720p.mkv");
|
||||||
expect(result).toBeNull();
|
expect(result).toBe("Show.S01.720p-GROUP");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns null when source has no episode token", () => {
|
it("returns null when source has no episode token", () => {
|
||||||
@ -236,6 +269,7 @@ describe("buildAutoRenameBaseName", () => {
|
|||||||
const result = buildAutoRenameBaseName("Show.S99.720p-4sf", "show.s99e999.720p.mkv");
|
const result = buildAutoRenameBaseName("Show.S99.720p-4sf", "show.s99e999.720p.mkv");
|
||||||
// SCENE_EPISODE_RE allows up to 3-digit episodes and 2-digit seasons
|
// SCENE_EPISODE_RE allows up to 3-digit episodes and 2-digit seasons
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!).toContain("S99E999");
|
||||||
});
|
});
|
||||||
|
|
||||||
// Real-world scene release patterns
|
// Real-world scene release patterns
|
||||||
@ -271,6 +305,30 @@ describe("buildAutoRenameBaseName", () => {
|
|||||||
expect(result).toBe("Severance.S02E07.2160p.ATVP.WEB-DL.DDP5.1.DV.H.265-4SF");
|
expect(result).toBe("Severance.S02E07.2160p.ATVP.WEB-DL.DDP5.1.DV.H.265-4SF");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("real-world: Britannia release keeps folder base name", () => {
|
||||||
|
const result = buildAutoRenameBaseName(
|
||||||
|
"Britannia.S02.GERMAN.720p.WEBRiP.x264-LAW",
|
||||||
|
"law-britannia.s02e01.720p.webrip"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Britannia.S02.GERMAN.720p.WEBRiP.x264-LAW");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("real-world: Britannia repack injects REPACK", () => {
|
||||||
|
const result = buildAutoRenameBaseName(
|
||||||
|
"Britannia.S02.GERMAN.720p.WEBRiP.x264-LAW",
|
||||||
|
"law-britannia.s02e09.720p.webrip.repack"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Britannia.S02.GERMAN.REPACK.720p.WEBRiP.x264-LAW");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("adds REPACK when folder name carries RP hint", () => {
|
||||||
|
const result = buildAutoRenameBaseName(
|
||||||
|
"Banshee.S02E01.German.RP.720p.BluRay.x264-RIPLEY",
|
||||||
|
"r-banshee.s02e01-720p"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Banshee.S02E01.German.REPACK.720p.BluRay.x264-RIPLEY");
|
||||||
|
});
|
||||||
|
|
||||||
it("real-world: folder already has wrong episode", () => {
|
it("real-world: folder already has wrong episode", () => {
|
||||||
const result = buildAutoRenameBaseName(
|
const result = buildAutoRenameBaseName(
|
||||||
"Cobra.Kai.S06E01.720p.NF.WEB-DL.DDP5.1.x264-4SF",
|
"Cobra.Kai.S06E01.720p.NF.WEB-DL.DDP5.1.x264-4SF",
|
||||||
@ -286,6 +344,7 @@ describe("buildAutoRenameBaseName", () => {
|
|||||||
const result = buildAutoRenameBaseName("Show.S01-4sf", "show.s01e01.mkv");
|
const result = buildAutoRenameBaseName("Show.S01-4sf", "show.s01e01.mkv");
|
||||||
// "mkv" should not be treated as part of the filename match
|
// "mkv" should not be treated as part of the filename match
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!).toContain("S01E01");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not match episode-like patterns in codec strings", () => {
|
it("does not match episode-like patterns in codec strings", () => {
|
||||||
@ -316,6 +375,7 @@ describe("buildAutoRenameBaseName", () => {
|
|||||||
// Extreme edge case - sanitizeFilename trims leading dots
|
// Extreme edge case - sanitizeFilename trims leading dots
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result!).toContain("S01E01");
|
expect(result!).toContain("S01E01");
|
||||||
|
expect(result!).toContain("-4sf");
|
||||||
expect(result!).not.toContain(".S01E01.S01E01"); // no duplication
|
expect(result!).not.toContain(".S01E01.S01E01"); // no duplication
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -327,3 +387,308 @@ describe("buildAutoRenameBaseName", () => {
|
|||||||
expect(result!).not.toContain(":");
|
expect(result!).not.toContain(":");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("buildAutoRenameBaseNameFromFolders", () => {
|
||||||
|
it("uses parent folder when current folder is not a scene template", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFolders(
|
||||||
|
[
|
||||||
|
"Episode 01",
|
||||||
|
"Banshee.S02.German.720p.BluRay.x264-RIPLEY"
|
||||||
|
],
|
||||||
|
"r-banshee.s02e01-720p"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Banshee.S02.German.720p.BluRay.x264-RIPLEY");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses nested scene subfolder directly", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFolders(
|
||||||
|
[
|
||||||
|
"Banshee.S02E01.German.720p.BluRay.x264-RIPLEY",
|
||||||
|
"Banshee.S02.German.720p.BluRay.x264-RIPLEY"
|
||||||
|
],
|
||||||
|
"r-banshee.s02e01-720p"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Banshee.S02E01.German.720p.BluRay.x264-RIPLEY");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("injects REPACK when parent folder carries repack hint", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFolders(
|
||||||
|
[
|
||||||
|
"Banshee.S02E01.German.720p.BluRay.x264-RIPLEY",
|
||||||
|
"Banshee.S02.German.RP.720p.BluRay.x264-RIPLEY"
|
||||||
|
],
|
||||||
|
"r-banshee.s02e01-720p"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Banshee.S02E01.German.REPACK.720p.BluRay.x264-RIPLEY");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses nested Arrow episode folder with title", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFolders(
|
||||||
|
[
|
||||||
|
"Arrow.S04E01.Green.Arrow.German.DL.720p.BluRay.x264-RSG",
|
||||||
|
"Arrow.S04.German.DL.720p.BluRay.x264-RSG"
|
||||||
|
],
|
||||||
|
"rsg-arrow-s04e01-720p"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Arrow.S04E01.Green.Arrow.German.DL.720p.BluRay.x264-RSG");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("adds REPACK for Arrow when source contains rp token", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFolders(
|
||||||
|
[
|
||||||
|
"Arrow.S04E01.Green.Arrow.German.DL.720p.BluRay.x264-RSG",
|
||||||
|
"Arrow.S04.German.DL.720p.BluRay.x264-RSG"
|
||||||
|
],
|
||||||
|
"rsg-arrow-s04e01.rp.720p"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Arrow.S04E01.Green.Arrow.German.DL.REPACK.720p.BluRay.x264-RSG");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts Teil token to episode using parent season", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFolders(
|
||||||
|
[
|
||||||
|
"Last.Impact.Der.Einschlag.Teil1.GERMAN.DL.720p.WEB.H264-SunDry",
|
||||||
|
"Last.Impact.Der.Einschlag.S01.GERMAN.DL.720p.WEB.H264-SunDry"
|
||||||
|
],
|
||||||
|
"sundry-last.impact.der.einschlag.teil1.720p.web.h264"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Last.Impact.Der.Einschlag.S01E01.GERMAN.DL.720p.WEB.H264-SunDry");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts Teil token to episode with REPACK", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFolders(
|
||||||
|
[
|
||||||
|
"Last.Impact.Der.Einschlag.Teil1.GERMAN.DL.720p.WEB.H264-SunDry",
|
||||||
|
"Last.Impact.Der.Einschlag.S01.GERMAN.DL.720p.WEB.H264-SunDry"
|
||||||
|
],
|
||||||
|
"sundry-last.impact.der.einschlag.teil1.rp.720p.web.h264"
|
||||||
|
);
|
||||||
|
expect(result).toBe("Last.Impact.Der.Einschlag.S01E01.GERMAN.DL.REPACK.720p.WEB.H264-SunDry");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forces episode insertion for flat season folder when many files share directory", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Arrow.S08.GERMAN.DUBBED.DL.720p.BluRay.x264-TMSF"
|
||||||
|
],
|
||||||
|
"tmsf-arrow-s08e03-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Arrow.S08E03.GERMAN.DUBBED.DL.720p.BluRay.x264-TMSF");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forces episode insertion plus REPACK for flat season folder", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Gotham.S05.GERMAN.DUBBED.720p.BLURAY.x264-ZZGtv"
|
||||||
|
],
|
||||||
|
"zzgtv-gotham-s05e02.rp",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Gotham.S05E02.GERMAN.DUBBED.REPACK.720p.BLURAY.x264-ZZGtv");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses nested episode title folder for Gotham TvR style", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Gotham.S04E01.Pax.Penguina.GERMAN.5.1.DL.AC3.720p.BDRiP.x264-TvR",
|
||||||
|
"Gotham.S04.GERMAN.5.1.DL.AC3.720p.BDRiP.x264-TvR"
|
||||||
|
],
|
||||||
|
"tvr-gotham-s04e01-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Gotham.S04E01.Pax.Penguina.GERMAN.5.1.DL.AC3.720p.BDRiP.x264-TvR");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses nested title folder for Britannia TV4A style", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Britannia.S01E01.Die.Landung.German.DL.720p.BluRay.x264-TV4A",
|
||||||
|
"Britannia.S01.German.DL.720p.BluRay.x264-TV4A"
|
||||||
|
],
|
||||||
|
"tv4a-britannia.s01e01-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Britannia.S01E01.Die.Landung.German.DL.720p.BluRay.x264-TV4A");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles odd source token style 101 by using nested Agent X folder", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Agent.X.S01E01.Pilot.German.DD51.Dubbed.DL.720p.iTunesHD.x264-TVS",
|
||||||
|
"Agent.X.S01.German.DD51.Dubbed.DL.720p.iTunesHD.x264-TVS"
|
||||||
|
],
|
||||||
|
"tvs-agent-x-dd51-ded-dl-7p-ithd-x264-101",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Agent.X.S01E01.Pilot.German.DD51.Dubbed.DL.720p.iTunesHD.x264-TVS");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps compact code 301 to S03E01 for nested Legion folder", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Legion.S03E01.Kapitel.20.German.DD51.Dubbed.DL.720p.AmazonHD.AVC-TVS",
|
||||||
|
"Legion.S03.German.DD51.Dubbed.DL.720p.AmazonHD.AVC-TVS"
|
||||||
|
],
|
||||||
|
"tvs-legion-dd51-ded-dl-7p-azhd-avc-301",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Legion.S03E01.Kapitel.20.German.DD51.Dubbed.DL.720p.AmazonHD.AVC-TVS");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps compact code 211 in flat season folder", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Lethal.Weapon.S02.German.DD51.Dubbed.DL.720p.AmazonHD.x264-TVS"
|
||||||
|
],
|
||||||
|
"tvs-lethal-weapon-dd51-ded-dl-7p-azhd-x264-211",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Lethal.Weapon.S02E11.German.DD51.Dubbed.DL.720p.AmazonHD.x264-TVS");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps episode-only token e01 via season folder hint and keeps REPACK", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Cheat.der.Betrug.S01.GERMAN.720p.WEB.h264-TMSF"
|
||||||
|
],
|
||||||
|
"tmsf-cheatderbetrug-e01-720p-repack",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Cheat.der.Betrug.S01E01.GERMAN.REPACK.720p.WEB.h264-TMSF");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps episode-only token e02 via season folder hint", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Cheat.der.Betrug.S01.GERMAN.720p.WEB.h264-TMSF"
|
||||||
|
],
|
||||||
|
"tmsf-cheatderbetrug-e02-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Cheat.der.Betrug.S01E02.GERMAN.720p.WEB.h264-TMSF");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps renaming for odd source order like 4sf-bs-720p-s01e05", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Cheat.der.Betrug.S01.GERMAN.720p.WEB.h264-TMSF"
|
||||||
|
],
|
||||||
|
"4sf-bs-720p-s01e05",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Cheat.der.Betrug.S01E05.GERMAN.720p.WEB.h264-TMSF");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts lowercase scene group suffixes", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Cheat.der.Betrug.S01.GERMAN.720p.WEB.h264-tmsf"
|
||||||
|
],
|
||||||
|
"tmsf-cheatderbetrug-e01-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Cheat.der.Betrug.S01E01.GERMAN.720p.WEB.h264-tmsf");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renames double episode file into season folder (Mammon style)", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Mammon.S01.German.1080P.Bluray.x264-SMAHD"
|
||||||
|
],
|
||||||
|
"tvr-mammon-s01e01e02-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Mammon.S01E01E02.German.1080P.Bluray.x264-SMAHD");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renames second double episode file correctly", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Mammon.S01.German.1080P.Bluray.x264-SMAHD"
|
||||||
|
],
|
||||||
|
"tvr-mammon-s01e03e04-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Mammon.S01E03E04.German.1080P.Bluray.x264-SMAHD");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renames third double episode file correctly", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Mammon.S01.German.1080P.Bluray.x264-SMAHD"
|
||||||
|
],
|
||||||
|
"tvr-mammon-s01e05e06-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Mammon.S01E05E06.German.1080P.Bluray.x264-SMAHD");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Last-resort fallback: folder has season but no scene group suffix (user-renamed packages)
|
||||||
|
it("renames when folder has season but no scene group suffix (Mystery Road case)", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
["Mystery Road S02"],
|
||||||
|
"myst.road.de.dl.hdtv.7p-s02e05",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Mystery Road S02E05");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renames with season-only folder and custom name without dots", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
["Meine Serie S03"],
|
||||||
|
"meine-serie-s03e10-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Meine Serie S03E10");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prefers scene-group folder over season-only fallback", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
[
|
||||||
|
"Mystery Road S02",
|
||||||
|
"Mystery.Road.S02.GERMAN.DL.AC3.720p.HDTV.x264-hrs"
|
||||||
|
],
|
||||||
|
"myst.road.de.dl.hdtv.7p-s02e05",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
// Should use the scene-group folder (hrs), not the custom one
|
||||||
|
expect(result).toBe("Mystery.Road.S02E05.GERMAN.DL.AC3.720p.HDTV.x264-hrs");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not use season-only fallback when forceEpisodeForSeasonFolder is false", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
["Mystery Road S02"],
|
||||||
|
"myst.road.de.dl.hdtv.7p-s02e05",
|
||||||
|
{ forceEpisodeForSeasonFolder: false }
|
||||||
|
);
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renames Riviera S02 with single-digit episode s02e2", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
["Riviera.S02.GERMAN.DUBBED.DL.720p.WebHD.x264-TVP"],
|
||||||
|
"tvp-riviera-s02e2-720p",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Riviera.S02E02.GERMAN.DUBBED.DL.720p.WebHD.x264-TVP");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renames Room 104 abbreviated source r104.de.dl.web.7p-s04e02", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
["Room.104.S04.GERMAN.DL.720p.WEBRiP.x264-LAW"],
|
||||||
|
"r104.de.dl.web.7p-s04e02",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Room.104.S04E02.GERMAN.DL.720p.WEBRiP.x264-LAW");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renames Room 104 wayne source with episode", () => {
|
||||||
|
const result = buildAutoRenameBaseNameFromFoldersWithOptions(
|
||||||
|
["Room.104.S04.GERMAN.DL.720p.WEBRiP.x264-LAW"],
|
||||||
|
"room.104.s04e01.german.dl.720p.web.h264-wayne",
|
||||||
|
{ forceEpisodeForSeasonFolder: true }
|
||||||
|
);
|
||||||
|
expect(result).toBe("Room.104.S04E01.GERMAN.DL.720p.WEBRiP.x264-LAW");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@ -25,15 +25,15 @@ describe("cleanup", () => {
|
|||||||
expect(fs.existsSync(path.join(dir, "movie.mkv"))).toBe(true);
|
expect(fs.existsSync(path.join(dir, "movie.mkv"))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("removes sample artifacts and link files", () => {
|
it("removes sample artifacts and link files", async () => {
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-clean-"));
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-clean-"));
|
||||||
tempDirs.push(dir);
|
tempDirs.push(dir);
|
||||||
fs.mkdirSync(path.join(dir, "Samples"), { recursive: true });
|
fs.mkdirSync(path.join(dir, "Samples"), { recursive: true });
|
||||||
fs.writeFileSync(path.join(dir, "Samples", "demo-sample.mkv"), "x");
|
fs.writeFileSync(path.join(dir, "Samples", "demo-sample.mkv"), "x");
|
||||||
fs.writeFileSync(path.join(dir, "download_links.txt"), "https://example.com/a\n");
|
fs.writeFileSync(path.join(dir, "download_links.txt"), "https://example.com/a\n");
|
||||||
|
|
||||||
const links = removeDownloadLinkArtifacts(dir);
|
const links = await removeDownloadLinkArtifacts(dir);
|
||||||
const samples = removeSampleArtifacts(dir);
|
const samples = await removeSampleArtifacts(dir);
|
||||||
expect(links).toBeGreaterThan(0);
|
expect(links).toBeGreaterThan(0);
|
||||||
expect(samples.files + samples.dirs).toBeGreaterThan(0);
|
expect(samples.files + samples.dirs).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
@ -66,7 +66,7 @@ describe("cleanup", () => {
|
|||||||
expect(fs.existsSync(path.join(sub2, "subtitle.srt"))).toBe(true);
|
expect(fs.existsSync(path.join(sub2, "subtitle.srt"))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("detects link artifacts by URL content in text files", () => {
|
it("detects link artifacts by URL content in text files", async () => {
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-clean-"));
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-clean-"));
|
||||||
tempDirs.push(dir);
|
tempDirs.push(dir);
|
||||||
|
|
||||||
@ -81,7 +81,7 @@ describe("cleanup", () => {
|
|||||||
// .dlc files should always be removed
|
// .dlc files should always be removed
|
||||||
fs.writeFileSync(path.join(dir, "container.dlc"), "encrypted-data");
|
fs.writeFileSync(path.join(dir, "container.dlc"), "encrypted-data");
|
||||||
|
|
||||||
const removed = removeDownloadLinkArtifacts(dir);
|
const removed = await removeDownloadLinkArtifacts(dir);
|
||||||
expect(removed).toBeGreaterThanOrEqual(3); // download_links.txt + bookmark.url + container.dlc
|
expect(removed).toBeGreaterThanOrEqual(3); // download_links.txt + bookmark.url + container.dlc
|
||||||
expect(fs.existsSync(path.join(dir, "download_links.txt"))).toBe(false);
|
expect(fs.existsSync(path.join(dir, "download_links.txt"))).toBe(false);
|
||||||
expect(fs.existsSync(path.join(dir, "bookmark.url"))).toBe(false);
|
expect(fs.existsSync(path.join(dir, "bookmark.url"))).toBe(false);
|
||||||
@ -90,7 +90,7 @@ describe("cleanup", () => {
|
|||||||
expect(fs.existsSync(path.join(dir, "readme.txt"))).toBe(true);
|
expect(fs.existsSync(path.join(dir, "readme.txt"))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not recurse into sample symlink or junction targets", () => {
|
it("does not recurse into sample symlink or junction targets", async () => {
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-clean-"));
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-clean-"));
|
||||||
const external = fs.mkdtempSync(path.join(os.tmpdir(), "rd-clean-ext-"));
|
const external = fs.mkdtempSync(path.join(os.tmpdir(), "rd-clean-ext-"));
|
||||||
tempDirs.push(dir, external);
|
tempDirs.push(dir, external);
|
||||||
@ -102,7 +102,7 @@ describe("cleanup", () => {
|
|||||||
const linkType: fs.symlink.Type = process.platform === "win32" ? "junction" : "dir";
|
const linkType: fs.symlink.Type = process.platform === "win32" ? "junction" : "dir";
|
||||||
fs.symlinkSync(external, linkedSampleDir, linkType);
|
fs.symlinkSync(external, linkedSampleDir, linkType);
|
||||||
|
|
||||||
const result = removeSampleArtifacts(dir);
|
const result = await removeSampleArtifacts(dir);
|
||||||
expect(result.files).toBe(0);
|
expect(result.files).toBe(0);
|
||||||
expect(fs.existsSync(outsideFile)).toBe(true);
|
expect(fs.existsSync(outsideFile)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -16,16 +16,195 @@ afterEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("container", () => {
|
describe("container", () => {
|
||||||
it("rejects oversized DLC files before network access", async () => {
|
it("skips oversized DLC files without throwing and blocking other files", async () => {
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-"));
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-"));
|
||||||
tempDirs.push(dir);
|
tempDirs.push(dir);
|
||||||
const filePath = path.join(dir, "oversized.dlc");
|
const oversizedFilePath = path.join(dir, "oversized.dlc");
|
||||||
fs.writeFileSync(filePath, Buffer.alloc((8 * 1024 * 1024) + 1, 1));
|
fs.writeFileSync(oversizedFilePath, Buffer.alloc((8 * 1024 * 1024) + 1, 1));
|
||||||
|
|
||||||
const fetchSpy = vi.fn(async () => new Response("should-not-run", { status: 500 }));
|
// Create a valid mockup DLC that would be skipped if an error was thrown
|
||||||
|
const validFilePath = path.join(dir, "valid.dlc");
|
||||||
|
// Just needs to be short enough to pass file limits but fail parsing, triggering dcrypt fallback
|
||||||
|
fs.writeFileSync(validFilePath, Buffer.from("Valid but not real DLC content..."));
|
||||||
|
|
||||||
|
const fetchSpy = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/upload")) {
|
||||||
|
return new Response("http://example.com/file1.rar\nhttp://example.com/file2.rar", { status: 200 });
|
||||||
|
}
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
});
|
||||||
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
||||||
|
|
||||||
await expect(importDlcContainers([filePath])).rejects.toThrow(/zu groß/i);
|
const result = await importDlcContainers([oversizedFilePath, validFilePath]);
|
||||||
expect(fetchSpy).toHaveBeenCalledTimes(0);
|
|
||||||
|
// Expect the oversized to be silently skipped, and valid to be parsed into 1 package with DLC filename
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].name).toBe("valid");
|
||||||
|
expect(result[0].links).toEqual(["http://example.com/file1.rar", "http://example.com/file2.rar"]);
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips non-dlc files completely", async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-non-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const txtPath = path.join(dir, "links.txt");
|
||||||
|
fs.writeFileSync(txtPath, "http://link.com/1");
|
||||||
|
|
||||||
|
const result = await importDlcContainers([txtPath]);
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to dcrypt if local decryption returns empty", async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const filePath = path.join(dir, "fallback.dlc");
|
||||||
|
|
||||||
|
// A file large enough to trigger local decryption attempt (needs > 89 bytes to pass the slice check)
|
||||||
|
fs.writeFileSync(filePath, Buffer.alloc(100, 1).toString("base64"));
|
||||||
|
|
||||||
|
const fetchSpy = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("service.jdownloader.org")) {
|
||||||
|
// Mock local RC service failure (returning 404)
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/upload")) {
|
||||||
|
// Mock dcrypt fallback success
|
||||||
|
return new Response("http://fallback.com/1", { status: 200 });
|
||||||
|
}
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
});
|
||||||
|
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const result = await importDlcContainers([filePath]);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].name).toBe("fallback");
|
||||||
|
expect(result[0].links).toEqual(["http://fallback.com/1"]);
|
||||||
|
// Should have tried both!
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to dcrypt when local decryption throws invalid padding", async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const filePath = path.join(dir, "invalid-local.dlc");
|
||||||
|
fs.writeFileSync(filePath, "X".repeat(120));
|
||||||
|
|
||||||
|
const fetchSpy = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("service.jdownloader.org")) {
|
||||||
|
return new Response(`<rc>${Buffer.alloc(16).toString("base64")}</rc>`, { status: 200 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/upload")) {
|
||||||
|
return new Response("http://example.com/fallback1", { status: 200 });
|
||||||
|
}
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
});
|
||||||
|
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const result = await importDlcContainers([filePath]);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].name).toBe("invalid-local");
|
||||||
|
expect(result[0].links).toEqual(["http://example.com/fallback1"]);
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to paste endpoint when upload returns 413", async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const filePath = path.join(dir, "big-dlc.dlc");
|
||||||
|
fs.writeFileSync(filePath, Buffer.alloc(100, 1).toString("base64"));
|
||||||
|
|
||||||
|
const fetchSpy = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("service.jdownloader.org")) {
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/upload")) {
|
||||||
|
return new Response("Request Entity Too Large", { status: 413 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/paste")) {
|
||||||
|
return new Response("http://paste-fallback.com/file1.rar\nhttp://paste-fallback.com/file2.rar", { status: 200 });
|
||||||
|
}
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
});
|
||||||
|
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const result = await importDlcContainers([filePath]);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].name).toBe("big-dlc");
|
||||||
|
expect(result[0].links).toEqual(["http://paste-fallback.com/file1.rar", "http://paste-fallback.com/file2.rar"]);
|
||||||
|
// local RC + upload + paste = 3 calls
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws when both dcrypt endpoints return 413", async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const filePath = path.join(dir, "huge.dlc");
|
||||||
|
fs.writeFileSync(filePath, Buffer.alloc(100, 1).toString("base64"));
|
||||||
|
|
||||||
|
const fetchSpy = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("service.jdownloader.org")) {
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/upload")) {
|
||||||
|
return new Response("Request Entity Too Large", { status: 413 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/paste")) {
|
||||||
|
return new Response("Request Entity Too Large", { status: 413 });
|
||||||
|
}
|
||||||
|
return new Response("", { status: 500 });
|
||||||
|
});
|
||||||
|
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
||||||
|
|
||||||
|
await expect(importDlcContainers([filePath])).rejects.toThrow(/zu groß für dcrypt/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws when upload returns 413 and paste returns 500", async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const filePath = path.join(dir, "doomed.dlc");
|
||||||
|
fs.writeFileSync(filePath, Buffer.from("not a valid dlc payload at all"));
|
||||||
|
|
||||||
|
const fetchSpy = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("service.jdownloader.org")) {
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/upload")) {
|
||||||
|
return new Response("Request Entity Too Large", { status: 413 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/paste")) {
|
||||||
|
return new Response("paste failure", { status: 500 });
|
||||||
|
}
|
||||||
|
return new Response("", { status: 500 });
|
||||||
|
});
|
||||||
|
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
||||||
|
|
||||||
|
await expect(importDlcContainers([filePath])).rejects.toThrow(/DLC konnte nicht importiert werden/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws clear error when all dlc imports fail", async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dlc-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const filePath = path.join(dir, "broken.dlc");
|
||||||
|
fs.writeFileSync(filePath, Buffer.from("not a valid dlc payload at all"));
|
||||||
|
|
||||||
|
const fetchSpy = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("service.jdownloader.org")) {
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("dcrypt.it/decrypt/upload")) {
|
||||||
|
return new Response("upstream failure", { status: 500 });
|
||||||
|
}
|
||||||
|
return new Response("", { status: 500 });
|
||||||
|
});
|
||||||
|
globalThis.fetch = fetchSpy as unknown as typeof fetch;
|
||||||
|
|
||||||
|
await expect(importDlcContainers([filePath])).rejects.toThrow(/DLC konnte nicht importiert werden/i);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -290,6 +290,44 @@ describe("debrid service", () => {
|
|||||||
expect(fetchSpy).toHaveBeenCalledTimes(0);
|
expect(fetchSpy).toHaveBeenCalledTimes(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("aborts Mega web unrestrict when caller signal is cancelled", async () => {
|
||||||
|
const settings = {
|
||||||
|
...defaultSettings(),
|
||||||
|
token: "",
|
||||||
|
bestToken: "",
|
||||||
|
allDebridToken: "",
|
||||||
|
megaLogin: "user",
|
||||||
|
megaPassword: "pass",
|
||||||
|
providerPrimary: "megadebrid" as const,
|
||||||
|
providerSecondary: "none" as const,
|
||||||
|
providerTertiary: "none" as const,
|
||||||
|
autoProviderFallback: false
|
||||||
|
};
|
||||||
|
|
||||||
|
const megaWeb = vi.fn((_link: string, signal?: AbortSignal): Promise<never> => new Promise((_, reject) => {
|
||||||
|
const onAbort = (): void => reject(new Error("aborted:mega-web-test"));
|
||||||
|
if (signal?.aborted) {
|
||||||
|
onAbort();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
signal?.addEventListener("abort", onAbort, { once: true });
|
||||||
|
}));
|
||||||
|
|
||||||
|
const service = new DebridService(settings, { megaWebUnrestrict: megaWeb });
|
||||||
|
const controller = new AbortController();
|
||||||
|
const abortTimer = setTimeout(() => {
|
||||||
|
controller.abort("test");
|
||||||
|
}, 200);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(service.unrestrictLink("https://rapidgator.net/file/abort-mega-web", controller.signal)).rejects.toThrow(/aborted/i);
|
||||||
|
expect(megaWeb).toHaveBeenCalledTimes(1);
|
||||||
|
expect(megaWeb.mock.calls[0]?.[1]).toBe(controller.signal);
|
||||||
|
} finally {
|
||||||
|
clearTimeout(abortTimer);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("respects provider selection and does not append hidden providers", async () => {
|
it("respects provider selection and does not append hidden providers", async () => {
|
||||||
const settings = {
|
const settings = {
|
||||||
...defaultSettings(),
|
...defaultSettings(),
|
||||||
@ -442,7 +480,7 @@ describe("debrid service", () => {
|
|||||||
expect(resolved.get(link)).toBe("Bulletproof.S01E01.German.DL.DD20.Synced.720p.AmazonHD.h264-GDR.part01.rar");
|
expect(resolved.get(link)).toBe("Bulletproof.S01E01.German.DL.DD20.Synced.720p.AmazonHD.h264-GDR.part01.rar");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("falls back to provider unrestrict for unresolved filename scan", async () => {
|
it("does not unrestrict non-rapidgator links during filename scan", async () => {
|
||||||
const settings = {
|
const settings = {
|
||||||
...defaultSettings(),
|
...defaultSettings(),
|
||||||
token: "rd-token",
|
token: "rd-token",
|
||||||
@ -455,6 +493,7 @@ describe("debrid service", () => {
|
|||||||
|
|
||||||
const linkFromPage = "https://rapidgator.net/file/11111111111111111111111111111111";
|
const linkFromPage = "https://rapidgator.net/file/11111111111111111111111111111111";
|
||||||
const linkFromProvider = "https://hoster.example/file/22222222222222222222222222222222";
|
const linkFromProvider = "https://hoster.example/file/22222222222222222222222222222222";
|
||||||
|
let unrestrictCalls = 0;
|
||||||
|
|
||||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
||||||
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
@ -467,6 +506,7 @@ describe("debrid service", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (url.includes("api.real-debrid.com/rest/1.0/unrestrict/link")) {
|
if (url.includes("api.real-debrid.com/rest/1.0/unrestrict/link")) {
|
||||||
|
unrestrictCalls += 1;
|
||||||
const body = init?.body;
|
const body = init?.body;
|
||||||
const bodyText = body instanceof URLSearchParams ? body.toString() : String(body || "");
|
const bodyText = body instanceof URLSearchParams ? body.toString() : String(body || "");
|
||||||
const linkValue = new URLSearchParams(bodyText).get("link") || "";
|
const linkValue = new URLSearchParams(bodyText).get("link") || "";
|
||||||
@ -492,10 +532,10 @@ describe("debrid service", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
expect(resolved.get(linkFromPage)).toBe("from-page.part1.rar");
|
expect(resolved.get(linkFromPage)).toBe("from-page.part1.rar");
|
||||||
expect(resolved.get(linkFromProvider)).toBe("from-provider.part2.rar");
|
expect(resolved.has(linkFromProvider)).toBe(false);
|
||||||
|
expect(unrestrictCalls).toBe(0);
|
||||||
expect(events).toEqual(expect.arrayContaining([
|
expect(events).toEqual(expect.arrayContaining([
|
||||||
{ link: linkFromPage, fileName: "from-page.part1.rar" },
|
{ link: linkFromPage, fileName: "from-page.part1.rar" }
|
||||||
{ link: linkFromProvider, fileName: "from-provider.part2.rar" }
|
|
||||||
]));
|
]));
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -533,7 +573,7 @@ describe("debrid service", () => {
|
|||||||
expect(unrestrictCalls).toBe(0);
|
expect(unrestrictCalls).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not map AllDebrid filename infos by index when response link is missing", async () => {
|
it("maps AllDebrid filename infos by index when response link is missing", async () => {
|
||||||
const settings = {
|
const settings = {
|
||||||
...defaultSettings(),
|
...defaultSettings(),
|
||||||
token: "",
|
token: "",
|
||||||
@ -572,7 +612,9 @@ describe("debrid service", () => {
|
|||||||
|
|
||||||
const service = new DebridService(settings);
|
const service = new DebridService(settings);
|
||||||
const resolved = await service.resolveFilenames([linkA, linkB]);
|
const resolved = await service.resolveFilenames([linkA, linkB]);
|
||||||
expect(resolved.size).toBe(0);
|
expect(resolved.get(linkA)).toBe("wrong-a.mkv");
|
||||||
|
expect(resolved.get(linkB)).toBe("wrong-b.mkv");
|
||||||
|
expect(resolved.size).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("retries AllDebrid filename infos after transient server error", async () => {
|
it("retries AllDebrid filename infos after transient server error", async () => {
|
||||||
@ -738,6 +780,11 @@ describe("extractRapidgatorFilenameFromHtml", () => {
|
|||||||
expect(extractRapidgatorFilenameFromHtml("")).toBe("");
|
expect(extractRapidgatorFilenameFromHtml("")).toBe("");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("ignores broad body text that is not a labeled filename", () => {
|
||||||
|
const html = "<html><body>Please download file now from mirror.mkv</body></html>";
|
||||||
|
expect(extractRapidgatorFilenameFromHtml(html)).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
it("extracts from File name label in page body", () => {
|
it("extracts from File name label in page body", () => {
|
||||||
const html = '<html><body>File name: <b>Show.S02E03.720p.part01.rar</b></body></html>';
|
const html = '<html><body>File name: <b>Show.S02E03.720p.part01.rar</b></body></html>';
|
||||||
expect(extractRapidgatorFilenameFromHtml(html)).toBe("Show.S02E03.720p.part01.rar");
|
expect(extractRapidgatorFilenameFromHtml(html)).toBe("Show.S02E03.720p.part01.rar");
|
||||||
|
|||||||
@ -177,7 +177,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "retry", links: ["https://dummy/retry"] }]);
|
manager.addPackages([{ name: "retry", links: ["https://dummy/retry"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -253,7 +253,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "same-name", links: ["https://dummy/first", "https://dummy/second"] }]);
|
manager.addPackages([{ name: "same-name", links: ["https://dummy/first", "https://dummy/second"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const items = Object.values(manager.getSnapshot().session.items);
|
const items = Object.values(manager.getSnapshot().session.items);
|
||||||
@ -465,7 +465,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "stall", links: ["https://dummy/stall"] }]);
|
manager.addPackages([{ name: "stall", links: ["https://dummy/stall"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -563,7 +563,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "connect-stall", links: ["https://dummy/connect-stall"] }]);
|
manager.addPackages([{ name: "connect-stall", links: ["https://dummy/connect-stall"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -666,7 +666,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "stall-connect", links: ["https://dummy/stall-connect"] }]);
|
manager.addPackages([{ name: "stall-connect", links: ["https://dummy/stall-connect"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -765,7 +765,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "watchdog-stall", links: ["https://dummy/watchdog-stall"] }]);
|
manager.addPackages([{ name: "watchdog-stall", links: ["https://dummy/watchdog-stall"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -880,7 +880,14 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "drain-stall", links: ["https://dummy/drain-stall"] }]);
|
manager.addPackages([{ name: "drain-stall", links: ["https://dummy/drain-stall"] }]);
|
||||||
|
const queuedSnapshot = manager.getSnapshot();
|
||||||
|
const packageId = queuedSnapshot.session.packageOrder[0] || "";
|
||||||
|
const itemId = queuedSnapshot.session.packages[packageId]?.itemIds[0] || "";
|
||||||
manager.start();
|
manager.start();
|
||||||
|
await waitFor(() => {
|
||||||
|
const status = manager.getSnapshot().session.items[itemId]?.fullStatus || "";
|
||||||
|
return status.includes("Warte auf Festplatte");
|
||||||
|
}, 12000);
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 40000);
|
await waitFor(() => !manager.getSnapshot().session.running, 40000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -954,6 +961,7 @@ describe("download manager", () => {
|
|||||||
token: "rd-token",
|
token: "rd-token",
|
||||||
outputDir: path.join(root, "downloads"),
|
outputDir: path.join(root, "downloads"),
|
||||||
extractDir: path.join(root, "extract"),
|
extractDir: path.join(root, "extract"),
|
||||||
|
retryLimit: 1,
|
||||||
autoExtract: false
|
autoExtract: false
|
||||||
},
|
},
|
||||||
emptySession(),
|
emptySession(),
|
||||||
@ -961,7 +969,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "content-name", links: ["https://rapidgator.net/file/6f09df2984fe01378537c7cd8d7fa7ce"] }]);
|
manager.addPackages([{ name: "content-name", links: ["https://rapidgator.net/file/6f09df2984fe01378537c7cd8d7fa7ce"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -1084,13 +1092,14 @@ describe("download manager", () => {
|
|||||||
token: "rd-token",
|
token: "rd-token",
|
||||||
outputDir: path.join(root, "downloads"),
|
outputDir: path.join(root, "downloads"),
|
||||||
extractDir: path.join(root, "extract"),
|
extractDir: path.join(root, "extract"),
|
||||||
|
retryLimit: 1,
|
||||||
autoExtract: false
|
autoExtract: false
|
||||||
},
|
},
|
||||||
session,
|
session,
|
||||||
createStoragePaths(path.join(root, "state"))
|
createStoragePaths(path.join(root, "state"))
|
||||||
);
|
);
|
||||||
|
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const item = manager.getSnapshot().session.items[itemId];
|
const item = manager.getSnapshot().session.items[itemId];
|
||||||
@ -1216,13 +1225,14 @@ describe("download manager", () => {
|
|||||||
token: "rd-token",
|
token: "rd-token",
|
||||||
outputDir: path.join(root, "downloads"),
|
outputDir: path.join(root, "downloads"),
|
||||||
extractDir: path.join(root, "extract"),
|
extractDir: path.join(root, "extract"),
|
||||||
|
retryLimit: 1,
|
||||||
autoExtract: false
|
autoExtract: false
|
||||||
},
|
},
|
||||||
session,
|
session,
|
||||||
createStoragePaths(path.join(root, "state"))
|
createStoragePaths(path.join(root, "state"))
|
||||||
);
|
);
|
||||||
|
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const item = manager.getSnapshot().session.items[itemId];
|
const item = manager.getSnapshot().session.items[itemId];
|
||||||
@ -1359,13 +1369,14 @@ describe("download manager", () => {
|
|||||||
token: "rd-token",
|
token: "rd-token",
|
||||||
outputDir: path.join(root, "downloads"),
|
outputDir: path.join(root, "downloads"),
|
||||||
extractDir: path.join(root, "extract"),
|
extractDir: path.join(root, "extract"),
|
||||||
|
retryLimit: 1,
|
||||||
autoExtract: false
|
autoExtract: false
|
||||||
},
|
},
|
||||||
session,
|
session,
|
||||||
createStoragePaths(path.join(root, "state"))
|
createStoragePaths(path.join(root, "state"))
|
||||||
);
|
);
|
||||||
|
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const item = manager.getSnapshot().session.items[itemId];
|
const item = manager.getSnapshot().session.items[itemId];
|
||||||
@ -1480,7 +1491,7 @@ describe("download manager", () => {
|
|||||||
createStoragePaths(path.join(root, "state"))
|
createStoragePaths(path.join(root, "state"))
|
||||||
);
|
);
|
||||||
|
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 45000);
|
await waitFor(() => !manager.getSnapshot().session.running, 45000);
|
||||||
|
|
||||||
const item = manager.getSnapshot().session.items[itemId];
|
const item = manager.getSnapshot().session.items[itemId];
|
||||||
@ -1494,7 +1505,7 @@ describe("download manager", () => {
|
|||||||
server.close();
|
server.close();
|
||||||
await once(server, "close");
|
await once(server, "close");
|
||||||
}
|
}
|
||||||
}, 30000);
|
}, 70000);
|
||||||
|
|
||||||
it("retries non-retriable HTTP statuses and eventually succeeds", async () => {
|
it("retries non-retriable HTTP statuses and eventually succeeds", async () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
@ -1561,7 +1572,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "status-retry", links: ["https://dummy/status-retry"] }]);
|
manager.addPackages([{ name: "status-retry", links: ["https://dummy/status-retry"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -1781,7 +1792,7 @@ describe("download manager", () => {
|
|||||||
expect(fs.existsSync(targetPath)).toBe(false);
|
expect(fs.existsSync(targetPath)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("detects start conflicts when extract output already exists", () => {
|
it("detects start conflicts when extract output already exists", async () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
tempDirs.push(root);
|
tempDirs.push(root);
|
||||||
|
|
||||||
@ -1840,7 +1851,7 @@ describe("download manager", () => {
|
|||||||
createStoragePaths(path.join(root, "state"))
|
createStoragePaths(path.join(root, "state"))
|
||||||
);
|
);
|
||||||
|
|
||||||
const conflicts = manager.getStartConflicts();
|
const conflicts = await manager.getStartConflicts();
|
||||||
expect(conflicts.length).toBe(1);
|
expect(conflicts.length).toBe(1);
|
||||||
expect(conflicts[0]?.packageId).toBe(packageId);
|
expect(conflicts[0]?.packageId).toBe(packageId);
|
||||||
});
|
});
|
||||||
@ -1906,8 +1917,104 @@ describe("download manager", () => {
|
|||||||
|
|
||||||
const result = await manager.resolveStartConflict(packageId, "skip");
|
const result = await manager.resolveStartConflict(packageId, "skip");
|
||||||
expect(result.skipped).toBe(true);
|
expect(result.skipped).toBe(true);
|
||||||
expect(manager.getSnapshot().session.packages[packageId]).toBeUndefined();
|
const snapshot = manager.getSnapshot();
|
||||||
expect(manager.getSnapshot().session.items[itemId]).toBeUndefined();
|
expect(snapshot.session.packages[packageId]).toBeDefined();
|
||||||
|
expect(snapshot.session.packages[packageId]?.status).toBe("queued");
|
||||||
|
expect(snapshot.session.items[itemId]).toBeDefined();
|
||||||
|
expect(snapshot.session.items[itemId]?.status).toBe("queued");
|
||||||
|
expect(snapshot.session.items[itemId]?.fullStatus).toBe("Wartet");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps already completed items when skipping start conflict", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
|
||||||
|
const packageId = "skip-partial-pkg";
|
||||||
|
const completedItemId = "skip-partial-completed";
|
||||||
|
const pendingItemId = "skip-partial-pending";
|
||||||
|
const now = Date.now() - 5000;
|
||||||
|
const outputDir = path.join(root, "downloads", "skip-partial");
|
||||||
|
const extractDir = path.join(root, "extract", "skip-partial");
|
||||||
|
fs.mkdirSync(outputDir, { recursive: true });
|
||||||
|
fs.mkdirSync(extractDir, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(extractDir, "existing.mkv"), "x", "utf8");
|
||||||
|
const completedTarget = path.join(outputDir, "skip-partial.part01.rar");
|
||||||
|
fs.writeFileSync(completedTarget, "part", "utf8");
|
||||||
|
|
||||||
|
const session = emptySession();
|
||||||
|
session.packageOrder = [packageId];
|
||||||
|
session.packages[packageId] = {
|
||||||
|
id: packageId,
|
||||||
|
name: "skip-partial",
|
||||||
|
outputDir,
|
||||||
|
extractDir,
|
||||||
|
status: "queued",
|
||||||
|
itemIds: [completedItemId, pendingItemId],
|
||||||
|
cancelled: false,
|
||||||
|
enabled: true,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now
|
||||||
|
};
|
||||||
|
session.items[completedItemId] = {
|
||||||
|
id: completedItemId,
|
||||||
|
packageId,
|
||||||
|
url: "https://dummy/skip-partial/completed",
|
||||||
|
provider: "realdebrid",
|
||||||
|
status: "completed",
|
||||||
|
retries: 0,
|
||||||
|
speedBps: 0,
|
||||||
|
downloadedBytes: 123,
|
||||||
|
totalBytes: 123,
|
||||||
|
progressPercent: 100,
|
||||||
|
fileName: "skip-partial.part01.rar",
|
||||||
|
targetPath: completedTarget,
|
||||||
|
resumable: true,
|
||||||
|
attempts: 1,
|
||||||
|
lastError: "",
|
||||||
|
fullStatus: "Entpackt",
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now
|
||||||
|
};
|
||||||
|
session.items[pendingItemId] = {
|
||||||
|
id: pendingItemId,
|
||||||
|
packageId,
|
||||||
|
url: "https://dummy/skip-partial/pending",
|
||||||
|
provider: null,
|
||||||
|
status: "queued",
|
||||||
|
retries: 0,
|
||||||
|
speedBps: 0,
|
||||||
|
downloadedBytes: 0,
|
||||||
|
totalBytes: null,
|
||||||
|
progressPercent: 0,
|
||||||
|
fileName: "skip-partial.part02.rar",
|
||||||
|
targetPath: path.join(outputDir, "skip-partial.part02.rar"),
|
||||||
|
resumable: true,
|
||||||
|
attempts: 0,
|
||||||
|
lastError: "",
|
||||||
|
fullStatus: "Wartet",
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now
|
||||||
|
};
|
||||||
|
|
||||||
|
const manager = new DownloadManager(
|
||||||
|
{
|
||||||
|
...defaultSettings(),
|
||||||
|
token: "rd-token",
|
||||||
|
outputDir: path.join(root, "downloads"),
|
||||||
|
extractDir: path.join(root, "extract")
|
||||||
|
},
|
||||||
|
session,
|
||||||
|
createStoragePaths(path.join(root, "state"))
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await manager.resolveStartConflict(packageId, "skip");
|
||||||
|
expect(result.skipped).toBe(true);
|
||||||
|
const snapshot = manager.getSnapshot();
|
||||||
|
expect(snapshot.session.packages[packageId]).toBeDefined();
|
||||||
|
expect(snapshot.session.items[completedItemId]?.status).toBe("completed");
|
||||||
|
expect(snapshot.session.items[completedItemId]?.fullStatus).toBe("Entpackt");
|
||||||
|
expect(snapshot.session.items[pendingItemId]?.status).toBe("queued");
|
||||||
|
expect(snapshot.session.items[pendingItemId]?.fullStatus).toBe("Wartet");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("resolves start conflict by overwriting and resetting queued package", async () => {
|
it("resolves start conflict by overwriting and resetting queued package", async () => {
|
||||||
@ -2388,7 +2495,7 @@ describe("download manager", () => {
|
|||||||
createStoragePaths(path.join(root, "state"))
|
createStoragePaths(path.join(root, "state"))
|
||||||
);
|
);
|
||||||
|
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 5000);
|
await waitFor(() => !manager.getSnapshot().session.running, 5000);
|
||||||
|
|
||||||
const snapshot = manager.getSnapshot();
|
const snapshot = manager.getSnapshot();
|
||||||
@ -2399,6 +2506,103 @@ describe("download manager", () => {
|
|||||||
expect(summary).toBeNull();
|
expect(summary).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("shows zero total when queue is empty despite stale persisted bytes", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
|
||||||
|
const session = emptySession();
|
||||||
|
session.totalDownloadedBytes = 19.99 * 1024 * 1024 * 1024;
|
||||||
|
session.runStartedAt = Date.now() - 5 * 60 * 1000;
|
||||||
|
|
||||||
|
const manager = new DownloadManager(
|
||||||
|
{
|
||||||
|
...defaultSettings(),
|
||||||
|
token: "rd-token",
|
||||||
|
outputDir: path.join(root, "downloads"),
|
||||||
|
extractDir: path.join(root, "extract"),
|
||||||
|
autoExtract: false
|
||||||
|
},
|
||||||
|
session,
|
||||||
|
createStoragePaths(path.join(root, "state"))
|
||||||
|
);
|
||||||
|
|
||||||
|
const snapshot = manager.getSnapshot();
|
||||||
|
expect(snapshot.stats.totalPackages).toBe(0);
|
||||||
|
expect(snapshot.stats.totalFiles).toBe(0);
|
||||||
|
expect(snapshot.stats.totalDownloaded).toBe(0);
|
||||||
|
expect(snapshot.session.totalDownloadedBytes).toBe(0);
|
||||||
|
expect(snapshot.session.runStartedAt).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clearAll resets total bytes and stats", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
|
||||||
|
const session = emptySession();
|
||||||
|
const packageId = "pkg-clear";
|
||||||
|
const itemId = "item-clear";
|
||||||
|
const now = Date.now() - 1000;
|
||||||
|
const outputDir = path.join(root, "downloads", "pkg-clear");
|
||||||
|
const extractDir = path.join(root, "extract", "pkg-clear");
|
||||||
|
const targetPath = path.join(outputDir, "episode.mkv");
|
||||||
|
|
||||||
|
session.packageOrder = [packageId];
|
||||||
|
session.packages[packageId] = {
|
||||||
|
id: packageId,
|
||||||
|
name: "pkg-clear",
|
||||||
|
outputDir,
|
||||||
|
extractDir,
|
||||||
|
status: "completed",
|
||||||
|
itemIds: [itemId],
|
||||||
|
cancelled: false,
|
||||||
|
enabled: true,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now
|
||||||
|
};
|
||||||
|
session.items[itemId] = {
|
||||||
|
id: itemId,
|
||||||
|
packageId,
|
||||||
|
url: "https://dummy/item-clear",
|
||||||
|
provider: "realdebrid",
|
||||||
|
status: "completed",
|
||||||
|
retries: 0,
|
||||||
|
speedBps: 0,
|
||||||
|
downloadedBytes: 1024,
|
||||||
|
totalBytes: 1024,
|
||||||
|
progressPercent: 100,
|
||||||
|
fileName: "episode.mkv",
|
||||||
|
targetPath,
|
||||||
|
resumable: true,
|
||||||
|
attempts: 1,
|
||||||
|
lastError: "",
|
||||||
|
fullStatus: "Fertig (1 KB)",
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now
|
||||||
|
};
|
||||||
|
session.totalDownloadedBytes = 1024;
|
||||||
|
session.runStartedAt = now;
|
||||||
|
|
||||||
|
const manager = new DownloadManager(
|
||||||
|
{
|
||||||
|
...defaultSettings(),
|
||||||
|
token: "rd-token",
|
||||||
|
outputDir: path.join(root, "downloads"),
|
||||||
|
extractDir: path.join(root, "extract"),
|
||||||
|
autoExtract: false
|
||||||
|
},
|
||||||
|
session,
|
||||||
|
createStoragePaths(path.join(root, "state"))
|
||||||
|
);
|
||||||
|
|
||||||
|
manager.clearAll();
|
||||||
|
const snapshot = manager.getSnapshot();
|
||||||
|
expect(snapshot.stats.totalPackages).toBe(0);
|
||||||
|
expect(snapshot.stats.totalFiles).toBe(0);
|
||||||
|
expect(snapshot.stats.totalDownloaded).toBe(0);
|
||||||
|
expect(snapshot.session.totalDownloadedBytes).toBe(0);
|
||||||
|
expect(snapshot.session.runStartedAt).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
it("does not start a run when queue is empty", async () => {
|
it("does not start a run when queue is empty", async () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
tempDirs.push(root);
|
tempDirs.push(root);
|
||||||
@ -2523,7 +2727,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "new", links: ["https://dummy/new"] }]);
|
manager.addPackages([{ name: "new", links: ["https://dummy/new"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await new Promise((resolve) => setTimeout(resolve, 120));
|
await new Promise((resolve) => setTimeout(resolve, 120));
|
||||||
|
|
||||||
const runningSnapshot = manager.getSnapshot();
|
const runningSnapshot = manager.getSnapshot();
|
||||||
@ -2601,7 +2805,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "fresh-retry", links: ["https://dummy/fresh"] }]);
|
manager.addPackages([{ name: "fresh-retry", links: ["https://dummy/fresh"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
||||||
|
|
||||||
const item = Object.values(manager.getSnapshot().session.items)[0];
|
const item = Object.values(manager.getSnapshot().session.items)[0];
|
||||||
@ -2686,7 +2890,7 @@ describe("download manager", () => {
|
|||||||
expect(extractDir).toBeTruthy();
|
expect(extractDir).toBeTruthy();
|
||||||
expect(fs.existsSync(extractDir)).toBe(false);
|
expect(fs.existsSync(extractDir)).toBe(false);
|
||||||
|
|
||||||
manager.start();
|
await manager.start();
|
||||||
await new Promise((resolve) => setTimeout(resolve, 140));
|
await new Promise((resolve) => setTimeout(resolve, 140));
|
||||||
expect(fs.existsSync(extractDir)).toBe(false);
|
expect(fs.existsSync(extractDir)).toBe(false);
|
||||||
|
|
||||||
@ -2695,14 +2899,14 @@ describe("download manager", () => {
|
|||||||
const snapshot = manager.getSnapshot();
|
const snapshot = manager.getSnapshot();
|
||||||
const item = Object.values(snapshot.session.items)[0];
|
const item = Object.values(snapshot.session.items)[0];
|
||||||
expect(item?.status).toBe("completed");
|
expect(item?.status).toBe("completed");
|
||||||
expect(item?.fullStatus).toBe("Entpackt");
|
expect(item?.fullStatus).toBe("Entpackt - Done");
|
||||||
expect(fs.existsSync(extractDir)).toBe(true);
|
expect(fs.existsSync(extractDir)).toBe(true);
|
||||||
expect(fs.existsSync(path.join(extractDir, "inside.txt"))).toBe(true);
|
expect(fs.existsSync(path.join(extractDir, "inside.txt"))).toBe(true);
|
||||||
} finally {
|
} finally {
|
||||||
server.close();
|
server.close();
|
||||||
await once(server, "close");
|
await once(server, "close");
|
||||||
}
|
}
|
||||||
});
|
}, 35000);
|
||||||
|
|
||||||
it("keeps accurate summary when completed items are cleaned immediately", async () => {
|
it("keeps accurate summary when completed items are cleaned immediately", async () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
@ -2763,7 +2967,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "cleanup", links: ["https://dummy/cleanup"] }]);
|
manager.addPackages([{ name: "cleanup", links: ["https://dummy/cleanup"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const snapshot = manager.getSnapshot();
|
const snapshot = manager.getSnapshot();
|
||||||
@ -2844,7 +3048,7 @@ describe("download manager", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
manager.addPackages([{ name: "cleanup-package", links: ["https://dummy/cleanup-package"] }]);
|
manager.addPackages([{ name: "cleanup-package", links: ["https://dummy/cleanup-package"] }]);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
await waitFor(() => !manager.getSnapshot().session.running, 30000);
|
||||||
|
|
||||||
const snapshot = manager.getSnapshot();
|
const snapshot = manager.getSnapshot();
|
||||||
@ -2857,7 +3061,7 @@ describe("download manager", () => {
|
|||||||
server.close();
|
server.close();
|
||||||
await once(server, "close");
|
await once(server, "close");
|
||||||
}
|
}
|
||||||
});
|
}, 35000);
|
||||||
|
|
||||||
it("counts queued package cancellations in run summary", async () => {
|
it("counts queued package cancellations in run summary", async () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
@ -3009,7 +3213,7 @@ describe("download manager", () => {
|
|||||||
const disabledItemId = initial.session.packages[disabledPkgId]?.itemIds[0] || "";
|
const disabledItemId = initial.session.packages[disabledPkgId]?.itemIds[0] || "";
|
||||||
|
|
||||||
manager.togglePackage(disabledPkgId);
|
manager.togglePackage(disabledPkgId);
|
||||||
manager.start();
|
await manager.start();
|
||||||
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
await waitFor(() => !manager.getSnapshot().session.running, 25000);
|
||||||
|
|
||||||
const snapshot = manager.getSnapshot();
|
const snapshot = manager.getSnapshot();
|
||||||
@ -3501,7 +3705,7 @@ describe("download manager", () => {
|
|||||||
await waitFor(() => fs.existsSync(path.join(extractDir, "episode.txt")), 25000);
|
await waitFor(() => fs.existsSync(path.join(extractDir, "episode.txt")), 25000);
|
||||||
const snapshot = manager.getSnapshot();
|
const snapshot = manager.getSnapshot();
|
||||||
expect(snapshot.session.packages[packageId]?.status).toBe("completed");
|
expect(snapshot.session.packages[packageId]?.status).toBe("completed");
|
||||||
expect(snapshot.session.items[itemId]?.fullStatus).toBe("Entpackt");
|
expect(snapshot.session.items[itemId]?.fullStatus).toBe("Entpackt - Done");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not fail startup post-processing when source package dir is missing but extract output exists", async () => {
|
it("does not fail startup post-processing when source package dir is missing but extract output exists", async () => {
|
||||||
@ -3568,7 +3772,7 @@ describe("download manager", () => {
|
|||||||
await waitFor(() => manager.getSnapshot().session.items[itemId]?.fullStatus.startsWith("Entpackt"), 12000);
|
await waitFor(() => manager.getSnapshot().session.items[itemId]?.fullStatus.startsWith("Entpackt"), 12000);
|
||||||
const snapshot = manager.getSnapshot();
|
const snapshot = manager.getSnapshot();
|
||||||
expect(snapshot.session.packages[packageId]?.status).toBe("completed");
|
expect(snapshot.session.packages[packageId]?.status).toBe("completed");
|
||||||
expect(snapshot.session.items[itemId]?.fullStatus).toBe("Entpackt");
|
expect(snapshot.session.items[itemId]?.fullStatus).toBe("Entpackt - Done");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("marks missing source package dir as extracted instead of failed", async () => {
|
it("marks missing source package dir as extracted instead of failed", async () => {
|
||||||
@ -3808,7 +4012,7 @@ describe("download manager", () => {
|
|||||||
await waitFor(() => fs.existsSync(expectedPath), 12000);
|
await waitFor(() => fs.existsSync(expectedPath), 12000);
|
||||||
const snapshot = manager.getSnapshot();
|
const snapshot = manager.getSnapshot();
|
||||||
expect(snapshot.session.packages[packageId]?.status).toBe("completed");
|
expect(snapshot.session.packages[packageId]?.status).toBe("completed");
|
||||||
expect(snapshot.session.items[itemId]?.fullStatus).toBe("Entpackt");
|
expect(snapshot.session.items[itemId]?.fullStatus).toBe("Entpackt - Done");
|
||||||
expect(fs.existsSync(expectedPath)).toBe(true);
|
expect(fs.existsSync(expectedPath)).toBe(true);
|
||||||
expect(fs.existsSync(originalExtractedPath)).toBe(false);
|
expect(fs.existsSync(originalExtractedPath)).toBe(false);
|
||||||
});
|
});
|
||||||
@ -3901,6 +4105,161 @@ describe("download manager", () => {
|
|||||||
expect(fs.existsSync(path.join(extractDir, unexpectedName))).toBe(false);
|
expect(fs.existsSync(path.join(extractDir, unexpectedName))).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("moves extracted MKV files into a flat library folder per completed package", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
|
||||||
|
const packageName = "Flat-Pack";
|
||||||
|
const sourceFileName = "Season 1/Episode01.mkv";
|
||||||
|
const { session, packageId, itemId, originalExtractedPath } = createCompletedArchiveSession(root, packageName, sourceFileName);
|
||||||
|
const mkvLibraryDir = path.join(root, "mkv-library");
|
||||||
|
|
||||||
|
const manager = new DownloadManager(
|
||||||
|
{
|
||||||
|
...defaultSettings(),
|
||||||
|
token: "rd-token",
|
||||||
|
outputDir: path.join(root, "downloads"),
|
||||||
|
extractDir: path.join(root, "extract"),
|
||||||
|
autoExtract: true,
|
||||||
|
autoRename4sf4sj: false,
|
||||||
|
collectMkvToLibrary: true,
|
||||||
|
mkvLibraryDir,
|
||||||
|
enableIntegrityCheck: false,
|
||||||
|
cleanupMode: "none"
|
||||||
|
},
|
||||||
|
session,
|
||||||
|
createStoragePaths(path.join(root, "state"))
|
||||||
|
);
|
||||||
|
|
||||||
|
const flattenedPath = path.join(mkvLibraryDir, "Episode01.mkv");
|
||||||
|
await waitFor(() => fs.existsSync(flattenedPath), 12000);
|
||||||
|
|
||||||
|
expect(manager.getSnapshot().session.packages[packageId]?.status).toBe("completed");
|
||||||
|
expect(manager.getSnapshot().session.items[itemId]?.fullStatus).toBe("Entpackt - Done");
|
||||||
|
expect(fs.existsSync(flattenedPath)).toBe(true);
|
||||||
|
expect(fs.existsSync(originalExtractedPath)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps existing MKV names and appends a suffix while flattening", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
|
||||||
|
const packageName = "Flat-Collision";
|
||||||
|
const sourceFileName = "Season 1/Episode01.mkv";
|
||||||
|
const { session } = createCompletedArchiveSession(root, packageName, sourceFileName);
|
||||||
|
const mkvLibraryDir = path.join(root, "mkv-library");
|
||||||
|
fs.mkdirSync(mkvLibraryDir, { recursive: true });
|
||||||
|
const existingPath = path.join(mkvLibraryDir, "Episode01.mkv");
|
||||||
|
fs.writeFileSync(existingPath, "already-here", "utf8");
|
||||||
|
|
||||||
|
new DownloadManager(
|
||||||
|
{
|
||||||
|
...defaultSettings(),
|
||||||
|
token: "rd-token",
|
||||||
|
outputDir: path.join(root, "downloads"),
|
||||||
|
extractDir: path.join(root, "extract"),
|
||||||
|
autoExtract: true,
|
||||||
|
autoRename4sf4sj: false,
|
||||||
|
collectMkvToLibrary: true,
|
||||||
|
mkvLibraryDir,
|
||||||
|
enableIntegrityCheck: false,
|
||||||
|
cleanupMode: "none"
|
||||||
|
},
|
||||||
|
session,
|
||||||
|
createStoragePaths(path.join(root, "state"))
|
||||||
|
);
|
||||||
|
|
||||||
|
const suffixedPath = path.join(mkvLibraryDir, "Episode01 (2).mkv");
|
||||||
|
await waitFor(() => fs.existsSync(suffixedPath), 12000);
|
||||||
|
|
||||||
|
expect(fs.existsSync(existingPath)).toBe(true);
|
||||||
|
expect(fs.readFileSync(existingPath, "utf8")).toBe("already-here");
|
||||||
|
expect(fs.existsSync(suffixedPath)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes empty package folders after MKV flattening even with desktop.ini or thumbs.db", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
|
||||||
|
const packageName = "Gotham.S03.GERMAN.5.1.DL.AC3.720p.BDRiP.x264-TvR";
|
||||||
|
const outputDir = path.join(root, "downloads", packageName);
|
||||||
|
const extractDir = path.join(root, "extract", packageName);
|
||||||
|
fs.mkdirSync(outputDir, { recursive: true });
|
||||||
|
|
||||||
|
const nestedFolder = "Gotham.S03E11.Ein.Ungeheuer.namens.Eifersucht.GERMAN.5.1.DL.AC3.720p.BDRiP.x264-TvR";
|
||||||
|
const sourceFileName = `${nestedFolder}/tvr-gotham-s03e11-720p.mkv`;
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile(sourceFileName, Buffer.from("video"));
|
||||||
|
zip.addFile(`${nestedFolder}/tvr-gotham-s03-720p.nfo`, Buffer.from("info"));
|
||||||
|
zip.addFile(`${nestedFolder}/Thumbs.db`, Buffer.from("thumbs"));
|
||||||
|
zip.addFile("desktop.ini", Buffer.from("system"));
|
||||||
|
const archivePath = path.join(outputDir, "episode.zip");
|
||||||
|
zip.writeZip(archivePath);
|
||||||
|
const archiveSize = fs.statSync(archivePath).size;
|
||||||
|
|
||||||
|
const session = emptySession();
|
||||||
|
const packageId = `${packageName}-pkg`;
|
||||||
|
const itemId = `${packageName}-item`;
|
||||||
|
const createdAt = Date.now() - 20_000;
|
||||||
|
session.packageOrder = [packageId];
|
||||||
|
session.packages[packageId] = {
|
||||||
|
id: packageId,
|
||||||
|
name: packageName,
|
||||||
|
outputDir,
|
||||||
|
extractDir,
|
||||||
|
status: "downloading",
|
||||||
|
itemIds: [itemId],
|
||||||
|
cancelled: false,
|
||||||
|
enabled: true,
|
||||||
|
createdAt,
|
||||||
|
updatedAt: createdAt
|
||||||
|
};
|
||||||
|
session.items[itemId] = {
|
||||||
|
id: itemId,
|
||||||
|
packageId,
|
||||||
|
url: "https://dummy/gotham",
|
||||||
|
provider: "realdebrid",
|
||||||
|
status: "completed",
|
||||||
|
retries: 0,
|
||||||
|
speedBps: 0,
|
||||||
|
downloadedBytes: archiveSize,
|
||||||
|
totalBytes: archiveSize,
|
||||||
|
progressPercent: 100,
|
||||||
|
fileName: "episode.zip",
|
||||||
|
targetPath: archivePath,
|
||||||
|
resumable: true,
|
||||||
|
attempts: 1,
|
||||||
|
lastError: "",
|
||||||
|
fullStatus: "Fertig",
|
||||||
|
createdAt,
|
||||||
|
updatedAt: createdAt
|
||||||
|
};
|
||||||
|
|
||||||
|
const mkvLibraryDir = path.join(root, "mkv-library");
|
||||||
|
new DownloadManager(
|
||||||
|
{
|
||||||
|
...defaultSettings(),
|
||||||
|
token: "rd-token",
|
||||||
|
outputDir: path.join(root, "downloads"),
|
||||||
|
extractDir: path.join(root, "extract"),
|
||||||
|
autoExtract: true,
|
||||||
|
autoRename4sf4sj: false,
|
||||||
|
collectMkvToLibrary: true,
|
||||||
|
mkvLibraryDir,
|
||||||
|
enableIntegrityCheck: false,
|
||||||
|
cleanupMode: "none"
|
||||||
|
},
|
||||||
|
session,
|
||||||
|
createStoragePaths(path.join(root, "state"))
|
||||||
|
);
|
||||||
|
|
||||||
|
const flattenedPath = path.join(mkvLibraryDir, "tvr-gotham-s03e11-720p.mkv");
|
||||||
|
await waitFor(() => fs.existsSync(flattenedPath), 12000);
|
||||||
|
|
||||||
|
expect(fs.existsSync(flattenedPath)).toBe(true);
|
||||||
|
expect(fs.existsSync(extractDir)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it("throws a controlled error for invalid queue import JSON", () => {
|
it("throws a controlled error for invalid queue import JSON", () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
tempDirs.push(root);
|
tempDirs.push(root);
|
||||||
@ -3947,7 +4306,7 @@ describe("download manager", () => {
|
|||||||
expect(internal.globalSpeedLimitNextAt).toBeGreaterThan(start);
|
expect(internal.globalSpeedLimitNextAt).toBeGreaterThan(start);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("resets speed window head when start finds no runnable items", () => {
|
it("resets speed window head when start finds no runnable items", async () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
tempDirs.push(root);
|
tempDirs.push(root);
|
||||||
|
|
||||||
@ -3971,12 +4330,69 @@ describe("download manager", () => {
|
|||||||
internal.speedEventsHead = 5;
|
internal.speedEventsHead = 5;
|
||||||
internal.speedBytesLastWindow = 999;
|
internal.speedBytesLastWindow = 999;
|
||||||
|
|
||||||
manager.start();
|
await manager.start();
|
||||||
expect(internal.speedEventsHead).toBe(0);
|
expect(internal.speedEventsHead).toBe(0);
|
||||||
expect(internal.speedEvents.length).toBe(0);
|
expect(internal.speedEvents.length).toBe(0);
|
||||||
expect(internal.speedBytesLastWindow).toBe(0);
|
expect(internal.speedBytesLastWindow).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("does not trigger global stall abort while write-buffer is disk-blocked", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const previousGlobalWatchdog = process.env.RD_GLOBAL_STALL_TIMEOUT_MS;
|
||||||
|
process.env.RD_GLOBAL_STALL_TIMEOUT_MS = "2500";
|
||||||
|
|
||||||
|
try {
|
||||||
|
const manager = new DownloadManager(
|
||||||
|
{
|
||||||
|
...defaultSettings(),
|
||||||
|
token: "rd-token",
|
||||||
|
outputDir: path.join(root, "downloads"),
|
||||||
|
extractDir: path.join(root, "extract")
|
||||||
|
},
|
||||||
|
emptySession(),
|
||||||
|
createStoragePaths(path.join(root, "state"))
|
||||||
|
);
|
||||||
|
|
||||||
|
manager.addPackages([{ name: "disk-block-guard", links: ["https://dummy/disk-block-guard"] }]);
|
||||||
|
const snapshot = manager.getSnapshot();
|
||||||
|
const packageId = snapshot.session.packageOrder[0] || "";
|
||||||
|
const itemId = snapshot.session.packages[packageId]?.itemIds[0] || "";
|
||||||
|
|
||||||
|
const internal = manager as unknown as any;
|
||||||
|
internal.session.running = true;
|
||||||
|
internal.session.paused = false;
|
||||||
|
internal.session.reconnectUntil = 0;
|
||||||
|
internal.session.totalDownloadedBytes = 0;
|
||||||
|
internal.session.items[itemId].status = "downloading";
|
||||||
|
internal.lastGlobalProgressBytes = 0;
|
||||||
|
internal.lastGlobalProgressAt = Date.now() - 10000;
|
||||||
|
|
||||||
|
const abortController = new AbortController();
|
||||||
|
internal.activeTasks.set(itemId, {
|
||||||
|
itemId,
|
||||||
|
packageId,
|
||||||
|
abortController,
|
||||||
|
abortReason: "none",
|
||||||
|
resumable: true,
|
||||||
|
nonResumableCounted: false,
|
||||||
|
blockedOnDiskWrite: true,
|
||||||
|
blockedOnDiskSince: Date.now() - 5000
|
||||||
|
});
|
||||||
|
|
||||||
|
internal.runGlobalStallWatchdog(Date.now());
|
||||||
|
|
||||||
|
expect(abortController.signal.aborted).toBe(false);
|
||||||
|
expect(internal.lastGlobalProgressAt).toBeGreaterThan(Date.now() - 2000);
|
||||||
|
} finally {
|
||||||
|
if (previousGlobalWatchdog === undefined) {
|
||||||
|
delete process.env.RD_GLOBAL_STALL_TIMEOUT_MS;
|
||||||
|
} else {
|
||||||
|
process.env.RD_GLOBAL_STALL_TIMEOUT_MS = previousGlobalWatchdog;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("cleans run tracking when start conflict is skipped", async () => {
|
it("cleans run tracking when start conflict is skipped", async () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dm-"));
|
||||||
tempDirs.push(root);
|
tempDirs.push(root);
|
||||||
|
|||||||
204
tests/extractor-jvm.test.ts
Normal file
204
tests/extractor-jvm.test.ts
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import AdmZip from "adm-zip";
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
import { extractPackageArchives } from "../src/main/extractor";
|
||||||
|
|
||||||
|
const tempDirs: string[] = [];
|
||||||
|
const originalBackend = process.env.RD_EXTRACT_BACKEND;
|
||||||
|
|
||||||
|
function hasJavaRuntime(): boolean {
|
||||||
|
const result = spawnSync("java", ["-version"], { stdio: "ignore" });
|
||||||
|
return result.status === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasJvmExtractorRuntime(): boolean {
|
||||||
|
const root = path.join(process.cwd(), "resources", "extractor-jvm");
|
||||||
|
const classesMain = path.join(root, "classes", "com", "sucukdeluxe", "extractor", "JBindExtractorMain.class");
|
||||||
|
const requiredLibs = [
|
||||||
|
path.join(root, "lib", "sevenzipjbinding.jar"),
|
||||||
|
path.join(root, "lib", "sevenzipjbinding-all-platforms.jar"),
|
||||||
|
path.join(root, "lib", "zip4j.jar")
|
||||||
|
];
|
||||||
|
return fs.existsSync(classesMain) && requiredLibs.every((libPath) => fs.existsSync(libPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const dir of tempDirs.splice(0)) {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
if (originalBackend === undefined) {
|
||||||
|
delete process.env.RD_EXTRACT_BACKEND;
|
||||||
|
} else {
|
||||||
|
process.env.RD_EXTRACT_BACKEND = originalBackend;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe.skipIf(!hasJavaRuntime() || !hasJvmExtractorRuntime())("extractor jvm backend", () => {
|
||||||
|
it("extracts zip archives through SevenZipJBinding backend", async () => {
|
||||||
|
process.env.RD_EXTRACT_BACKEND = "jvm";
|
||||||
|
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-jvm-extract-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
const zipPath = path.join(packageDir, "release.zip");
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile("episode.txt", Buffer.from("ok"));
|
||||||
|
zip.writeZip(zipPath);
|
||||||
|
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none",
|
||||||
|
conflictMode: "overwrite",
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(1);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
expect(fs.existsSync(path.join(targetDir, "episode.txt"))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emits progress callbacks with archiveName and percent", async () => {
|
||||||
|
process.env.RD_EXTRACT_BACKEND = "jvm";
|
||||||
|
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-jvm-progress-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
// Create a ZIP with some content to trigger progress
|
||||||
|
const zipPath = path.join(packageDir, "progress-test.zip");
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile("file1.txt", Buffer.from("Hello World ".repeat(100)));
|
||||||
|
zip.addFile("file2.txt", Buffer.from("Another file ".repeat(100)));
|
||||||
|
zip.writeZip(zipPath);
|
||||||
|
|
||||||
|
const progressUpdates: Array<{
|
||||||
|
archiveName: string;
|
||||||
|
percent: number;
|
||||||
|
phase: string;
|
||||||
|
archivePercent?: number;
|
||||||
|
}> = [];
|
||||||
|
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none",
|
||||||
|
conflictMode: "overwrite",
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
onProgress: (update) => {
|
||||||
|
progressUpdates.push({
|
||||||
|
archiveName: update.archiveName,
|
||||||
|
percent: update.percent,
|
||||||
|
phase: update.phase,
|
||||||
|
archivePercent: update.archivePercent,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(1);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
|
||||||
|
// Should have at least preparing, extracting, and done phases
|
||||||
|
const phases = new Set(progressUpdates.map((u) => u.phase));
|
||||||
|
expect(phases.has("preparing")).toBe(true);
|
||||||
|
expect(phases.has("extracting")).toBe(true);
|
||||||
|
|
||||||
|
// Extracting phase should include the archive name
|
||||||
|
const extracting = progressUpdates.filter((u) => u.phase === "extracting" && u.archiveName === "progress-test.zip");
|
||||||
|
expect(extracting.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
// Should end at 100%
|
||||||
|
const lastExtracting = extracting[extracting.length - 1];
|
||||||
|
expect(lastExtracting.archivePercent).toBe(100);
|
||||||
|
|
||||||
|
// Files should exist
|
||||||
|
expect(fs.existsSync(path.join(targetDir, "file1.txt"))).toBe(true);
|
||||||
|
expect(fs.existsSync(path.join(targetDir, "file2.txt"))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("extracts multiple archives sequentially with progress for each", async () => {
|
||||||
|
process.env.RD_EXTRACT_BACKEND = "jvm";
|
||||||
|
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-jvm-multi-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
// Create two separate ZIP archives
|
||||||
|
const zip1 = new AdmZip();
|
||||||
|
zip1.addFile("episode01.txt", Buffer.from("ep1 content"));
|
||||||
|
zip1.writeZip(path.join(packageDir, "archive1.zip"));
|
||||||
|
|
||||||
|
const zip2 = new AdmZip();
|
||||||
|
zip2.addFile("episode02.txt", Buffer.from("ep2 content"));
|
||||||
|
zip2.writeZip(path.join(packageDir, "archive2.zip"));
|
||||||
|
|
||||||
|
const archiveNames = new Set<string>();
|
||||||
|
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none",
|
||||||
|
conflictMode: "overwrite",
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
onProgress: (update) => {
|
||||||
|
if (update.phase === "extracting" && update.archiveName) {
|
||||||
|
archiveNames.add(update.archiveName);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(2);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
// Both archive names should have appeared in progress
|
||||||
|
expect(archiveNames.has("archive1.zip")).toBe(true);
|
||||||
|
expect(archiveNames.has("archive2.zip")).toBe(true);
|
||||||
|
// Both files extracted
|
||||||
|
expect(fs.existsSync(path.join(targetDir, "episode01.txt"))).toBe(true);
|
||||||
|
expect(fs.existsSync(path.join(targetDir, "episode02.txt"))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("respects ask/skip conflict mode in jvm backend", async () => {
|
||||||
|
process.env.RD_EXTRACT_BACKEND = "jvm";
|
||||||
|
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-jvm-extract-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
fs.mkdirSync(targetDir, { recursive: true });
|
||||||
|
|
||||||
|
const zipPath = path.join(packageDir, "conflict.zip");
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile("same.txt", Buffer.from("new"));
|
||||||
|
zip.writeZip(zipPath);
|
||||||
|
|
||||||
|
const existingPath = path.join(targetDir, "same.txt");
|
||||||
|
fs.writeFileSync(existingPath, "old", "utf8");
|
||||||
|
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none",
|
||||||
|
conflictMode: "ask",
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(1);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
expect(fs.readFileSync(existingPath, "utf8")).toBe("old");
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -2,15 +2,41 @@ import fs from "node:fs";
|
|||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import AdmZip from "adm-zip";
|
import AdmZip from "adm-zip";
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
import { buildExternalExtractArgs, collectArchiveCleanupTargets, extractPackageArchives } from "../src/main/extractor";
|
import {
|
||||||
|
buildExternalExtractArgs,
|
||||||
|
collectArchiveCleanupTargets,
|
||||||
|
extractPackageArchives,
|
||||||
|
archiveFilenamePasswords,
|
||||||
|
detectArchiveSignature,
|
||||||
|
classifyExtractionError,
|
||||||
|
findArchiveCandidates,
|
||||||
|
} from "../src/main/extractor";
|
||||||
|
|
||||||
const tempDirs: string[] = [];
|
const tempDirs: string[] = [];
|
||||||
|
const originalExtractBackend = process.env.RD_EXTRACT_BACKEND;
|
||||||
|
const originalStatfs = fs.promises.statfs;
|
||||||
|
const originalZipEntryMemoryLimit = process.env.RD_ZIP_ENTRY_MEMORY_LIMIT_MB;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
process.env.RD_EXTRACT_BACKEND = "legacy";
|
||||||
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
for (const dir of tempDirs.splice(0)) {
|
for (const dir of tempDirs.splice(0)) {
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
|
if (originalExtractBackend === undefined) {
|
||||||
|
delete process.env.RD_EXTRACT_BACKEND;
|
||||||
|
} else {
|
||||||
|
process.env.RD_EXTRACT_BACKEND = originalExtractBackend;
|
||||||
|
}
|
||||||
|
(fs.promises as any).statfs = originalStatfs;
|
||||||
|
if (originalZipEntryMemoryLimit === undefined) {
|
||||||
|
delete process.env.RD_ZIP_ENTRY_MEMORY_LIMIT_MB;
|
||||||
|
} else {
|
||||||
|
process.env.RD_ZIP_ENTRY_MEMORY_LIMIT_MB = originalZipEntryMemoryLimit;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("extractor", () => {
|
describe("extractor", () => {
|
||||||
@ -555,8 +581,7 @@ describe("extractor", () => {
|
|||||||
expect(targets.has(r02)).toBe(true);
|
expect(targets.has(r02)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not fallback to external extractor when ZIP safety guard triggers", async () => {
|
it("keeps original ZIP size guard error when external fallback is unavailable", async () => {
|
||||||
const previousLimit = process.env.RD_ZIP_ENTRY_MEMORY_LIMIT_MB;
|
|
||||||
process.env.RD_ZIP_ENTRY_MEMORY_LIMIT_MB = "8";
|
process.env.RD_ZIP_ENTRY_MEMORY_LIMIT_MB = "8";
|
||||||
|
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-extract-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-extract-"));
|
||||||
@ -570,7 +595,6 @@ describe("extractor", () => {
|
|||||||
zip.addFile("large.bin", Buffer.alloc(9 * 1024 * 1024, 7));
|
zip.addFile("large.bin", Buffer.alloc(9 * 1024 * 1024, 7));
|
||||||
zip.writeZip(zipPath);
|
zip.writeZip(zipPath);
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await extractPackageArchives({
|
const result = await extractPackageArchives({
|
||||||
packageDir,
|
packageDir,
|
||||||
targetDir,
|
targetDir,
|
||||||
@ -582,20 +606,9 @@ describe("extractor", () => {
|
|||||||
expect(result.extracted).toBe(0);
|
expect(result.extracted).toBe(0);
|
||||||
expect(result.failed).toBe(1);
|
expect(result.failed).toBe(1);
|
||||||
expect(String(result.lastError)).toMatch(/ZIP-Eintrag.*groß/i);
|
expect(String(result.lastError)).toMatch(/ZIP-Eintrag.*groß/i);
|
||||||
} finally {
|
|
||||||
if (previousLimit === undefined) {
|
|
||||||
delete process.env.RD_ZIP_ENTRY_MEMORY_LIMIT_MB;
|
|
||||||
} else {
|
|
||||||
process.env.RD_ZIP_ENTRY_MEMORY_LIMIT_MB = previousLimit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("matches resume-state archive names case-insensitively on Windows", async () => {
|
it.skipIf(process.platform !== "win32")("matches resume-state archive names case-insensitively on Windows", async () => {
|
||||||
if (process.platform !== "win32") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-extract-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-extract-"));
|
||||||
tempDirs.push(root);
|
tempDirs.push(root);
|
||||||
const packageDir = path.join(root, "pkg");
|
const packageDir = path.join(root, "pkg");
|
||||||
@ -618,4 +631,459 @@ describe("extractor", () => {
|
|||||||
expect(result.extracted).toBe(1);
|
expect(result.extracted).toBe(1);
|
||||||
expect(result.failed).toBe(0);
|
expect(result.failed).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("disk space check", () => {
|
||||||
|
it("aborts extraction when disk space is insufficient", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-diskspace-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
fs.mkdirSync(targetDir, { recursive: true });
|
||||||
|
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile("test.txt", Buffer.alloc(1024, 0x41));
|
||||||
|
zip.writeZip(path.join(packageDir, "test.zip"));
|
||||||
|
|
||||||
|
(fs.promises as any).statfs = async () => ({ bfree: 1, bsize: 1 });
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none" as any,
|
||||||
|
conflictMode: "overwrite" as any,
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
})
|
||||||
|
).rejects.toThrow(/Nicht genug Speicherplatz/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("proceeds when disk space is sufficient", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-diskspace-ok-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
fs.mkdirSync(targetDir, { recursive: true });
|
||||||
|
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile("test.txt", Buffer.alloc(1024, 0x41));
|
||||||
|
zip.writeZip(path.join(packageDir, "test.zip"));
|
||||||
|
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none" as any,
|
||||||
|
conflictMode: "overwrite" as any,
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
});
|
||||||
|
expect(result.extracted).toBe(1);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("nested extraction", () => {
|
||||||
|
it("extracts archives found inside extracted output", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-nested-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
fs.mkdirSync(targetDir, { recursive: true });
|
||||||
|
|
||||||
|
const innerZip = new AdmZip();
|
||||||
|
innerZip.addFile("deep.txt", Buffer.from("deep content"));
|
||||||
|
|
||||||
|
const outerZip = new AdmZip();
|
||||||
|
outerZip.addFile("inner.zip", innerZip.toBuffer());
|
||||||
|
outerZip.writeZip(path.join(packageDir, "outer.zip"));
|
||||||
|
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none" as any,
|
||||||
|
conflictMode: "overwrite" as any,
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(2);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
expect(fs.existsSync(path.join(targetDir, "deep.txt"))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not extract blacklisted extensions like .iso", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-nested-bl-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
fs.mkdirSync(targetDir, { recursive: true });
|
||||||
|
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile("disc.iso", Buffer.alloc(64, 0));
|
||||||
|
zip.addFile("readme.txt", Buffer.from("hello"));
|
||||||
|
zip.writeZip(path.join(packageDir, "package.zip"));
|
||||||
|
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none" as any,
|
||||||
|
conflictMode: "overwrite" as any,
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(1);
|
||||||
|
expect(fs.existsSync(path.join(targetDir, "disc.iso"))).toBe(true);
|
||||||
|
expect(fs.existsSync(path.join(targetDir, "readme.txt"))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("archiveFilenamePasswords", () => {
|
||||||
|
it("extracts stem and spaced variant from archive name", () => {
|
||||||
|
const result = archiveFilenamePasswords("MyRelease.S01E01.rar");
|
||||||
|
expect(result).toContain("MyRelease.S01E01");
|
||||||
|
expect(result).toContain("MyRelease S01E01");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips multipart rar suffix", () => {
|
||||||
|
const result = archiveFilenamePasswords("Show.S02E03.part01.rar");
|
||||||
|
expect(result).toContain("Show.S02E03");
|
||||||
|
expect(result).toContain("Show S02E03");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips .zip.001 suffix", () => {
|
||||||
|
const result = archiveFilenamePasswords("Movie.2024.zip.001");
|
||||||
|
expect(result).toContain("Movie.2024");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips .tar.gz suffix", () => {
|
||||||
|
const result = archiveFilenamePasswords("backup.tar.gz");
|
||||||
|
expect(result).toContain("backup");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns empty array for empty input", () => {
|
||||||
|
expect(archiveFilenamePasswords("")).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns single entry when no dots/underscores", () => {
|
||||||
|
const result = archiveFilenamePasswords("simple.zip");
|
||||||
|
expect(result).toEqual(["simple"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replaces underscores with spaces", () => {
|
||||||
|
const result = archiveFilenamePasswords("my_archive_name.7z");
|
||||||
|
expect(result).toContain("my_archive_name");
|
||||||
|
expect(result).toContain("my archive name");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe(".rev cleanup", () => {
|
||||||
|
it("collects .rev files for single RAR cleanup", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-rev-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
const mainRar = path.join(packageDir, "show.rar");
|
||||||
|
const rev = path.join(packageDir, "show.rev");
|
||||||
|
const r00 = path.join(packageDir, "show.r00");
|
||||||
|
|
||||||
|
fs.writeFileSync(mainRar, "a", "utf8");
|
||||||
|
fs.writeFileSync(rev, "b", "utf8");
|
||||||
|
fs.writeFileSync(r00, "c", "utf8");
|
||||||
|
|
||||||
|
const targets = new Set(collectArchiveCleanupTargets(mainRar));
|
||||||
|
expect(targets.has(mainRar)).toBe(true);
|
||||||
|
expect(targets.has(rev)).toBe(true);
|
||||||
|
expect(targets.has(r00)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("collects .rev files for multipart RAR cleanup", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-rev-mp-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
const part1 = path.join(packageDir, "show.part01.rar");
|
||||||
|
const part2 = path.join(packageDir, "show.part02.rar");
|
||||||
|
const rev = path.join(packageDir, "show.rev");
|
||||||
|
|
||||||
|
fs.writeFileSync(part1, "a", "utf8");
|
||||||
|
fs.writeFileSync(part2, "b", "utf8");
|
||||||
|
fs.writeFileSync(rev, "c", "utf8");
|
||||||
|
|
||||||
|
const targets = new Set(collectArchiveCleanupTargets(part1));
|
||||||
|
expect(targets.has(part1)).toBe(true);
|
||||||
|
expect(targets.has(part2)).toBe(true);
|
||||||
|
expect(targets.has(rev)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("generic .001 split cleanup", () => {
|
||||||
|
it("collects all numbered parts for generic splits", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-split-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
const p001 = path.join(packageDir, "movie.001");
|
||||||
|
const p002 = path.join(packageDir, "movie.002");
|
||||||
|
const p003 = path.join(packageDir, "movie.003");
|
||||||
|
const other = path.join(packageDir, "other.001");
|
||||||
|
|
||||||
|
fs.writeFileSync(p001, "a", "utf8");
|
||||||
|
fs.writeFileSync(p002, "b", "utf8");
|
||||||
|
fs.writeFileSync(p003, "c", "utf8");
|
||||||
|
fs.writeFileSync(other, "x", "utf8");
|
||||||
|
|
||||||
|
const targets = new Set(collectArchiveCleanupTargets(p001));
|
||||||
|
expect(targets.has(p001)).toBe(true);
|
||||||
|
expect(targets.has(p002)).toBe(true);
|
||||||
|
expect(targets.has(p003)).toBe(true);
|
||||||
|
expect(targets.has(other)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("detectArchiveSignature", () => {
|
||||||
|
it("detects RAR signature", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-sig-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const filePath = path.join(root, "test.rar");
|
||||||
|
// RAR5 signature: 52 61 72 21 1A 07
|
||||||
|
fs.writeFileSync(filePath, Buffer.from("526172211a0700", "hex"));
|
||||||
|
const sig = await detectArchiveSignature(filePath);
|
||||||
|
expect(sig).toBe("rar");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("detects ZIP signature", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-sig-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const filePath = path.join(root, "test.zip");
|
||||||
|
fs.writeFileSync(filePath, Buffer.from("504b030414000000", "hex"));
|
||||||
|
const sig = await detectArchiveSignature(filePath);
|
||||||
|
expect(sig).toBe("zip");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("detects 7z signature", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-sig-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const filePath = path.join(root, "test.7z");
|
||||||
|
fs.writeFileSync(filePath, Buffer.from("377abcaf271c0004", "hex"));
|
||||||
|
const sig = await detectArchiveSignature(filePath);
|
||||||
|
expect(sig).toBe("7z");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for non-archive files", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-sig-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const filePath = path.join(root, "test.txt");
|
||||||
|
fs.writeFileSync(filePath, "Hello World", "utf8");
|
||||||
|
const sig = await detectArchiveSignature(filePath);
|
||||||
|
expect(sig).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for non-existent file", async () => {
|
||||||
|
const sig = await detectArchiveSignature("/nonexistent/file.rar");
|
||||||
|
expect(sig).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("findArchiveCandidates extended formats", () => {
|
||||||
|
it("finds .tar.gz files", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-tar-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(packageDir, "backup.tar.gz"), "data", "utf8");
|
||||||
|
fs.writeFileSync(path.join(packageDir, "readme.txt"), "info", "utf8");
|
||||||
|
|
||||||
|
const candidates = await findArchiveCandidates(packageDir);
|
||||||
|
expect(candidates.map((c) => path.basename(c))).toContain("backup.tar.gz");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("finds .tar.bz2 files", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-tar-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(packageDir, "archive.tar.bz2"), "data", "utf8");
|
||||||
|
|
||||||
|
const candidates = await findArchiveCandidates(packageDir);
|
||||||
|
expect(candidates.map((c) => path.basename(c))).toContain("archive.tar.bz2");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("finds generic .001 split files", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-split-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(packageDir, "movie.001"), "data", "utf8");
|
||||||
|
fs.writeFileSync(path.join(packageDir, "movie.002"), "data", "utf8");
|
||||||
|
|
||||||
|
const candidates = await findArchiveCandidates(packageDir);
|
||||||
|
const names = candidates.map((c) => path.basename(c));
|
||||||
|
expect(names).toContain("movie.001");
|
||||||
|
// .002 should NOT be in candidates (only .001 is the entry point)
|
||||||
|
expect(names).not.toContain("movie.002");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not duplicate .zip.001 as generic split", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-dedup-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(packageDir, "movie.zip.001"), "data", "utf8");
|
||||||
|
fs.writeFileSync(path.join(packageDir, "movie.zip.002"), "data", "utf8");
|
||||||
|
|
||||||
|
const candidates = await findArchiveCandidates(packageDir);
|
||||||
|
const names = candidates.map((c) => path.basename(c));
|
||||||
|
// .zip.001 should appear once from zipSplit detection, not duplicated by genericSplit
|
||||||
|
expect(names.filter((n) => n === "movie.zip.001")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("classifyExtractionError", () => {
|
||||||
|
it("classifies CRC errors", () => {
|
||||||
|
expect(classifyExtractionError("CRC failed for file.txt")).toBe("crc_error");
|
||||||
|
expect(classifyExtractionError("Checksum error in data")).toBe("crc_error");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("classifies wrong password", () => {
|
||||||
|
expect(classifyExtractionError("Wrong password")).toBe("wrong_password");
|
||||||
|
expect(classifyExtractionError("Falsches Passwort")).toBe("wrong_password");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("classifies missing parts", () => {
|
||||||
|
expect(classifyExtractionError("Missing volume: part2.rar")).toBe("missing_parts");
|
||||||
|
expect(classifyExtractionError("Unexpected end of archive")).toBe("missing_parts");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("classifies unsupported format", () => {
|
||||||
|
expect(classifyExtractionError("kein RAR-Archiv")).toBe("unsupported_format");
|
||||||
|
expect(classifyExtractionError("UNSUPPORTEDMETHOD")).toBe("unsupported_format");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("classifies disk full", () => {
|
||||||
|
expect(classifyExtractionError("Nicht genug Speicherplatz")).toBe("disk_full");
|
||||||
|
expect(classifyExtractionError("No space left on device")).toBe("disk_full");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("classifies timeout", () => {
|
||||||
|
expect(classifyExtractionError("Entpacken Timeout nach 360s")).toBe("timeout");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("classifies abort", () => {
|
||||||
|
expect(classifyExtractionError("aborted:extract")).toBe("aborted");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("classifies no extractor", () => {
|
||||||
|
expect(classifyExtractionError("WinRAR/UnRAR nicht gefunden")).toBe("no_extractor");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns unknown for unrecognized errors", () => {
|
||||||
|
expect(classifyExtractionError("something weird happened")).toBe("unknown");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("password discovery", () => {
|
||||||
|
it("extracts first archive serially before parallel pool when multiple passwords", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-pwdisc-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
// Create 3 zip archives
|
||||||
|
for (const name of ["ep01.zip", "ep02.zip", "ep03.zip"]) {
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile(`${name}.txt`, Buffer.from(name));
|
||||||
|
zip.writeZip(path.join(packageDir, name));
|
||||||
|
}
|
||||||
|
|
||||||
|
const seenOrder: string[] = [];
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none",
|
||||||
|
conflictMode: "overwrite",
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
maxParallel: 2,
|
||||||
|
passwordList: "pw1|pw2|pw3",
|
||||||
|
onProgress: (update) => {
|
||||||
|
if (update.phase !== "extracting" || !update.archiveName) return;
|
||||||
|
if (seenOrder[seenOrder.length - 1] !== update.archiveName) {
|
||||||
|
seenOrder.push(update.archiveName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(3);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
// First archive should be ep01 (natural order, extracted serially for discovery)
|
||||||
|
expect(seenOrder[0]).toBe("ep01.zip");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips discovery when only one password candidate", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-pwdisc-skip-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
for (const name of ["a.zip", "b.zip"]) {
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile(`${name}.txt`, Buffer.from(name));
|
||||||
|
zip.writeZip(path.join(packageDir, name));
|
||||||
|
}
|
||||||
|
|
||||||
|
// No passwordList → only empty string → length=1 → no discovery phase
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none",
|
||||||
|
conflictMode: "overwrite",
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
maxParallel: 4
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(2);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips discovery when only one archive", async () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rd-pwdisc-one-"));
|
||||||
|
tempDirs.push(root);
|
||||||
|
const packageDir = path.join(root, "pkg");
|
||||||
|
const targetDir = path.join(root, "out");
|
||||||
|
fs.mkdirSync(packageDir, { recursive: true });
|
||||||
|
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile("single.txt", Buffer.from("single"));
|
||||||
|
zip.writeZip(path.join(packageDir, "only.zip"));
|
||||||
|
|
||||||
|
const result = await extractPackageArchives({
|
||||||
|
packageDir,
|
||||||
|
targetDir,
|
||||||
|
cleanupMode: "none",
|
||||||
|
conflictMode: "overwrite",
|
||||||
|
removeLinks: false,
|
||||||
|
removeSamples: false,
|
||||||
|
maxParallel: 4,
|
||||||
|
passwordList: "pw1|pw2|pw3"
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.extracted).toBe(1);
|
||||||
|
expect(result.failed).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
74
tests/link-parser.test.ts
Normal file
74
tests/link-parser.test.ts
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { mergePackageInputs, parseCollectorInput } from "../src/main/link-parser";
|
||||||
|
|
||||||
|
describe("link-parser", () => {
|
||||||
|
describe("mergePackageInputs", () => {
|
||||||
|
it("merges packages with the same name and preserves order", () => {
|
||||||
|
const input = [
|
||||||
|
{ name: "Package A", links: ["http://link1", "http://link2"] },
|
||||||
|
{ name: "Package B", links: ["http://link3"] },
|
||||||
|
{ name: "Package A", links: ["http://link4", "http://link1"] },
|
||||||
|
{ name: "", links: ["http://link5"] } // empty name will be inferred
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = mergePackageInputs(input);
|
||||||
|
|
||||||
|
expect(result).toHaveLength(3); // Package A, Package B, and inferred 'Paket'
|
||||||
|
|
||||||
|
const pkgA = result.find(p => p.name === "Package A");
|
||||||
|
expect(pkgA?.links).toEqual(["http://link1", "http://link2", "http://link4"]); // link1 deduplicated
|
||||||
|
|
||||||
|
const pkgB = result.find(p => p.name === "Package B");
|
||||||
|
expect(pkgB?.links).toEqual(["http://link3"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sanitizes names during merge", () => {
|
||||||
|
const input = [
|
||||||
|
{ name: "Valid_Name", links: ["http://link1"] },
|
||||||
|
{ name: "Valid?Name*", links: ["http://link2"] }
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = mergePackageInputs(input);
|
||||||
|
|
||||||
|
// "Valid?Name*" becomes "Valid Name " -> trimmed to "Valid Name"
|
||||||
|
expect(result.map(p => p.name).sort()).toEqual(["Valid Name", "Valid_Name"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("parseCollectorInput", () => {
|
||||||
|
it("returns empty array for empty or invalid input", () => {
|
||||||
|
expect(parseCollectorInput("")).toEqual([]);
|
||||||
|
expect(parseCollectorInput("just some text without links")).toEqual([]);
|
||||||
|
expect(parseCollectorInput("ftp://notsupported")).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses and merges links from raw text", () => {
|
||||||
|
const rawText = `
|
||||||
|
Here are some links:
|
||||||
|
http://example.com/part1.rar
|
||||||
|
http://example.com/part2.rar
|
||||||
|
|
||||||
|
# package: Custom_Name
|
||||||
|
http://other.com/file1
|
||||||
|
http://other.com/file2
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = parseCollectorInput(rawText, "DefaultFallback");
|
||||||
|
|
||||||
|
// Should have 2 packages: "DefaultFallback" and "Custom_Name"
|
||||||
|
expect(result).toHaveLength(2);
|
||||||
|
|
||||||
|
const defaultPkg = result.find(p => p.name === "DefaultFallback");
|
||||||
|
expect(defaultPkg?.links).toEqual([
|
||||||
|
"http://example.com/part1.rar",
|
||||||
|
"http://example.com/part2.rar"
|
||||||
|
]);
|
||||||
|
|
||||||
|
const customPkg = result.find(p => p.name === "Custom_Name"); // sanitized!
|
||||||
|
expect(customPkg?.links).toEqual([
|
||||||
|
"http://other.com/file1",
|
||||||
|
"http://other.com/file2"
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
178
tests/mega-web-fallback.test.ts
Normal file
178
tests/mega-web-fallback.test.ts
Normal file
@ -0,0 +1,178 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { MegaWebFallback } from "../src/main/mega-web-fallback";
|
||||||
|
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
|
||||||
|
describe("mega-web-fallback", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("MegaWebFallback class", () => {
|
||||||
|
it("returns null when credentials are empty", async () => {
|
||||||
|
const fallback = new MegaWebFallback(() => ({ login: "", password: "" }));
|
||||||
|
const result = await fallback.unrestrict("https://mega.debrid/test");
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("logs in, fetches HTML, parses code, and polls AJAX for direct url", async () => {
|
||||||
|
let fetchCallCount = 0;
|
||||||
|
globalThis.fetch = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
fetchCallCount += 1;
|
||||||
|
|
||||||
|
if (urlStr.includes("form=login")) {
|
||||||
|
const headers = new Headers();
|
||||||
|
headers.append("set-cookie", "session=goodcookie; path=/");
|
||||||
|
return new Response("", { headers, status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (urlStr.includes("page=debrideur")) {
|
||||||
|
return new Response('<form id="debridForm"></form>', { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (urlStr.includes("form=debrid")) {
|
||||||
|
// The POST to generate the code
|
||||||
|
return new Response(`
|
||||||
|
<div class="acp-box">
|
||||||
|
<h3>Link: https://mega.debrid/link1</h3>
|
||||||
|
<a href="javascript:processDebrid(1,'secretcode123',0)">Download</a>
|
||||||
|
</div>
|
||||||
|
`, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (urlStr.includes("ajax=debrid")) {
|
||||||
|
// Polling endpoint
|
||||||
|
return new Response(JSON.stringify({ link: "https://mega.direct/123" }), { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response("Not found", { status: 404 });
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const fallback = new MegaWebFallback(() => ({ login: "user", password: "pwd" }));
|
||||||
|
|
||||||
|
const result = await fallback.unrestrict("https://mega.debrid/link1");
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result?.directUrl).toBe("https://mega.direct/123");
|
||||||
|
expect(result?.fileName).toBe("link1");
|
||||||
|
// Calls: 1. Login POST, 2. Verify GET, 3. Generate POST, 4. Polling POST
|
||||||
|
expect(fetchCallCount).toBe(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws if login fails to set cookie", async () => {
|
||||||
|
globalThis.fetch = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("form=login")) {
|
||||||
|
const headers = new Headers(); // No cookie
|
||||||
|
return new Response("", { headers, status: 200 });
|
||||||
|
}
|
||||||
|
return new Response("Not found", { status: 404 });
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const fallback = new MegaWebFallback(() => ({ login: "bad", password: "bad" }));
|
||||||
|
|
||||||
|
await expect(fallback.unrestrict("http://mega.debrid/file"))
|
||||||
|
.rejects.toThrow("Mega-Web Login liefert kein Session-Cookie");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws if login verify check fails (no form found)", async () => {
|
||||||
|
globalThis.fetch = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
if (urlStr.includes("form=login")) {
|
||||||
|
const headers = new Headers();
|
||||||
|
headers.append("set-cookie", "session=goodcookie; path=/");
|
||||||
|
return new Response("", { headers, status: 200 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("page=debrideur")) {
|
||||||
|
// Missing form!
|
||||||
|
return new Response('<html><body>Nothing here</body></html>', { status: 200 });
|
||||||
|
}
|
||||||
|
return new Response("Not found", { status: 404 });
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const fallback = new MegaWebFallback(() => ({ login: "a", password: "b" }));
|
||||||
|
|
||||||
|
await expect(fallback.unrestrict("http://mega.debrid/file"))
|
||||||
|
.rejects.toThrow("Mega-Web Login ungültig oder Session blockiert");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null if generation fails to find a code", async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
globalThis.fetch = vi.fn(async (url: string | URL | Request) => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
callCount++;
|
||||||
|
if (urlStr.includes("form=login")) {
|
||||||
|
const headers = new Headers();
|
||||||
|
headers.append("set-cookie", "session=goodcookie; path=/");
|
||||||
|
return new Response("", { headers, status: 200 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("page=debrideur")) {
|
||||||
|
return new Response('<form id="debridForm"></form>', { status: 200 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("form=debrid")) {
|
||||||
|
// The generate POST returns HTML without any codes
|
||||||
|
return new Response(`<div>No links here</div>`, { status: 200 });
|
||||||
|
}
|
||||||
|
return new Response("Not found", { status: 404 });
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const fallback = new MegaWebFallback(() => ({ login: "a", password: "b" }));
|
||||||
|
const result = await fallback.unrestrict("http://mega.debrid/file");
|
||||||
|
|
||||||
|
// Generation fails -> resets cookie -> tries again -> fails again -> returns null
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("aborts pending Mega-Web polling when signal is cancelled", async () => {
|
||||||
|
globalThis.fetch = vi.fn((url: string | URL | Request, init?: RequestInit): Promise<Response> => {
|
||||||
|
const urlStr = String(url);
|
||||||
|
|
||||||
|
if (urlStr.includes("form=login")) {
|
||||||
|
const headers = new Headers();
|
||||||
|
headers.append("set-cookie", "session=goodcookie; path=/");
|
||||||
|
return Promise.resolve(new Response("", { headers, status: 200 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (urlStr.includes("page=debrideur")) {
|
||||||
|
return Promise.resolve(new Response('<form id="debridForm"></form>', { status: 200 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (urlStr.includes("form=debrid")) {
|
||||||
|
return Promise.resolve(new Response(`
|
||||||
|
<div class="acp-box">
|
||||||
|
<h3>Link: https://mega.debrid/link2</h3>
|
||||||
|
<a href="javascript:processDebrid(1,'secretcode456',0)">Download</a>
|
||||||
|
</div>
|
||||||
|
`, { status: 200 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (urlStr.includes("ajax=debrid")) {
|
||||||
|
return new Promise<Response>((_resolve, reject) => {
|
||||||
|
const signal = init?.signal;
|
||||||
|
const onAbort = (): void => reject(new Error("aborted:ajax"));
|
||||||
|
if (signal?.aborted) {
|
||||||
|
onAbort();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
signal?.addEventListener("abort", onAbort, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.resolve(new Response("Not found", { status: 404 }));
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const fallback = new MegaWebFallback(() => ({ login: "user", password: "pwd" }));
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
controller.abort("test");
|
||||||
|
}, 200);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(fallback.unrestrict("https://mega.debrid/link2", controller.signal)).rejects.toThrow(/aborted/i);
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
188
tests/resolve-archive-items.test.ts
Normal file
188
tests/resolve-archive-items.test.ts
Normal file
@ -0,0 +1,188 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { resolveArchiveItemsFromList } from "../src/main/download-manager";
|
||||||
|
|
||||||
|
type MinimalItem = {
|
||||||
|
targetPath?: string;
|
||||||
|
fileName?: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
function makeItems(names: string[]): MinimalItem[] {
|
||||||
|
return names.map((name) => ({
|
||||||
|
targetPath: `C:\\Downloads\\Package\\${name}`,
|
||||||
|
fileName: name,
|
||||||
|
id: name,
|
||||||
|
status: "completed",
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("resolveArchiveItemsFromList", () => {
|
||||||
|
// ── Multipart RAR (.partN.rar) ──
|
||||||
|
|
||||||
|
it("matches multipart .part1.rar archives", () => {
|
||||||
|
const items = makeItems([
|
||||||
|
"Movie.part1.rar",
|
||||||
|
"Movie.part2.rar",
|
||||||
|
"Movie.part3.rar",
|
||||||
|
"Other.rar",
|
||||||
|
]);
|
||||||
|
const result = resolveArchiveItemsFromList("Movie.part1.rar", items as any);
|
||||||
|
expect(result).toHaveLength(3);
|
||||||
|
expect(result.map((i: any) => i.fileName)).toEqual([
|
||||||
|
"Movie.part1.rar",
|
||||||
|
"Movie.part2.rar",
|
||||||
|
"Movie.part3.rar",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches multipart .part01.rar archives (zero-padded)", () => {
|
||||||
|
const items = makeItems([
|
||||||
|
"Film.part01.rar",
|
||||||
|
"Film.part02.rar",
|
||||||
|
"Film.part10.rar",
|
||||||
|
"Unrelated.zip",
|
||||||
|
]);
|
||||||
|
const result = resolveArchiveItemsFromList("Film.part01.rar", items as any);
|
||||||
|
expect(result).toHaveLength(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Old-style RAR (.rar + .r00, .r01, etc.) ──
|
||||||
|
|
||||||
|
it("matches old-style .rar + .rNN volumes", () => {
|
||||||
|
const items = makeItems([
|
||||||
|
"Archive.rar",
|
||||||
|
"Archive.r00",
|
||||||
|
"Archive.r01",
|
||||||
|
"Archive.r02",
|
||||||
|
"Other.zip",
|
||||||
|
]);
|
||||||
|
const result = resolveArchiveItemsFromList("Archive.rar", items as any);
|
||||||
|
expect(result).toHaveLength(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Single RAR ──
|
||||||
|
|
||||||
|
it("matches a single .rar file", () => {
|
||||||
|
const items = makeItems(["SingleFile.rar", "Other.mkv"]);
|
||||||
|
const result = resolveArchiveItemsFromList("SingleFile.rar", items as any);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect((result[0] as any).fileName).toBe("SingleFile.rar");
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Split ZIP ──
|
||||||
|
|
||||||
|
it("matches split .zip.NNN files", () => {
|
||||||
|
const items = makeItems([
|
||||||
|
"Data.zip",
|
||||||
|
"Data.zip.001",
|
||||||
|
"Data.zip.002",
|
||||||
|
"Data.zip.003",
|
||||||
|
]);
|
||||||
|
const result = resolveArchiveItemsFromList("Data.zip.001", items as any);
|
||||||
|
expect(result).toHaveLength(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Split 7z ──
|
||||||
|
|
||||||
|
it("matches split .7z.NNN files", () => {
|
||||||
|
const items = makeItems([
|
||||||
|
"Backup.7z.001",
|
||||||
|
"Backup.7z.002",
|
||||||
|
]);
|
||||||
|
const result = resolveArchiveItemsFromList("Backup.7z.001", items as any);
|
||||||
|
expect(result).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Generic .NNN splits ──
|
||||||
|
|
||||||
|
it("matches generic .NNN split files", () => {
|
||||||
|
const items = makeItems([
|
||||||
|
"video.001",
|
||||||
|
"video.002",
|
||||||
|
"video.003",
|
||||||
|
]);
|
||||||
|
const result = resolveArchiveItemsFromList("video.001", items as any);
|
||||||
|
expect(result).toHaveLength(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Exact filename match ──
|
||||||
|
|
||||||
|
it("matches a single .zip by exact name", () => {
|
||||||
|
const items = makeItems(["myarchive.zip", "other.rar"]);
|
||||||
|
const result = resolveArchiveItemsFromList("myarchive.zip", items as any);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect((result[0] as any).fileName).toBe("myarchive.zip");
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Case insensitivity ──
|
||||||
|
|
||||||
|
it("matches case-insensitively", () => {
|
||||||
|
const items = makeItems([
|
||||||
|
"MOVIE.PART1.RAR",
|
||||||
|
"MOVIE.PART2.RAR",
|
||||||
|
]);
|
||||||
|
const result = resolveArchiveItemsFromList("movie.part1.rar", items as any);
|
||||||
|
expect(result).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Stem-based fallback ──
|
||||||
|
|
||||||
|
it("uses stem-based fallback when exact patterns fail", () => {
|
||||||
|
// Simulate a debrid service that renames "Movie.part1.rar" to "Movie.part1_dl.rar"
|
||||||
|
// but the disk file is "Movie.part1.rar"
|
||||||
|
const items = makeItems([
|
||||||
|
"Movie.rar",
|
||||||
|
]);
|
||||||
|
// The archive on disk is "Movie.part1.rar" but there's no item matching the
|
||||||
|
// .partN pattern. The stem "movie" should match "Movie.rar" via fallback.
|
||||||
|
const result = resolveArchiveItemsFromList("Movie.part1.rar", items as any);
|
||||||
|
// stem fallback: "movie" starts with "movie" and ends with .rar
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Single item fallback ──
|
||||||
|
|
||||||
|
it("returns single archive item when no pattern matches", () => {
|
||||||
|
const items = makeItems(["totally-different-name.rar"]);
|
||||||
|
const result = resolveArchiveItemsFromList("Original.rar", items as any);
|
||||||
|
// Single item in list with archive extension → return it
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Empty when no match ──
|
||||||
|
|
||||||
|
it("returns empty when items have no archive extensions", () => {
|
||||||
|
const items = makeItems(["video.mkv", "subtitle.srt"]);
|
||||||
|
const result = resolveArchiveItemsFromList("Archive.rar", items as any);
|
||||||
|
expect(result).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Items without targetPath ──
|
||||||
|
|
||||||
|
it("falls back to fileName when targetPath is missing", () => {
|
||||||
|
const items = [
|
||||||
|
{ fileName: "Movie.part1.rar", id: "1", status: "completed" },
|
||||||
|
{ fileName: "Movie.part2.rar", id: "2", status: "completed" },
|
||||||
|
];
|
||||||
|
const result = resolveArchiveItemsFromList("Movie.part1.rar", items as any);
|
||||||
|
expect(result).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Multiple archives, should not cross-match ──
|
||||||
|
|
||||||
|
it("does not cross-match different archive groups", () => {
|
||||||
|
const items = makeItems([
|
||||||
|
"Episode.S01E01.part1.rar",
|
||||||
|
"Episode.S01E01.part2.rar",
|
||||||
|
"Episode.S01E02.part1.rar",
|
||||||
|
"Episode.S01E02.part2.rar",
|
||||||
|
]);
|
||||||
|
const result1 = resolveArchiveItemsFromList("Episode.S01E01.part1.rar", items as any);
|
||||||
|
expect(result1).toHaveLength(2);
|
||||||
|
expect(result1.every((i: any) => i.fileName.includes("S01E01"))).toBe(true);
|
||||||
|
|
||||||
|
const result2 = resolveArchiveItemsFromList("Episode.S01E02.part1.rar", items as any);
|
||||||
|
expect(result2).toHaveLength(2);
|
||||||
|
expect(result2.every((i: any) => i.fileName.includes("S01E02"))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -153,7 +153,7 @@ async function main(): Promise<void> {
|
|||||||
createStoragePaths(path.join(tempRoot, "state-pause"))
|
createStoragePaths(path.join(tempRoot, "state-pause"))
|
||||||
);
|
);
|
||||||
manager2.addPackages([{ name: "pause", links: ["https://dummy/slow"] }]);
|
manager2.addPackages([{ name: "pause", links: ["https://dummy/slow"] }]);
|
||||||
manager2.start();
|
await manager2.start();
|
||||||
await new Promise((resolve) => setTimeout(resolve, 120));
|
await new Promise((resolve) => setTimeout(resolve, 120));
|
||||||
const paused = manager2.togglePause();
|
const paused = manager2.togglePause();
|
||||||
assert(paused, "Pause konnte nicht aktiviert werden");
|
assert(paused, "Pause konnte nicht aktiviert werden");
|
||||||
|
|||||||
163
tests/session-log.test.ts
Normal file
163
tests/session-log.test.ts
Normal file
@ -0,0 +1,163 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
import { initSessionLog, getSessionLogPath, shutdownSessionLog } from "../src/main/session-log";
|
||||||
|
import { setLogListener } from "../src/main/logger";
|
||||||
|
|
||||||
|
const tempDirs: string[] = [];
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
// Ensure session log is shut down between tests
|
||||||
|
shutdownSessionLog();
|
||||||
|
// Ensure listener is cleared between tests
|
||||||
|
setLogListener(null);
|
||||||
|
for (const dir of tempDirs.splice(0)) {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("session-log", () => {
|
||||||
|
it("initSessionLog creates directory and file", () => {
|
||||||
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-slog-"));
|
||||||
|
tempDirs.push(baseDir);
|
||||||
|
|
||||||
|
initSessionLog(baseDir);
|
||||||
|
const logPath = getSessionLogPath();
|
||||||
|
expect(logPath).not.toBeNull();
|
||||||
|
expect(fs.existsSync(logPath!)).toBe(true);
|
||||||
|
expect(fs.existsSync(path.join(baseDir, "session-logs"))).toBe(true);
|
||||||
|
expect(path.basename(logPath!)).toMatch(/^session_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.txt$/);
|
||||||
|
|
||||||
|
const content = fs.readFileSync(logPath!, "utf8");
|
||||||
|
expect(content).toContain("=== Session gestartet:");
|
||||||
|
|
||||||
|
shutdownSessionLog();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("logger listener writes to session log", async () => {
|
||||||
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-slog-"));
|
||||||
|
tempDirs.push(baseDir);
|
||||||
|
|
||||||
|
initSessionLog(baseDir);
|
||||||
|
const logPath = getSessionLogPath()!;
|
||||||
|
|
||||||
|
// Simulate a log line via the listener
|
||||||
|
const { logger } = await import("../src/main/logger");
|
||||||
|
logger.info("Test-Nachricht für Session-Log");
|
||||||
|
|
||||||
|
// Wait for flush (200ms interval + margin)
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||||
|
|
||||||
|
const content = fs.readFileSync(logPath, "utf8");
|
||||||
|
expect(content).toContain("Test-Nachricht für Session-Log");
|
||||||
|
|
||||||
|
shutdownSessionLog();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shutdownSessionLog writes closing line", () => {
|
||||||
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-slog-"));
|
||||||
|
tempDirs.push(baseDir);
|
||||||
|
|
||||||
|
initSessionLog(baseDir);
|
||||||
|
const logPath = getSessionLogPath()!;
|
||||||
|
|
||||||
|
shutdownSessionLog();
|
||||||
|
|
||||||
|
const content = fs.readFileSync(logPath, "utf8");
|
||||||
|
expect(content).toContain("=== Session beendet:");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shutdownSessionLog removes listener", async () => {
|
||||||
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-slog-"));
|
||||||
|
tempDirs.push(baseDir);
|
||||||
|
|
||||||
|
initSessionLog(baseDir);
|
||||||
|
const logPath = getSessionLogPath()!;
|
||||||
|
|
||||||
|
shutdownSessionLog();
|
||||||
|
|
||||||
|
// Log after shutdown - should NOT appear in session log
|
||||||
|
const { logger } = await import("../src/main/logger");
|
||||||
|
logger.info("Nach-Shutdown-Nachricht");
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||||
|
|
||||||
|
const content = fs.readFileSync(logPath, "utf8");
|
||||||
|
expect(content).not.toContain("Nach-Shutdown-Nachricht");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("cleanupOldSessionLogs deletes old files", async () => {
|
||||||
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-slog-"));
|
||||||
|
tempDirs.push(baseDir);
|
||||||
|
|
||||||
|
const logsDir = path.join(baseDir, "session-logs");
|
||||||
|
fs.mkdirSync(logsDir, { recursive: true });
|
||||||
|
|
||||||
|
// Create a fake old session log
|
||||||
|
const oldFile = path.join(logsDir, "session_2020-01-01_00-00-00.txt");
|
||||||
|
fs.writeFileSync(oldFile, "old session");
|
||||||
|
// Set mtime to 30 days ago
|
||||||
|
const oldTime = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||||
|
fs.utimesSync(oldFile, oldTime, oldTime);
|
||||||
|
|
||||||
|
// Create a recent file
|
||||||
|
const newFile = path.join(logsDir, "session_2099-01-01_00-00-00.txt");
|
||||||
|
fs.writeFileSync(newFile, "new session");
|
||||||
|
|
||||||
|
// initSessionLog triggers cleanup
|
||||||
|
initSessionLog(baseDir);
|
||||||
|
|
||||||
|
// Wait for async cleanup
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||||
|
|
||||||
|
expect(fs.existsSync(oldFile)).toBe(false);
|
||||||
|
expect(fs.existsSync(newFile)).toBe(true);
|
||||||
|
|
||||||
|
shutdownSessionLog();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("cleanupOldSessionLogs keeps recent files", async () => {
|
||||||
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-slog-"));
|
||||||
|
tempDirs.push(baseDir);
|
||||||
|
|
||||||
|
const logsDir = path.join(baseDir, "session-logs");
|
||||||
|
fs.mkdirSync(logsDir, { recursive: true });
|
||||||
|
|
||||||
|
// Create a file from 2 days ago (should be kept)
|
||||||
|
const recentFile = path.join(logsDir, "session_2025-12-01_00-00-00.txt");
|
||||||
|
fs.writeFileSync(recentFile, "recent session");
|
||||||
|
const recentTime = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000);
|
||||||
|
fs.utimesSync(recentFile, recentTime, recentTime);
|
||||||
|
|
||||||
|
initSessionLog(baseDir);
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||||
|
|
||||||
|
expect(fs.existsSync(recentFile)).toBe(true);
|
||||||
|
|
||||||
|
shutdownSessionLog();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("multiple sessions create different files", async () => {
|
||||||
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-slog-"));
|
||||||
|
tempDirs.push(baseDir);
|
||||||
|
|
||||||
|
initSessionLog(baseDir);
|
||||||
|
const path1 = getSessionLogPath();
|
||||||
|
shutdownSessionLog();
|
||||||
|
|
||||||
|
// Small delay to ensure different timestamp
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1100));
|
||||||
|
|
||||||
|
initSessionLog(baseDir);
|
||||||
|
const path2 = getSessionLogPath();
|
||||||
|
shutdownSessionLog();
|
||||||
|
|
||||||
|
expect(path1).not.toBeNull();
|
||||||
|
expect(path2).not.toBeNull();
|
||||||
|
expect(path1).not.toBe(path2);
|
||||||
|
expect(fs.existsSync(path1!)).toBe(true);
|
||||||
|
expect(fs.existsSync(path2!)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -80,10 +80,12 @@ describe("settings storage", () => {
|
|||||||
completedCleanupPolicy: "broken" as unknown as AppSettings["completedCleanupPolicy"],
|
completedCleanupPolicy: "broken" as unknown as AppSettings["completedCleanupPolicy"],
|
||||||
speedLimitMode: "broken" as unknown as AppSettings["speedLimitMode"],
|
speedLimitMode: "broken" as unknown as AppSettings["speedLimitMode"],
|
||||||
maxParallel: 0,
|
maxParallel: 0,
|
||||||
|
retryLimit: 999,
|
||||||
reconnectWaitSeconds: 9999,
|
reconnectWaitSeconds: 9999,
|
||||||
speedLimitKbps: -1,
|
speedLimitKbps: -1,
|
||||||
outputDir: " ",
|
outputDir: " ",
|
||||||
extractDir: " ",
|
extractDir: " ",
|
||||||
|
mkvLibraryDir: " ",
|
||||||
updateRepo: " "
|
updateRepo: " "
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -95,10 +97,12 @@ describe("settings storage", () => {
|
|||||||
expect(normalized.completedCleanupPolicy).toBe("never");
|
expect(normalized.completedCleanupPolicy).toBe("never");
|
||||||
expect(normalized.speedLimitMode).toBe("global");
|
expect(normalized.speedLimitMode).toBe("global");
|
||||||
expect(normalized.maxParallel).toBe(1);
|
expect(normalized.maxParallel).toBe(1);
|
||||||
|
expect(normalized.retryLimit).toBe(99);
|
||||||
expect(normalized.reconnectWaitSeconds).toBe(600);
|
expect(normalized.reconnectWaitSeconds).toBe(600);
|
||||||
expect(normalized.speedLimitKbps).toBe(0);
|
expect(normalized.speedLimitKbps).toBe(0);
|
||||||
expect(normalized.outputDir).toBe(defaultSettings().outputDir);
|
expect(normalized.outputDir).toBe(defaultSettings().outputDir);
|
||||||
expect(normalized.extractDir).toBe(defaultSettings().extractDir);
|
expect(normalized.extractDir).toBe(defaultSettings().extractDir);
|
||||||
|
expect(normalized.mkvLibraryDir).toBe(defaultSettings().mkvLibraryDir);
|
||||||
expect(normalized.updateRepo).toBe(defaultSettings().updateRepo);
|
expect(normalized.updateRepo).toBe(defaultSettings().updateRepo);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -113,6 +117,7 @@ describe("settings storage", () => {
|
|||||||
providerPrimary: "not-valid",
|
providerPrimary: "not-valid",
|
||||||
completedCleanupPolicy: "not-valid",
|
completedCleanupPolicy: "not-valid",
|
||||||
maxParallel: "999",
|
maxParallel: "999",
|
||||||
|
retryLimit: "-3",
|
||||||
reconnectWaitSeconds: "1",
|
reconnectWaitSeconds: "1",
|
||||||
speedLimitMode: "not-valid",
|
speedLimitMode: "not-valid",
|
||||||
updateRepo: ""
|
updateRepo: ""
|
||||||
@ -124,6 +129,7 @@ describe("settings storage", () => {
|
|||||||
expect(loaded.providerPrimary).toBe("realdebrid");
|
expect(loaded.providerPrimary).toBe("realdebrid");
|
||||||
expect(loaded.completedCleanupPolicy).toBe("never");
|
expect(loaded.completedCleanupPolicy).toBe("never");
|
||||||
expect(loaded.maxParallel).toBe(50);
|
expect(loaded.maxParallel).toBe(50);
|
||||||
|
expect(loaded.retryLimit).toBe(0);
|
||||||
expect(loaded.reconnectWaitSeconds).toBe(10);
|
expect(loaded.reconnectWaitSeconds).toBe(10);
|
||||||
expect(loaded.speedLimitMode).toBe("global");
|
expect(loaded.speedLimitMode).toBe("global");
|
||||||
expect(loaded.updateRepo).toBe(defaultSettings().updateRepo);
|
expect(loaded.updateRepo).toBe(defaultSettings().updateRepo);
|
||||||
@ -298,6 +304,58 @@ describe("settings storage", () => {
|
|||||||
expect(loaded.packageOrder).toEqual(empty.packageOrder);
|
expect(loaded.packageOrder).toEqual(empty.packageOrder);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("loads backup session when primary session is corrupted", () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-store-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const paths = createStoragePaths(dir);
|
||||||
|
|
||||||
|
const backupSession = emptySession();
|
||||||
|
backupSession.packageOrder = ["pkg-backup"];
|
||||||
|
backupSession.packages["pkg-backup"] = {
|
||||||
|
id: "pkg-backup",
|
||||||
|
name: "Backup Package",
|
||||||
|
outputDir: path.join(dir, "out"),
|
||||||
|
extractDir: path.join(dir, "extract"),
|
||||||
|
status: "queued",
|
||||||
|
itemIds: ["item-backup"],
|
||||||
|
cancelled: false,
|
||||||
|
enabled: true,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now()
|
||||||
|
};
|
||||||
|
backupSession.items["item-backup"] = {
|
||||||
|
id: "item-backup",
|
||||||
|
packageId: "pkg-backup",
|
||||||
|
url: "https://example.com/backup-file",
|
||||||
|
provider: null,
|
||||||
|
status: "queued",
|
||||||
|
retries: 0,
|
||||||
|
speedBps: 0,
|
||||||
|
downloadedBytes: 0,
|
||||||
|
totalBytes: null,
|
||||||
|
progressPercent: 0,
|
||||||
|
fileName: "backup-file.rar",
|
||||||
|
targetPath: path.join(dir, "out", "backup-file.rar"),
|
||||||
|
resumable: true,
|
||||||
|
attempts: 0,
|
||||||
|
lastError: "",
|
||||||
|
fullStatus: "Wartet",
|
||||||
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now()
|
||||||
|
};
|
||||||
|
|
||||||
|
fs.writeFileSync(`${paths.sessionFile}.bak`, JSON.stringify(backupSession), "utf8");
|
||||||
|
fs.writeFileSync(paths.sessionFile, "{broken-session-json", "utf8");
|
||||||
|
|
||||||
|
const loaded = loadSession(paths);
|
||||||
|
expect(loaded.packageOrder).toEqual(["pkg-backup"]);
|
||||||
|
expect(loaded.packages["pkg-backup"]?.name).toBe("Backup Package");
|
||||||
|
expect(loaded.items["item-backup"]?.fileName).toBe("backup-file.rar");
|
||||||
|
|
||||||
|
const restoredPrimary = JSON.parse(fs.readFileSync(paths.sessionFile, "utf8")) as { packages?: Record<string, unknown> };
|
||||||
|
expect(restoredPrimary.packages && "pkg-backup" in restoredPrimary.packages).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
it("returns defaults when config file contains invalid JSON", () => {
|
it("returns defaults when config file contains invalid JSON", () => {
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-store-"));
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-store-"));
|
||||||
tempDirs.push(dir);
|
tempDirs.push(dir);
|
||||||
@ -310,6 +368,7 @@ describe("settings storage", () => {
|
|||||||
const defaults = defaultSettings();
|
const defaults = defaultSettings();
|
||||||
expect(loaded.providerPrimary).toBe(defaults.providerPrimary);
|
expect(loaded.providerPrimary).toBe(defaults.providerPrimary);
|
||||||
expect(loaded.maxParallel).toBe(defaults.maxParallel);
|
expect(loaded.maxParallel).toBe(defaults.maxParallel);
|
||||||
|
expect(loaded.retryLimit).toBe(defaults.retryLimit);
|
||||||
expect(loaded.outputDir).toBe(defaults.outputDir);
|
expect(loaded.outputDir).toBe(defaults.outputDir);
|
||||||
expect(loaded.cleanupMode).toBe(defaults.cleanupMode);
|
expect(loaded.cleanupMode).toBe(defaults.cleanupMode);
|
||||||
});
|
});
|
||||||
@ -388,6 +447,32 @@ describe("settings storage", () => {
|
|||||||
expect(persisted.summaryText).toBe("before-mutation");
|
expect(persisted.summaryText).toBe("before-mutation");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("creates session backup before sync and async session overwrites", async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-store-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
const paths = createStoragePaths(dir);
|
||||||
|
|
||||||
|
const first = emptySession();
|
||||||
|
first.summaryText = "first";
|
||||||
|
saveSession(paths, first);
|
||||||
|
|
||||||
|
const second = emptySession();
|
||||||
|
second.summaryText = "second";
|
||||||
|
saveSession(paths, second);
|
||||||
|
|
||||||
|
const backupAfterSync = JSON.parse(fs.readFileSync(`${paths.sessionFile}.bak`, "utf8")) as { summaryText?: string };
|
||||||
|
expect(backupAfterSync.summaryText).toBe("first");
|
||||||
|
|
||||||
|
const third = emptySession();
|
||||||
|
third.summaryText = "third";
|
||||||
|
await saveSessionAsync(paths, third);
|
||||||
|
|
||||||
|
const backupAfterAsync = JSON.parse(fs.readFileSync(`${paths.sessionFile}.bak`, "utf8")) as { summaryText?: string };
|
||||||
|
const primaryAfterAsync = JSON.parse(fs.readFileSync(paths.sessionFile, "utf8")) as { summaryText?: string };
|
||||||
|
expect(backupAfterAsync.summaryText).toBe("second");
|
||||||
|
expect(primaryAfterAsync.summaryText).toBe("third");
|
||||||
|
});
|
||||||
|
|
||||||
it("applies defaults for missing fields when loading old config", () => {
|
it("applies defaults for missing fields when loading old config", () => {
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-store-"));
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rd-store-"));
|
||||||
tempDirs.push(dir);
|
tempDirs.push(dir);
|
||||||
@ -409,7 +494,7 @@ describe("settings storage", () => {
|
|||||||
|
|
||||||
// Old fields should be preserved
|
// Old fields should be preserved
|
||||||
expect(loaded.token).toBe("my-token");
|
expect(loaded.token).toBe("my-token");
|
||||||
expect(loaded.outputDir).toBe("/custom/output");
|
expect(loaded.outputDir).toBe(path.resolve("/custom/output"));
|
||||||
|
|
||||||
// Missing new fields should get default values
|
// Missing new fields should get default values
|
||||||
expect(loaded.autoProviderFallback).toBe(defaults.autoProviderFallback);
|
expect(loaded.autoProviderFallback).toBe(defaults.autoProviderFallback);
|
||||||
@ -418,6 +503,9 @@ describe("settings storage", () => {
|
|||||||
expect(loaded.speedLimitMode).toBe(defaults.speedLimitMode);
|
expect(loaded.speedLimitMode).toBe(defaults.speedLimitMode);
|
||||||
expect(loaded.clipboardWatch).toBe(defaults.clipboardWatch);
|
expect(loaded.clipboardWatch).toBe(defaults.clipboardWatch);
|
||||||
expect(loaded.minimizeToTray).toBe(defaults.minimizeToTray);
|
expect(loaded.minimizeToTray).toBe(defaults.minimizeToTray);
|
||||||
|
expect(loaded.retryLimit).toBe(defaults.retryLimit);
|
||||||
|
expect(loaded.collectMkvToLibrary).toBe(defaults.collectMkvToLibrary);
|
||||||
|
expect(loaded.mkvLibraryDir).toBe(defaults.mkvLibraryDir);
|
||||||
expect(loaded.theme).toBe(defaults.theme);
|
expect(loaded.theme).toBe(defaults.theme);
|
||||||
expect(loaded.bandwidthSchedules).toEqual(defaults.bandwidthSchedules);
|
expect(loaded.bandwidthSchedules).toEqual(defaults.bandwidthSchedules);
|
||||||
expect(loaded.updateRepo).toBe(defaults.updateRepo);
|
expect(loaded.updateRepo).toBe(defaults.updateRepo);
|
||||||
|
|||||||
@ -3,7 +3,7 @@ import crypto from "node:crypto";
|
|||||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
import { checkGitHubUpdate, installLatestUpdate, isRemoteNewer, normalizeUpdateRepo, parseVersionParts } from "../src/main/update";
|
import { checkGitHubUpdate, installLatestUpdate, isRemoteNewer, normalizeUpdateRepo, parseVersionParts } from "../src/main/update";
|
||||||
import { APP_VERSION } from "../src/main/constants";
|
import { APP_VERSION } from "../src/main/constants";
|
||||||
import { UpdateCheckResult } from "../src/shared/types";
|
import { UpdateCheckResult, UpdateInstallProgress } from "../src/shared/types";
|
||||||
|
|
||||||
const originalFetch = globalThis.fetch;
|
const originalFetch = globalThis.fetch;
|
||||||
|
|
||||||
@ -11,6 +11,10 @@ function sha256Hex(buffer: Buffer): string {
|
|||||||
return crypto.createHash("sha256").update(buffer).digest("hex");
|
return crypto.createHash("sha256").update(buffer).digest("hex");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sha512Hex(buffer: Buffer): string {
|
||||||
|
return crypto.createHash("sha512").update(buffer).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
globalThis.fetch = originalFetch;
|
globalThis.fetch = originalFetch;
|
||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
@ -18,23 +22,23 @@ afterEach(() => {
|
|||||||
|
|
||||||
describe("update", () => {
|
describe("update", () => {
|
||||||
it("normalizes update repo input", () => {
|
it("normalizes update repo input", () => {
|
||||||
expect(normalizeUpdateRepo("")).toBe("Sucukdeluxe/real-debrid-downloader");
|
expect(normalizeUpdateRepo("")).toBe("Administrator/real-debrid-downloader");
|
||||||
expect(normalizeUpdateRepo("owner/repo")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("owner/repo")).toBe("owner/repo");
|
||||||
expect(normalizeUpdateRepo("https://github.com/owner/repo")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("https://codeberg.org/owner/repo")).toBe("owner/repo");
|
||||||
expect(normalizeUpdateRepo("https://www.github.com/owner/repo")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("https://www.codeberg.org/owner/repo")).toBe("owner/repo");
|
||||||
expect(normalizeUpdateRepo("https://github.com/owner/repo/releases/tag/v1.2.3")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("https://codeberg.org/owner/repo/releases/tag/v1.2.3")).toBe("owner/repo");
|
||||||
expect(normalizeUpdateRepo("github.com/owner/repo.git")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("codeberg.org/owner/repo.git")).toBe("owner/repo");
|
||||||
expect(normalizeUpdateRepo("git@github.com:owner/repo.git")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("git@codeberg.org:owner/repo.git")).toBe("owner/repo");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses normalized repo slug for GitHub API requests", async () => {
|
it("uses normalized repo slug for API requests", async () => {
|
||||||
let requestedUrl = "";
|
let requestedUrl = "";
|
||||||
globalThis.fetch = (async (input: RequestInfo | URL): Promise<Response> => {
|
globalThis.fetch = (async (input: RequestInfo | URL): Promise<Response> => {
|
||||||
requestedUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
requestedUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
tag_name: `v${APP_VERSION}`,
|
tag_name: `v${APP_VERSION}`,
|
||||||
html_url: "https://github.com/owner/repo/releases/tag/v1.0.0",
|
html_url: "https://git.24-music.de/owner/repo/releases/tag/v1.0.0",
|
||||||
assets: []
|
assets: []
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
@ -44,8 +48,8 @@ describe("update", () => {
|
|||||||
);
|
);
|
||||||
}) as typeof fetch;
|
}) as typeof fetch;
|
||||||
|
|
||||||
const result = await checkGitHubUpdate("https://github.com/owner/repo/releases");
|
const result = await checkGitHubUpdate("https://git.24-music.de/owner/repo/releases");
|
||||||
expect(requestedUrl).toBe("https://api.github.com/repos/owner/repo/releases/latest");
|
expect(requestedUrl).toBe("https://git.24-music.de/api/v1/repos/owner/repo/releases/latest");
|
||||||
expect(result.currentVersion).toBe(APP_VERSION);
|
expect(result.currentVersion).toBe(APP_VERSION);
|
||||||
expect(result.latestVersion).toBe(APP_VERSION);
|
expect(result.latestVersion).toBe(APP_VERSION);
|
||||||
expect(result.updateAvailable).toBe(false);
|
expect(result.updateAvailable).toBe(false);
|
||||||
@ -55,7 +59,7 @@ describe("update", () => {
|
|||||||
globalThis.fetch = (async (): Promise<Response> => new Response(
|
globalThis.fetch = (async (): Promise<Response> => new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
tag_name: "v9.9.9",
|
tag_name: "v9.9.9",
|
||||||
html_url: "https://github.com/owner/repo/releases/tag/v9.9.9",
|
html_url: "https://codeberg.org/owner/repo/releases/tag/v9.9.9",
|
||||||
assets: [
|
assets: [
|
||||||
{
|
{
|
||||||
name: "Real-Debrid-Downloader 9.9.9.exe",
|
name: "Real-Debrid-Downloader 9.9.9.exe",
|
||||||
@ -91,7 +95,7 @@ describe("update", () => {
|
|||||||
if (url.includes("stale-setup.exe")) {
|
if (url.includes("stale-setup.exe")) {
|
||||||
return new Response("missing", { status: 404 });
|
return new Response("missing", { status: 404 });
|
||||||
}
|
}
|
||||||
if (url.includes("/releases/latest/download/")) {
|
if (url.includes("/releases/download/v9.9.9/")) {
|
||||||
return new Response(executablePayload, {
|
return new Response(executablePayload, {
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: { "Content-Type": "application/octet-stream" }
|
headers: { "Content-Type": "application/octet-stream" }
|
||||||
@ -105,7 +109,7 @@ describe("update", () => {
|
|||||||
currentVersion: APP_VERSION,
|
currentVersion: APP_VERSION,
|
||||||
latestVersion: "9.9.9",
|
latestVersion: "9.9.9",
|
||||||
latestTag: "v9.9.9",
|
latestTag: "v9.9.9",
|
||||||
releaseUrl: "https://github.com/owner/repo/releases/tag/v9.9.9",
|
releaseUrl: "https://codeberg.org/owner/repo/releases/tag/v9.9.9",
|
||||||
setupAssetUrl: "https://example.invalid/stale-setup.exe",
|
setupAssetUrl: "https://example.invalid/stale-setup.exe",
|
||||||
setupAssetName: "Real-Debrid-Downloader Setup 9.9.9.exe",
|
setupAssetName: "Real-Debrid-Downloader Setup 9.9.9.exe",
|
||||||
setupAssetDigest: `sha256:${executableDigest}`
|
setupAssetDigest: `sha256:${executableDigest}`
|
||||||
@ -113,7 +117,7 @@ describe("update", () => {
|
|||||||
|
|
||||||
const result = await installLatestUpdate("owner/repo", prechecked);
|
const result = await installLatestUpdate("owner/repo", prechecked);
|
||||||
expect(result.started).toBe(true);
|
expect(result.started).toBe(true);
|
||||||
expect(requestedUrls.some((url) => url.includes("/releases/latest/download/"))).toBe(true);
|
expect(requestedUrls.some((url) => url.includes("/releases/download/v9.9.9/"))).toBe(true);
|
||||||
expect(requestedUrls.filter((url) => url.includes("stale-setup.exe"))).toHaveLength(1);
|
expect(requestedUrls.filter((url) => url.includes("stale-setup.exe"))).toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -176,7 +180,7 @@ describe("update", () => {
|
|||||||
currentVersion: APP_VERSION,
|
currentVersion: APP_VERSION,
|
||||||
latestVersion: "9.9.9",
|
latestVersion: "9.9.9",
|
||||||
latestTag: "v9.9.9",
|
latestTag: "v9.9.9",
|
||||||
releaseUrl: "https://github.com/owner/repo/releases/tag/v9.9.9",
|
releaseUrl: "https://codeberg.org/owner/repo/releases/tag/v9.9.9",
|
||||||
setupAssetUrl: "",
|
setupAssetUrl: "",
|
||||||
setupAssetName: ""
|
setupAssetName: ""
|
||||||
};
|
};
|
||||||
@ -240,7 +244,7 @@ describe("update", () => {
|
|||||||
currentVersion: APP_VERSION,
|
currentVersion: APP_VERSION,
|
||||||
latestVersion: "9.9.9",
|
latestVersion: "9.9.9",
|
||||||
latestTag: "v9.9.9",
|
latestTag: "v9.9.9",
|
||||||
releaseUrl: "https://github.com/owner/repo/releases/tag/v9.9.9",
|
releaseUrl: "https://codeberg.org/owner/repo/releases/tag/v9.9.9",
|
||||||
setupAssetUrl: "https://example.invalid/hang-setup.exe",
|
setupAssetUrl: "https://example.invalid/hang-setup.exe",
|
||||||
setupAssetName: "",
|
setupAssetName: "",
|
||||||
setupAssetDigest: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
setupAssetDigest: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||||
@ -276,7 +280,7 @@ describe("update", () => {
|
|||||||
currentVersion: APP_VERSION,
|
currentVersion: APP_VERSION,
|
||||||
latestVersion: "9.9.9",
|
latestVersion: "9.9.9",
|
||||||
latestTag: "v9.9.9",
|
latestTag: "v9.9.9",
|
||||||
releaseUrl: "https://github.com/owner/repo/releases/tag/v9.9.9",
|
releaseUrl: "https://codeberg.org/owner/repo/releases/tag/v9.9.9",
|
||||||
setupAssetUrl: "https://example.invalid/mismatch-setup.exe",
|
setupAssetUrl: "https://example.invalid/mismatch-setup.exe",
|
||||||
setupAssetName: "setup.exe",
|
setupAssetName: "setup.exe",
|
||||||
setupAssetDigest: "sha256:1111111111111111111111111111111111111111111111111111111111111111"
|
setupAssetDigest: "sha256:1111111111111111111111111111111111111111111111111111111111111111"
|
||||||
@ -286,33 +290,213 @@ describe("update", () => {
|
|||||||
expect(result.started).toBe(false);
|
expect(result.started).toBe(false);
|
||||||
expect(result.message).toMatch(/integrit|sha256|mismatch/i);
|
expect(result.message).toMatch(/integrit|sha256|mismatch/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("uses latest.yml SHA512 digest when API asset digest is missing", async () => {
|
||||||
|
const executablePayload = fs.readFileSync(process.execPath);
|
||||||
|
const digestSha512Hex = sha512Hex(executablePayload);
|
||||||
|
const digestSha512Base64 = Buffer.from(digestSha512Hex, "hex").toString("base64");
|
||||||
|
const requestedUrls: string[] = [];
|
||||||
|
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL): Promise<Response> => {
|
||||||
|
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
|
requestedUrls.push(url);
|
||||||
|
|
||||||
|
if (url.endsWith("/releases/tags/v9.9.9")) {
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
tag_name: "v9.9.9",
|
||||||
|
draft: false,
|
||||||
|
prerelease: false,
|
||||||
|
assets: [
|
||||||
|
{
|
||||||
|
name: "Real-Debrid-Downloader Setup 9.9.9.exe",
|
||||||
|
browser_download_url: "https://example.invalid/setup-no-digest.exe"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "latest.yml",
|
||||||
|
browser_download_url: "https://example.invalid/latest.yml"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}), {
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "application/json" }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.includes("latest.yml")) {
|
||||||
|
return new Response(
|
||||||
|
`version: 9.9.9\npath: Real-Debrid-Downloader-Setup-9.9.9.exe\nsha512: ${digestSha512Base64}\n`,
|
||||||
|
{
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "text/yaml" }
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.includes("setup-no-digest.exe")) {
|
||||||
|
return new Response(executablePayload, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/octet-stream",
|
||||||
|
"Content-Length": String(executablePayload.length)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response("missing", { status: 404 });
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const prechecked: UpdateCheckResult = {
|
||||||
|
updateAvailable: true,
|
||||||
|
currentVersion: APP_VERSION,
|
||||||
|
latestVersion: "9.9.9",
|
||||||
|
latestTag: "v9.9.9",
|
||||||
|
releaseUrl: "https://codeberg.org/owner/repo/releases/tag/v9.9.9",
|
||||||
|
setupAssetUrl: "https://example.invalid/setup-no-digest.exe",
|
||||||
|
setupAssetName: "Real-Debrid-Downloader Setup 9.9.9.exe",
|
||||||
|
setupAssetDigest: ""
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await installLatestUpdate("owner/repo", prechecked);
|
||||||
|
expect(result.started).toBe(true);
|
||||||
|
expect(requestedUrls.some((url) => url.endsWith("/releases/tags/v9.9.9"))).toBe(true);
|
||||||
|
expect(requestedUrls.some((url) => url.includes("latest.yml"))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects installer when latest.yml SHA512 digest does not match", async () => {
|
||||||
|
const executablePayload = fs.readFileSync(process.execPath);
|
||||||
|
const wrongDigestBase64 = Buffer.alloc(64, 0x13).toString("base64");
|
||||||
|
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL): Promise<Response> => {
|
||||||
|
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
|
|
||||||
|
if (url.endsWith("/releases/tags/v9.9.9")) {
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
tag_name: "v9.9.9",
|
||||||
|
draft: false,
|
||||||
|
prerelease: false,
|
||||||
|
assets: [
|
||||||
|
{
|
||||||
|
name: "Real-Debrid-Downloader Setup 9.9.9.exe",
|
||||||
|
browser_download_url: "https://example.invalid/setup-no-digest.exe"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "latest.yml",
|
||||||
|
browser_download_url: "https://example.invalid/latest.yml"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}), {
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "application/json" }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.includes("latest.yml")) {
|
||||||
|
return new Response(
|
||||||
|
`version: 9.9.9\npath: Real-Debrid-Downloader Setup 9.9.9.exe\nsha512: ${wrongDigestBase64}\n`,
|
||||||
|
{
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "text/yaml" }
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.includes("setup-no-digest.exe")) {
|
||||||
|
return new Response(executablePayload, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/octet-stream",
|
||||||
|
"Content-Length": String(executablePayload.length)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response("missing", { status: 404 });
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const prechecked: UpdateCheckResult = {
|
||||||
|
updateAvailable: true,
|
||||||
|
currentVersion: APP_VERSION,
|
||||||
|
latestVersion: "9.9.9",
|
||||||
|
latestTag: "v9.9.9",
|
||||||
|
releaseUrl: "https://codeberg.org/owner/repo/releases/tag/v9.9.9",
|
||||||
|
setupAssetUrl: "https://example.invalid/setup-no-digest.exe",
|
||||||
|
setupAssetName: "Real-Debrid-Downloader Setup 9.9.9.exe",
|
||||||
|
setupAssetDigest: ""
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await installLatestUpdate("owner/repo", prechecked);
|
||||||
|
expect(result.started).toBe(false);
|
||||||
|
expect(result.message).toMatch(/sha512|integrit|mismatch/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emits install progress events while downloading and launching update", async () => {
|
||||||
|
const executablePayload = fs.readFileSync(process.execPath);
|
||||||
|
const digest = sha256Hex(executablePayload);
|
||||||
|
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL): Promise<Response> => {
|
||||||
|
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
|
if (url.includes("progress-setup.exe")) {
|
||||||
|
return new Response(executablePayload, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/octet-stream",
|
||||||
|
"Content-Length": String(executablePayload.length)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new Response("missing", { status: 404 });
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const prechecked: UpdateCheckResult = {
|
||||||
|
updateAvailable: true,
|
||||||
|
currentVersion: APP_VERSION,
|
||||||
|
latestVersion: "9.9.9",
|
||||||
|
latestTag: "v9.9.9",
|
||||||
|
releaseUrl: "https://codeberg.org/owner/repo/releases/tag/v9.9.9",
|
||||||
|
setupAssetUrl: "https://example.invalid/progress-setup.exe",
|
||||||
|
setupAssetName: "setup.exe",
|
||||||
|
setupAssetDigest: `sha256:${digest}`
|
||||||
|
};
|
||||||
|
|
||||||
|
const progressEvents: UpdateInstallProgress[] = [];
|
||||||
|
const result = await installLatestUpdate("owner/repo", prechecked, (progress) => {
|
||||||
|
progressEvents.push(progress);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.started).toBe(true);
|
||||||
|
expect(progressEvents.some((entry) => entry.stage === "starting")).toBe(true);
|
||||||
|
expect(progressEvents.some((entry) => entry.stage === "downloading")).toBe(true);
|
||||||
|
expect(progressEvents.some((entry) => entry.stage === "verifying")).toBe(true);
|
||||||
|
expect(progressEvents.some((entry) => entry.stage === "launching")).toBe(true);
|
||||||
|
expect(progressEvents.some((entry) => entry.stage === "done")).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("normalizeUpdateRepo extended", () => {
|
describe("normalizeUpdateRepo extended", () => {
|
||||||
it("handles trailing slashes and extra path segments", () => {
|
it("handles trailing slashes and extra path segments", () => {
|
||||||
expect(normalizeUpdateRepo("owner/repo/")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("owner/repo/")).toBe("owner/repo");
|
||||||
expect(normalizeUpdateRepo("/owner/repo/")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("/owner/repo/")).toBe("owner/repo");
|
||||||
expect(normalizeUpdateRepo("https://github.com/owner/repo/tree/main/src")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("https://codeberg.org/owner/repo/tree/main/src")).toBe("owner/repo");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("handles ssh-style git URLs", () => {
|
it("handles ssh-style git URLs", () => {
|
||||||
expect(normalizeUpdateRepo("git@github.com:user/project.git")).toBe("user/project");
|
expect(normalizeUpdateRepo("git@codeberg.org:user/project.git")).toBe("user/project");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns default for malformed inputs", () => {
|
it("returns default for malformed inputs", () => {
|
||||||
expect(normalizeUpdateRepo("just-one-part")).toBe("Sucukdeluxe/real-debrid-downloader");
|
expect(normalizeUpdateRepo("just-one-part")).toBe("Administrator/real-debrid-downloader");
|
||||||
expect(normalizeUpdateRepo(" ")).toBe("Sucukdeluxe/real-debrid-downloader");
|
expect(normalizeUpdateRepo(" ")).toBe("Administrator/real-debrid-downloader");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rejects traversal-like owner or repo segments", () => {
|
it("rejects traversal-like owner or repo segments", () => {
|
||||||
expect(normalizeUpdateRepo("../owner/repo")).toBe("Sucukdeluxe/real-debrid-downloader");
|
expect(normalizeUpdateRepo("../owner/repo")).toBe("Administrator/real-debrid-downloader");
|
||||||
expect(normalizeUpdateRepo("owner/../repo")).toBe("Sucukdeluxe/real-debrid-downloader");
|
expect(normalizeUpdateRepo("owner/../repo")).toBe("Administrator/real-debrid-downloader");
|
||||||
expect(normalizeUpdateRepo("https://github.com/owner/../../repo")).toBe("Sucukdeluxe/real-debrid-downloader");
|
expect(normalizeUpdateRepo("https://codeberg.org/owner/../../repo")).toBe("Administrator/real-debrid-downloader");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("handles www prefix", () => {
|
it("handles www prefix", () => {
|
||||||
expect(normalizeUpdateRepo("https://www.github.com/owner/repo")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("https://www.codeberg.org/owner/repo")).toBe("owner/repo");
|
||||||
expect(normalizeUpdateRepo("www.github.com/owner/repo")).toBe("owner/repo");
|
expect(normalizeUpdateRepo("www.codeberg.org/owner/repo")).toBe("owner/repo");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -12,5 +12,5 @@
|
|||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
"types": ["node", "vite/client"]
|
"types": ["node", "vite/client"]
|
||||||
},
|
},
|
||||||
"include": ["src", "tests", "vite.config.ts"]
|
"include": ["src", "tests", "vite.config.mts"]
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user