mirror of
https://github.com/moku-project/Moku.git
synced 2026-06-13 09:19:56 -05:00
Compare commits
127 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d74790c3a0 | |||
| 0e93908bb2 | |||
| 074147f64f | |||
| f91b46cfa5 | |||
| 71ee4052f3 | |||
| 5e2114810e | |||
| b3fca70f27 | |||
| 68f25a2ea7 | |||
| 3d6b6430ed | |||
| 54307d4411 | |||
| f8f080eff3 | |||
| f41f8a9c22 | |||
| 8cef79b2b4 | |||
| 6c39ef538f | |||
| 081becdd60 | |||
| c891cb349c | |||
| 8cef74bb98 | |||
| bf071dcfc7 | |||
| da788e90ba | |||
| b0efb183e8 | |||
| 745b6993de | |||
| bd79169f71 | |||
| 6fccf02614 | |||
| fa7cfdc4e6 | |||
| 9c614b38f8 | |||
| 30e50b5a1b | |||
| 8ef0a14363 | |||
| 4e2ad6cae7 | |||
| 9e56b1176c | |||
| d025d07e07 | |||
| f988641446 | |||
| 3dad4bc729 | |||
| 1af21efebd | |||
| b7197a09a7 | |||
| 50dd8d7e35 | |||
| b2eaea6552 | |||
| 35aae6d85a | |||
| 28e5f5625e | |||
| b99e4d9a3d | |||
| d5f50c6495 | |||
| 89cfa50aff | |||
| 5e591411e4 | |||
| 8aaaf2451a | |||
| 75cc767b58 | |||
| d30c623200 | |||
| 017e9bc6da | |||
| 3b8088a2bf | |||
| 2c5320dd1f | |||
| 1e35f304b6 | |||
| 61339ea006 | |||
| f161fc08a2 | |||
| 239960683b | |||
| 3b5efc85d0 | |||
| 7df3846e75 | |||
| 01f123f5be | |||
| 0e2371096b | |||
| 47ae80a7d2 | |||
| d98547d540 | |||
| 897ecfd316 | |||
| e3abc72f1b | |||
| 6b56db7cf2 | |||
| 93cedca6b5 | |||
| 9f8bf6ffc1 | |||
| 39f813b4d7 | |||
| 18ac38e888 | |||
| 1e2e923eab | |||
| d3a40b9152 | |||
| b1444582a3 | |||
| bee8117aac | |||
| 0bea9c22cb | |||
| bf3f68b996 | |||
| 4b728ad5b7 | |||
| f3f91f1555 | |||
| 062662781a | |||
| cbf8a7fe13 | |||
| 5af80213c7 | |||
| 17d739a1cd | |||
| 2867dc9612 | |||
| a9dc047b44 | |||
| ef190ae66f | |||
| 6d921944ac | |||
| 244447da9b | |||
| f05f781b5b | |||
| f7c5aebf29 | |||
| e09ae9d2e7 | |||
| 7b2ae74c02 | |||
| 0d53e3f102 | |||
| 093b395cc1 | |||
| efdd8ff95d | |||
| c0f0ff9bd3 | |||
| 3f6049c12d | |||
| 5451a2654b | |||
| e625755c5e | |||
| bd95bf4eb1 | |||
| b4d680ddd1 | |||
| d1b7429b5d | |||
| 000195be89 | |||
| 399d429142 | |||
| b79ee99e8a | |||
| 80c4b9d9be | |||
| 4584e6e69e | |||
| 83711c155d | |||
| 3702a25813 | |||
| a71cc719ba | |||
| 1801fecdbb | |||
| 0cd799f450 | |||
| 5dab7761bc | |||
| 552a11a517 | |||
| c8ec6d6b90 | |||
| daaeae00fe | |||
| 79cb2f7c56 | |||
| 4d3dfdbec6 | |||
| 78573eacb1 | |||
| 1bb7da3b22 | |||
| dd0cf9372d | |||
| 50928c6343 | |||
| 170493aa71 | |||
| c009bd71fc | |||
| 4df7f416a7 | |||
| 63209cb828 | |||
| 2c1391c378 | |||
| 41fd4a820c | |||
| 9f3c6d2ac3 | |||
| f5b3f76b5d | |||
| 528f966b1f | |||
| 75e8bc5986 | |||
| 8123053a40 |
@@ -88,10 +88,10 @@ jobs:
|
||||
- name: Download Suwayomi (Linux x64)
|
||||
run: |
|
||||
curl -fsSL \
|
||||
"https://github.com/Suwayomi/Suwayomi-Server/releases/download/v2.1.1867/Suwayomi-Server-v2.1.1867-linux-x64.tar.gz" \
|
||||
"https://github.com/Suwayomi/Suwayomi-Server-preview/releases/download/v2.1.2087/Suwayomi-Server-v2.1.2087-linux-x64.tar.gz" \
|
||||
-o suwayomi-linux.tar.gz
|
||||
|
||||
echo "b2344bd73c4e26bede63cdb4b44b1b4168d8a8500b3b2b1a0219519a3ef708fe suwayomi-linux.tar.gz" | sha256sum -c -
|
||||
echo "888bee202649ce7e3e3468a729c4084fb465f024b4033cab3f8ab98b0c66fe76 suwayomi-linux.tar.gz" | sha256sum -c -
|
||||
|
||||
mkdir -p suwayomi-extracted
|
||||
tar -xzf suwayomi-linux.tar.gz -C suwayomi-extracted --strip-components=1
|
||||
|
||||
@@ -79,7 +79,7 @@ jobs:
|
||||
download_suwayomi() {
|
||||
local asset="$1" sha="$2" outdir="$3"
|
||||
curl -fsSL \
|
||||
"https://github.com/Suwayomi/Suwayomi-Server/releases/download/v2.1.1867/${asset}" \
|
||||
"https://github.com/Suwayomi/Suwayomi-Server-preview/releases/download/v2.1.2087/${asset}" \
|
||||
-o "${outdir}.tar.gz"
|
||||
echo "${sha} ${outdir}.tar.gz" | shasum -a 256 -c -
|
||||
mkdir -p "${outdir}"
|
||||
@@ -87,13 +87,13 @@ jobs:
|
||||
}
|
||||
|
||||
download_suwayomi \
|
||||
"Suwayomi-Server-v2.1.1867-macOS-arm64.tar.gz" \
|
||||
"c80abdbba29f7895e9556c6c9481368557d5f930b5f69bcb30639ba498925f3c" \
|
||||
"Suwayomi-Server-v2.1.2087-macOS-arm64.tar.gz" \
|
||||
"59f73a53a139d5d843e16cab4f3ac425a410add6bee0a60920fa26eb0a4b8a5c" \
|
||||
"suwayomi-arm64"
|
||||
|
||||
download_suwayomi \
|
||||
"Suwayomi-Server-v2.1.1867-macOS-x64.tar.gz" \
|
||||
"c7590aeb645dd7135a05b9f3ea1fee384a4abeb465c0b3638d5b738d20dfe174" \
|
||||
"Suwayomi-Server-v2.1.2087-macOS-x64.tar.gz" \
|
||||
"da7e664e4c2615a0b9eac09ee38fe979feee1d6c0b266e19dba1ceea8ae3795c" \
|
||||
"suwayomi-x64"
|
||||
|
||||
- name: Stage Suwayomi sidecars
|
||||
|
||||
@@ -79,9 +79,9 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
curl -fsSL \
|
||||
"https://github.com/Suwayomi/Suwayomi-Server/releases/download/v2.1.1867/Suwayomi-Server-v2.1.1867-windows-x64.zip" \
|
||||
"https://github.com/Suwayomi/Suwayomi-Server-preview/releases/download/v2.1.2087/Suwayomi-Server-v2.1.2087-windows-x64.zip" \
|
||||
-o suwayomi-windows.zip
|
||||
echo "ab6687d278e0dd0984f67abbc853511a7e764f84b126a35d09bfd9b0307321ff suwayomi-windows.zip" | sha256sum -c -
|
||||
echo "65c3ec544190bc4e52f8ba05b49c87448421d9825aaaeb902cb4e34e69ff7207 suwayomi-windows.zip" | sha256sum -c -
|
||||
unzip -q suwayomi-windows.zip -d suwayomi-raw
|
||||
|
||||
- name: Extract Suwayomi bundle
|
||||
|
||||
+21
-8
@@ -1,26 +1,34 @@
|
||||
# --- Build Artifacts ---
|
||||
node_modules/
|
||||
suwayomi-raw/
|
||||
suwayomi-windows.zip
|
||||
dist/
|
||||
dist-tauri/
|
||||
target/
|
||||
bin/
|
||||
out/
|
||||
notes/
|
||||
|
||||
# --- Nix ---
|
||||
.direnv/
|
||||
result
|
||||
result-*
|
||||
|
||||
# --- Logs ---
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.test
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# --- IDEs & OS ---
|
||||
.output
|
||||
.vercel
|
||||
.netlify
|
||||
.wrangler
|
||||
/.svelte-kit
|
||||
/build
|
||||
|
||||
.vscode/
|
||||
.idea/
|
||||
.DS_Store
|
||||
@@ -30,14 +38,19 @@ yarn-error.log*
|
||||
*.sln
|
||||
*.swp
|
||||
|
||||
# --- Tauri specific ---
|
||||
src-tauri/target/
|
||||
src-tauri/binaries/
|
||||
src-tauri/gen/
|
||||
|
||||
# --- Flatpak build artifacts ---
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
|
||||
build-dir/
|
||||
repo/
|
||||
dist/
|
||||
packaging/frontend-dist.tar.gz
|
||||
*.flatpak
|
||||
.flatpak-builder/\n# --- Staged sidecar binaries (platform-specific, never commit) ---\nsrc-tauri/binaries/
|
||||
./flatpak-builder
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
pkgname=moku
|
||||
pkgver=0.9.1
|
||||
pkgver=0.9.4
|
||||
pkgrel=1
|
||||
pkgdesc="Native Linux manga reader frontend for Suwayomi-Server"
|
||||
arch=('x86_64')
|
||||
@@ -13,27 +13,46 @@ depends=(
|
||||
)
|
||||
makedepends=(
|
||||
'rust'
|
||||
'cargo'
|
||||
'nodejs'
|
||||
'pnpm'
|
||||
)
|
||||
optdepends=(
|
||||
'discord: Discord rich presence'
|
||||
)
|
||||
options=('!strip')
|
||||
source=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/moku-project/Moku/archive/refs/tags/v$pkgver.tar.gz"
|
||||
"Suwayomi-Server-v2.1.1867.jar::https://github.com/Suwayomi/Suwayomi-Server/releases/download/v2.1.1867/Suwayomi-Server-v2.1.1867.jar"
|
||||
"Suwayomi-Server-v2.1.2087.jar::https://github.com/Suwayomi/Suwayomi-Server-preview/releases/download/v2.1.2087/Suwayomi-Server-v2.1.2087.jar"
|
||||
)
|
||||
noextract=("Suwayomi-Server-v2.1.2087.jar")
|
||||
sha256sums=(
|
||||
'fc1c8268b812e70e56460c8930ca8ae83bcd30eea5903ddfef4e30a3a9a5c1cc'
|
||||
'f589a422674252394c13b289a9c8be691905bf583efb7f4d5f1501ae5e91e6b3'
|
||||
)
|
||||
b2sums=(
|
||||
'SKIP'
|
||||
'SKIP'
|
||||
'51e307c2581e4e1a002991ab3e3a77503c8b074c42695987a984a7382d0ac5af'
|
||||
)
|
||||
|
||||
prepare() {
|
||||
cd "Moku-$pkgver"
|
||||
pnpm install --frozen-lockfile
|
||||
sed -i 's/^lto\s*=\s*true/lto = "thin"/' src-tauri/Cargo.toml
|
||||
mkdir -p src-tauri/.cargo
|
||||
cat > src-tauri/.cargo/config.toml << 'EOF'
|
||||
[target.x86_64-unknown-linux-gnu]
|
||||
linker = "x86_64-linux-gnu-gcc"
|
||||
EOF
|
||||
}
|
||||
|
||||
build() {
|
||||
cd "Moku-$pkgver"
|
||||
pnpm build
|
||||
local fixed_cflags="${CFLAGS/-march=native/-march=x86-64}"
|
||||
fixed_cflags="${fixed_cflags/-flto=auto/}"
|
||||
local fixed_cxxflags="${CXXFLAGS/-march=native/-march=x86-64}"
|
||||
fixed_cxxflags="${fixed_cxxflags/-flto=auto/}"
|
||||
CFLAGS="$fixed_cflags" \
|
||||
CXXFLAGS="$fixed_cxxflags" \
|
||||
TAURI_SKIP_DEVSERVER_CHECK=true cargo build \
|
||||
--release \
|
||||
--manifest-path src-tauri/Cargo.toml
|
||||
@@ -45,11 +64,11 @@ package() {
|
||||
install -Dm755 src-tauri/target/release/moku \
|
||||
"$pkgdir/usr/bin/moku"
|
||||
|
||||
install -Dm644 "$srcdir/Suwayomi-Server-v2.1.1867.jar" \
|
||||
install -Dm644 "$srcdir/Suwayomi-Server-v2.1.2087.jar" \
|
||||
"$pkgdir/usr/lib/moku/tachidesk/Suwayomi-Server.jar"
|
||||
|
||||
install -dm755 "$pkgdir/usr/lib/moku/tachidesk/default-conf"
|
||||
cat > "$pkgdir/usr/lib/moku/tachidesk/default-conf/server.conf" << 'EOF'
|
||||
cat > "$pkgdir/usr/lib/moku/tachidesk/default-conf/server.conf" << 'CONF'
|
||||
server.ip = "127.0.0.1"
|
||||
server.port = 4567
|
||||
server.webUIEnabled = false
|
||||
@@ -60,22 +79,22 @@ server.autoDownloadNewChapters = false
|
||||
server.globalUpdateInterval = 12
|
||||
server.maxSourcesInParallel = 6
|
||||
server.extensionRepos = []
|
||||
EOF
|
||||
CONF
|
||||
|
||||
install -Dm755 /dev/stdin "$pkgdir/usr/bin/moku-suwayomi" << 'EOF'
|
||||
install -Dm755 /dev/stdin "$pkgdir/usr/bin/moku-suwayomi" << 'LAUNCHER'
|
||||
#!/bin/sh
|
||||
DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/moku/tachidesk"
|
||||
DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/Tachidesk"
|
||||
mkdir -p "$DATA_DIR"
|
||||
|
||||
if [ ! -f "$DATA_DIR/server.conf" ]; then
|
||||
cp /usr/lib/moku/tachidesk/default-conf/server.conf "$DATA_DIR/server.conf"
|
||||
cp /usr/lib/moku/tachidesk/default-conf/server.conf "$DATA_DIR/server.conf"
|
||||
fi
|
||||
|
||||
sed -i \
|
||||
-e 's|server\.webUIEnabled.*|server.webUIEnabled = false|' \
|
||||
-e 's|server\.initialOpenInBrowserEnabled.*|server.initialOpenInBrowserEnabled = false|' \
|
||||
-e 's|server\.systemTrayEnabled.*|server.systemTrayEnabled = false|' \
|
||||
"$DATA_DIR/server.conf"
|
||||
-e 's|server\.webUIEnabled.*|server.webUIEnabled = false|' \
|
||||
-e 's|server\.initialOpenInBrowserEnabled.*|server.initialOpenInBrowserEnabled = false|' \
|
||||
-e 's|server\.systemTrayEnabled.*|server.systemTrayEnabled = false|' \
|
||||
"$DATA_DIR/server.conf"
|
||||
|
||||
grep -q 'server\.webUIEnabled' "$DATA_DIR/server.conf" || echo 'server.webUIEnabled = false' >> "$DATA_DIR/server.conf"
|
||||
grep -q 'server\.initialOpenInBrowserEnabled' "$DATA_DIR/server.conf" || echo 'server.initialOpenInBrowserEnabled = false' >> "$DATA_DIR/server.conf"
|
||||
@@ -87,13 +106,13 @@ export _JAVA_OPTIONS="-Djava.awt.headless=true"
|
||||
export JAVA_TOOL_OPTIONS="-Djava.awt.headless=true"
|
||||
|
||||
exec java \
|
||||
-Djava.awt.headless=true \
|
||||
-Dapple.awt.UIElement=true \
|
||||
-Dsun.java2d.noddraw=true \
|
||||
-Dsun.awt.disablegui=true \
|
||||
-Dsuwayomi.tachidesk.config.server.rootDir="$DATA_DIR" \
|
||||
-jar /usr/lib/moku/tachidesk/Suwayomi-Server.jar
|
||||
EOF
|
||||
-Djava.awt.headless=true \
|
||||
-Dapple.awt.UIElement=true \
|
||||
-Dsun.java2d.noddraw=true \
|
||||
-Dsun.awt.disablegui=true \
|
||||
-Dsuwayomi.tachidesk.config.server.rootDir="$DATA_DIR" \
|
||||
-jar /usr/lib/moku/tachidesk/Suwayomi-Server.jar
|
||||
LAUNCHER
|
||||
|
||||
install -Dm644 packaging/io.github.moku_project.Moku.desktop \
|
||||
"$pkgdir/usr/share/applications/io.github.moku_project.Moku.desktop"
|
||||
@@ -105,6 +124,6 @@ EOF
|
||||
"$pkgdir/usr/share/icons/hicolor/256x256/apps/io.github.moku_project.Moku.png"
|
||||
install -Dm644 packaging/io.github.moku_project.Moku.metainfo.xml \
|
||||
"$pkgdir/usr/share/metainfo/io.github.moku_project.Moku.metainfo.xml"
|
||||
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
install -Dm644 LICENSE \
|
||||
"$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
}
|
||||
@@ -1,173 +1,42 @@
|
||||
<div align="center">
|
||||
<img src="docs/banner.svg" width="100%" alt="Moku" />
|
||||
</div>
|
||||
# sv
|
||||
|
||||
<div align="center">
|
||||
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
|
||||
|
||||
[](https://github.com/moku-project/Moku/releases/latest)
|
||||
[](https://github.com/moku-project/Moku/commits/main)
|
||||
[](https://github.com/moku-project/Moku)
|
||||
[](https://discord.gg/x97hj8zR72)
|
||||
## Creating a project
|
||||
|
||||
</div>
|
||||
If you're seeing this, you've probably already done this step. Congrats!
|
||||
|
||||
<br/>
|
||||
|
||||
Moku is a fast, minimal manga reader frontend for [Suwayomi-Server](https://github.com/Suwayomi/Suwayomi-Server). It wraps Suwayomi's GraphQL API in a lightweight Tauri app — no Electron overhead.
|
||||
|
||||
---
|
||||
|
||||
## Screenshots
|
||||
|
||||
<div align="center">
|
||||
<img src="docs/screenshots/Moku-Home.png" width="100%" alt="Home" />
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<img src="docs/screenshots/Moku-Search.png" width="49%" alt="Search" />
|
||||
<img src="docs/screenshots/Moku-TagSearch.png" width="49%" alt="Tag Search" />
|
||||
<img src="docs/screenshots/Moku-Settings.png" width="49%" alt="Settings" />
|
||||
<img src="docs/screenshots/Moku-Preview.png" width="49%" alt="Preview" />
|
||||
<img src="docs/screenshots/Moku-Downloads.png" width="49%" alt="Downloads" />
|
||||
<img src="docs/screenshots/Moku-ReaderSettings.png" width="49%" alt="Reader Settings" />
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<a href="docs/screenshots" style="color: #a8c4a8;">View all screenshots →</a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **Library management** — organize manga into folders, track unread counts, filter by genre
|
||||
- **Per-folder sorting & filtering** — each folder has its own independent sort (unread, A–Z, recently read, latest chapter, and more) and publication status filter (Ongoing, Completed, Hiatus, etc.)
|
||||
- **Built-in reader** — single page, long strip, configurable fit modes, customizable keybinds
|
||||
- **Markers** — pin color-coded notes to any page while reading; markers appear as dots on the progress bar and are browseable under Series Detail → Manage → Markers
|
||||
- **Extension support** — install and manage Suwayomi extensions directly from the app
|
||||
- **Download management** — queue and monitor chapter downloads with progress toasts
|
||||
- **Automation** — pre-download titles automatically and optionally delete chapters after they're marked as read (accessible from Series Detail)
|
||||
- **Discord Rich Presence** — shows the manga title, current chapter, and an elapsed timer in your Discord status; configurable in Settings → General
|
||||
- **Auto-start server** — optionally launch Suwayomi in the background on startup
|
||||
- **Multiple themes** — Dark, Light, Midnight, Warm, High Contrast, and more
|
||||
- **Auto-updates** — in-app update checker with silent background notifications
|
||||
- **Improved NSFW filtering** — expanded tag parser gives the Hide NSFW setting better coverage across sources
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
### Windows
|
||||
|
||||
**winget:**
|
||||
|
||||
```powershell
|
||||
winget install Moku.Moku
|
||||
```sh
|
||||
# create a new project
|
||||
npx sv create my-app
|
||||
```
|
||||
|
||||
> Thanks to [@frozenKelp](https://github.com/frozenKelp) for setting up and maintaining the winget package through v0.9.0.
|
||||
To recreate this project with the same configuration:
|
||||
|
||||
Or download the `.exe` installer from the [releases page](https://github.com/moku-project/Moku/releases/latest). Suwayomi-Server and a JRE are bundled.
|
||||
|
||||
### Linux (Flatpak, recommended)
|
||||
|
||||
Suwayomi-Server and a bundled JRE are included — no separate install needed.
|
||||
|
||||
```bash
|
||||
flatpak install io.github.moku_app.Moku
|
||||
```sh
|
||||
# recreate this project
|
||||
pnpm dlx sv@0.15.3 create --template minimal --types ts --install pnpm .
|
||||
```
|
||||
|
||||
Or download the latest `moku.flatpak` from the [releases page](https://github.com/moku-project/Moku/releases/latest) and install manually:
|
||||
## Developing
|
||||
|
||||
```bash
|
||||
flatpak install moku.flatpak
|
||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
|
||||
# or start the server and open the app in a new browser tab
|
||||
npm run dev -- --open
|
||||
```
|
||||
|
||||
### Nix
|
||||
## Building
|
||||
|
||||
```bash
|
||||
nix run github:moku-project/Moku
|
||||
To create a production version of your app:
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
|
||||
Add to your flake:
|
||||
You can preview the production build with `npm run preview`.
|
||||
|
||||
```nix
|
||||
inputs.moku.url = "github:moku-project/Moku";
|
||||
```
|
||||
|
||||
### macOS
|
||||
|
||||
Download the `.dmg` from the [releases page](https://github.com/moku-project/Moku/releases/latest).
|
||||
|
||||
> **Note:** Builds are ad-hoc signed. On first launch you may need to run:
|
||||
> ```bash
|
||||
> xattr -rd com.apple.quarantine /Applications/Moku.app
|
||||
> ```
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
If you're not using the bundled Flatpak or Windows installer, [Suwayomi-Server](https://github.com/Suwayomi/Suwayomi-Server) must be running separately. By default Moku connects to `http://127.0.0.1:4567`.
|
||||
|
||||
You can point Moku at any Suwayomi instance — local or remote — via **Settings → General → Server URL**.
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
**Prerequisites:** [Rust](https://rustup.rs), [Node.js](https://nodejs.org), [pnpm](https://pnpm.io), and [Tauri v2 prerequisites](https://tauri.app/start/prerequisites/).
|
||||
|
||||
```bash
|
||||
git clone https://github.com/moku-project/Moku
|
||||
cd Moku
|
||||
pnpm install
|
||||
pnpm tauri:dev
|
||||
```
|
||||
|
||||
Or with Nix:
|
||||
|
||||
```bash
|
||||
nix develop
|
||||
pnpm install
|
||||
pnpm tauri:dev
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Stack
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| [Tauri v2](https://tauri.app) | Native app shell |
|
||||
| [Svelte 5](https://svelte.dev) + [TypeScript](https://www.typescriptlang.org) | UI |
|
||||
| [Vite](https://vitejs.dev) | Frontend bundler |
|
||||
| [Crane](https://github.com/ipetkov/crane) | Nix Rust builds |
|
||||
|
||||
---
|
||||
|
||||
## Community
|
||||
|
||||
Questions, feedback, or just want to hang out — join the Discord.
|
||||
|
||||
[](https://discord.gg/x97hj8zR72)
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Distributed under the [Apache 2.0 License](./LICENSE).
|
||||
|
||||
---
|
||||
|
||||
## Disclaimer
|
||||
|
||||
Moku does not host or distribute any content. The developers have no affiliation with any content providers accessible through connected sources.
|
||||
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.
|
||||
|
||||
@@ -7,10 +7,7 @@ Major Revisions:
|
||||
|
||||
Minor Revisions:
|
||||
- Investigate feasibility of Multi-Page Screenshot (Reader)
|
||||
- Add Hover Info on Library (Make sure doesn't conflict with additional clicks)
|
||||
- Revise Migration (https://github.com/Suwayomi/Suwayomi-WebUI/pull/1073)
|
||||
- Look at how Manga are Organized in WebUI and Implement into Series-Detail (Chapter Display is Off)
|
||||
|
||||
|
||||
Priority Bugs:
|
||||
- Fix Library-Refresh System (TESTING)
|
||||
@@ -19,21 +16,24 @@ Priority Bugs:
|
||||
- Allow User to Wipe Suwayomi (Scratch)
|
||||
- If Possible, Component based Wipe (Library, Etc)
|
||||
|
||||
|
||||
In-Progress:
|
||||
- Enable Cloudflare Bypass (Suwayomi Config) (Requires Patching)
|
||||
Pending/On-Hold:
|
||||
- Enable Cloudflare Bypass (Suwayomi Config) (Requires Patching)
|
||||
- Working on 3D Display Cards
|
||||
- Add Flathub Support (Pending Video)
|
||||
|
||||
- Change Auto-Link Threshold
|
||||
- Fix Auto-Link De-dupe for Images
|
||||
- Optimize Auto-Link Latency (IP)
|
||||
|
||||
In-Progress:
|
||||
- Fix Tracking Login
|
||||
- Pasting OAuth URL is not User-Friendly, Look for Alternatives
|
||||
|
||||
- Tracking
|
||||
- Fix SeriesDetail Tracking Window (Maybe Link to TrackingPanel)
|
||||
|
||||
- Hide Completed from Library Settting
|
||||
- Apply Syer's Fix for Library on Backup Load (Manga Metadata)
|
||||
- Note User's have to always install extensions manually
|
||||
- Create "Missing Source" for Manga
|
||||
|
||||
- Wire Series-Detail Refresh to Fix Manga-Metadata (MAJOR)
|
||||
|
||||
- UI LOGIN DOES NOT WORK OFFLINE
|
||||
Notes from last time:
|
||||
- Currently working on #42, just need to mount panel and fix button in reader
|
||||
+364
@@ -0,0 +1,364 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { platform } from "@tauri-apps/plugin-os";
|
||||
import { store, updateSettings, setActiveDownloads } from "@store/state.svelte";
|
||||
import { downloadStore } from "@features/downloads/store/downloadState.svelte";
|
||||
import { boot, initStore, startProbe, stopProbe, retryBoot, bypassBoot } from "@store/boot.svelte";
|
||||
import { initRpc, setIdle, clearReading, destroyRpc } from "@store/discord";
|
||||
import { applyTheme } from "@core/theme";
|
||||
import { applyZoom, mountZoomKey, mountIdleDetection } from "@core/ui";
|
||||
import { checkForUpdateSilently } from "@core/updater";
|
||||
import Layout from "@shared/chrome/Layout.svelte";
|
||||
import Reader from "@features/reader/components/Reader.svelte";
|
||||
import Settings from "@features/settings/components/Settings.svelte";
|
||||
import ThemeEditor from "@features/settings/components/ThemeEditor.svelte";
|
||||
import TitleBar from "@shared/chrome/TitleBar.svelte";
|
||||
import Toaster from "@shared/chrome/Toaster.svelte";
|
||||
import SplashScreen from "@shared/chrome/SplashScreen.svelte";
|
||||
import MangaPreview from "@shared/manga/MangaPreview.svelte";
|
||||
import AuthGate from "@shared/chrome/AuthGate.svelte";
|
||||
|
||||
const win = getCurrentWindow();
|
||||
void platform();
|
||||
|
||||
let appReady = $state(false);
|
||||
let idle = $state(false);
|
||||
let devSplash = $state(false);
|
||||
|
||||
let themeEditorOpen = $state(false);
|
||||
let themeEditorEditId = $state<string | null>(null);
|
||||
|
||||
let closeDialogOpen = $state(false);
|
||||
let closeRemember = $state(false);
|
||||
|
||||
function openThemeEditor(id?: string | null) {
|
||||
themeEditorEditId = id ?? null;
|
||||
themeEditorOpen = true;
|
||||
}
|
||||
|
||||
function closeThemeEditor() {
|
||||
themeEditorOpen = false;
|
||||
themeEditorEditId = null;
|
||||
}
|
||||
|
||||
async function doQuit() {
|
||||
if (store.settings.autoStartServer) {
|
||||
await Promise.race([
|
||||
invoke("kill_server").catch(() => {}),
|
||||
new Promise(res => setTimeout(res, 2000)),
|
||||
]);
|
||||
}
|
||||
await invoke("exit_app");
|
||||
}
|
||||
|
||||
async function doHide() {
|
||||
await win.hide();
|
||||
}
|
||||
|
||||
async function handleCloseRequested() {
|
||||
const action = store.settings.closeAction ?? "ask";
|
||||
if (action === "tray") { await doHide(); return; }
|
||||
if (action === "quit") { await doQuit(); return; }
|
||||
closeDialogOpen = true;
|
||||
}
|
||||
|
||||
async function confirmClose(choice: "tray" | "quit") {
|
||||
closeDialogOpen = false;
|
||||
if (closeRemember) updateSettings({ closeAction: choice });
|
||||
closeRemember = false;
|
||||
if (choice === "tray") await doHide();
|
||||
else await doQuit();
|
||||
}
|
||||
|
||||
$effect(() => { void store.settings.theme; applyTheme(); });
|
||||
$effect(() => { void store.settings.uiZoom; applyZoom(); });
|
||||
$effect(() => mountZoomKey());
|
||||
|
||||
$effect(() => {
|
||||
if (!appReady) return;
|
||||
return mountIdleDetection(
|
||||
() => { idle = true; },
|
||||
() => { if (idle) idle = false; },
|
||||
);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!appReady) return;
|
||||
const timer = setTimeout(checkForUpdateSilently, 5_000);
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!appReady) return;
|
||||
downloadStore.poll();
|
||||
const dlInterval = setInterval(() => downloadStore.poll(), 2000);
|
||||
return () => clearInterval(dlInterval);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (store.settings.discordRpc) {
|
||||
initRpc();
|
||||
} else {
|
||||
clearReading();
|
||||
destroyRpc();
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!store.activeChapter && store.settings.discordRpc) setIdle();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const next = downloadStore.queue.slice();
|
||||
downloadStore.detectTransitions(next);
|
||||
});
|
||||
|
||||
onMount(async () => {
|
||||
document.addEventListener("contextmenu", e => e.preventDefault());
|
||||
(window as any).__mokuShowSplash = () => { devSplash = true; };
|
||||
|
||||
applyZoom();
|
||||
|
||||
store.isFullscreen = await win.isFullscreen();
|
||||
|
||||
const unlistenResize = await win.onResized(async () => {
|
||||
store.isFullscreen = await win.isFullscreen();
|
||||
});
|
||||
|
||||
const unlistenScale = await win.onScaleChanged(async () => {
|
||||
applyZoom();
|
||||
});
|
||||
|
||||
const unlistenClose = await win.listen("tauri://close-requested", handleCloseRequested);
|
||||
|
||||
await initStore();
|
||||
startProbe();
|
||||
|
||||
if (store.settings.autoStartServer) {
|
||||
invoke<void>("spawn_server", {
|
||||
binary: store.settings.serverBinary,
|
||||
webUiEnabled: store.settings.suwayomiWebUI ?? false,
|
||||
}).catch((err: any) => {
|
||||
if (err?.kind === "NotConfigured") boot.notConfigured = true;
|
||||
else console.warn("Could not start server:", err);
|
||||
});
|
||||
}
|
||||
|
||||
const unlistenDownload = await listen<{ chapterId: number; mangaId: number; progress: number }[]>(
|
||||
"download-progress",
|
||||
e => setActiveDownloads(e.payload),
|
||||
);
|
||||
|
||||
return () => {
|
||||
stopProbe();
|
||||
unlistenResize();
|
||||
unlistenScale();
|
||||
unlistenDownload();
|
||||
unlistenClose();
|
||||
destroyRpc();
|
||||
delete (window as any).__mokuShowSplash;
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if devSplash}
|
||||
<SplashScreen mode="idle" showFps showCards={store.settings.splashCards ?? true}
|
||||
onDismiss={() => setTimeout(() => devSplash = false, 340)} />
|
||||
|
||||
{:else if !appReady && !boot.loginRequired}
|
||||
<SplashScreen mode="loading" ringFull={boot.serverProbeOk}
|
||||
failed={boot.failed} notConfigured={boot.notConfigured}
|
||||
showCards={store.settings.splashCards ?? true}
|
||||
onReady={() => { appReady = true; }}
|
||||
onRetry={retryBoot}
|
||||
onBypass={() => bypassBoot(() => { appReady = true; })} />
|
||||
|
||||
{:else if boot.loginRequired}
|
||||
<SplashScreen mode="loading" ringFull={true} showCards={store.settings.splashCards ?? true} />
|
||||
<AuthGate onReady={() => { appReady = true; }} />
|
||||
|
||||
{:else}
|
||||
{#if idle && !store.activeChapter}
|
||||
<SplashScreen mode="idle" showCards={store.settings.splashCards ?? true}
|
||||
onDismiss={() => { idle = false; }} />
|
||||
{/if}
|
||||
|
||||
{#if boot.sessionExpired}
|
||||
<SplashScreen mode="loading" ringFull={true} showCards={store.settings.splashCards ?? true} />
|
||||
<AuthGate onReady={() => { boot.sessionExpired = false; }} />
|
||||
{/if}
|
||||
|
||||
<div id="app-shell" class="root">
|
||||
{#if !store.activeChapter}<TitleBar onClose={handleCloseRequested} />{/if}
|
||||
<div class="content">
|
||||
{#if store.activeChapter}<Reader />{:else}<Layout />{/if}
|
||||
</div>
|
||||
{#if store.settingsOpen}<Settings onOpenThemeEditor={openThemeEditor} />{/if}
|
||||
{#if themeEditorOpen}
|
||||
<ThemeEditor bind:editingId={themeEditorEditId} onClose={closeThemeEditor} />
|
||||
{/if}
|
||||
<MangaPreview />
|
||||
<Toaster />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if closeDialogOpen}
|
||||
<div class="close-backdrop" role="presentation" onclick={() => { closeDialogOpen = false; closeRemember = false; }}>
|
||||
<div class="close-dialog" role="dialog" aria-modal="true" onclick={(e) => e.stopPropagation()}>
|
||||
<div class="close-header">
|
||||
<p class="close-title">Close Moku?</p>
|
||||
<p class="close-sub">Choose how the app should exit.</p>
|
||||
</div>
|
||||
<div class="close-actions">
|
||||
<button class="close-btn" onclick={() => confirmClose("tray")}>
|
||||
<span class="close-btn-label">Minimize to Tray</span>
|
||||
<span class="close-btn-desc">Keep running in the background</span>
|
||||
</button>
|
||||
<button class="close-btn close-btn-danger" onclick={() => confirmClose("quit")}>
|
||||
<span class="close-btn-label">Quit</span>
|
||||
<span class="close-btn-desc">Stop Moku entirely</span>
|
||||
</button>
|
||||
</div>
|
||||
<button class="close-remember" onclick={() => closeRemember = !closeRemember}>
|
||||
<span class="close-remember-toggle" class:on={closeRemember}><span class="close-remember-thumb"></span></span>
|
||||
<span class="close-remember-label">Remember my choice</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.root { display: flex; flex-direction: column; height: 100%; overflow: hidden; }
|
||||
.content { flex: 1; overflow: hidden; }
|
||||
|
||||
.close-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: var(--z-modal);
|
||||
}
|
||||
|
||||
.close-dialog {
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: var(--radius-2xl);
|
||||
padding: var(--sp-5);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
width: 300px;
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(255,255,255,0.04) inset,
|
||||
0 20px 60px rgba(0,0,0,0.65),
|
||||
0 6px 20px rgba(0,0,0,0.35);
|
||||
}
|
||||
|
||||
.close-header { display: flex; flex-direction: column; gap: 3px; }
|
||||
|
||||
.close-title {
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--text-base);
|
||||
font-weight: var(--weight-medium);
|
||||
color: var(--text-primary);
|
||||
letter-spacing: var(--tracking-tight);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.close-sub {
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--text-xs);
|
||||
color: var(--text-faint);
|
||||
letter-spacing: var(--tracking-wide);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.close-actions { display: flex; flex-direction: column; gap: var(--sp-1); }
|
||||
|
||||
.close-btn {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
width: 100%;
|
||||
padding: 10px var(--sp-3);
|
||||
border-radius: var(--radius-lg);
|
||||
border: 1px solid var(--border-dim);
|
||||
background: var(--bg-raised);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background var(--t-base), border-color var(--t-base);
|
||||
}
|
||||
.close-btn:hover { background: var(--bg-overlay); border-color: var(--border-strong); }
|
||||
|
||||
.close-btn-danger { border-color: color-mix(in srgb, var(--color-error) 30%, transparent); }
|
||||
.close-btn-danger:hover { background: var(--color-error-bg); border-color: color-mix(in srgb, var(--color-error) 55%, transparent); }
|
||||
.close-btn-danger .close-btn-label { color: var(--color-error); }
|
||||
.close-btn-danger .close-btn-desc { color: color-mix(in srgb, var(--color-error) 55%, var(--text-faint)); }
|
||||
|
||||
.close-btn-label {
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--text-secondary);
|
||||
font-weight: var(--weight-medium);
|
||||
}
|
||||
|
||||
.close-btn-desc {
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--text-2xs);
|
||||
color: var(--text-faint);
|
||||
letter-spacing: var(--tracking-wide);
|
||||
}
|
||||
|
||||
.close-remember {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding: var(--sp-1) 0 0;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.close-remember-toggle {
|
||||
position: relative;
|
||||
width: 28px;
|
||||
height: 16px;
|
||||
border-radius: var(--radius-full);
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--bg-overlay);
|
||||
flex-shrink: 0;
|
||||
transition: background var(--t-base), border-color var(--t-base);
|
||||
}
|
||||
.close-remember-toggle.on { background: var(--accent); border-color: var(--accent); }
|
||||
|
||||
.close-remember-thumb {
|
||||
position: absolute;
|
||||
top: 1px;
|
||||
left: 1px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-faint);
|
||||
transition: transform var(--t-base), background var(--t-base);
|
||||
}
|
||||
.close-remember-toggle.on .close-remember-thumb {
|
||||
transform: translateX(12px);
|
||||
background: var(--bg-void);
|
||||
}
|
||||
|
||||
.close-remember-label {
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--text-xs);
|
||||
color: var(--text-faint);
|
||||
letter-spacing: var(--tracking-wide);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,151 @@
|
||||
import { store } from "@store/state.svelte";
|
||||
import { fetchAuthenticated, AuthRequiredError, refreshUiAccessToken } from "../core/auth";
|
||||
import { boot } from "@store/boot.svelte";
|
||||
import { getBlobUrl } from "@core/cache/imageCache";
|
||||
|
||||
const DEFAULT_URL = "http://127.0.0.1:4567";
|
||||
|
||||
type ReauthResolver = () => void;
|
||||
let _reauthQueue: ReauthResolver[] = [];
|
||||
|
||||
export function notifyReauthSuccess() {
|
||||
const queue = _reauthQueue;
|
||||
_reauthQueue = [];
|
||||
queue.forEach(resolve => resolve());
|
||||
}
|
||||
|
||||
function waitForReauth(): Promise<void> {
|
||||
return new Promise(resolve => { _reauthQueue.push(resolve); });
|
||||
}
|
||||
|
||||
export function getServerUrl(): string {
|
||||
const url = store.settings.serverUrl;
|
||||
return typeof url === "string" && url.trim() ? url.replace(/\/$/, "") : DEFAULT_URL;
|
||||
}
|
||||
|
||||
export function plainThumbUrl(path: string): string {
|
||||
if (!path) return "";
|
||||
if (path.startsWith("http")) return path;
|
||||
return `${getServerUrl()}${path}`;
|
||||
}
|
||||
|
||||
export async function resolveImageUrl(path: string): Promise<string> {
|
||||
if (!path) return "";
|
||||
const url = path.startsWith("http") ? path : `${getServerUrl()}${path}`;
|
||||
const mode = store.settings.serverAuthMode ?? "NONE";
|
||||
if (mode === "NONE") return url;
|
||||
return getBlobUrl(url);
|
||||
}
|
||||
|
||||
export const thumbUrl = plainThumbUrl;
|
||||
|
||||
interface GQLResponse<T> {
|
||||
data: T;
|
||||
errors?: { message: string }[];
|
||||
}
|
||||
|
||||
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) { reject(new DOMException("Aborted", "AbortError")); return; }
|
||||
const timer = setTimeout(resolve, ms);
|
||||
signal?.addEventListener("abort", () => {
|
||||
clearTimeout(timer);
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
}, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchWithRetry(
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
signal?: AbortSignal,
|
||||
retries = 3,
|
||||
delayMs = 300,
|
||||
): Promise<Response> {
|
||||
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
for (let i = 0; i < retries; i++) {
|
||||
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
try {
|
||||
const res = await fetchAuthenticated(url, init, signal, boot.skipped);
|
||||
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
return res;
|
||||
} catch (e: any) {
|
||||
if (e?.authRequired) throw e;
|
||||
if (e?.name === "AbortError" || signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
if (e instanceof AuthRequiredError) throw e;
|
||||
if (i === retries - 1) throw e;
|
||||
await abortableSleep(delayMs * Math.pow(1.5, i), signal);
|
||||
}
|
||||
}
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
|
||||
export async function fetchImage(
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ src: string; revoke: () => void }> {
|
||||
if (!path) return { src: "", revoke: () => {} };
|
||||
|
||||
const url = path.startsWith("http") ? path : `${getServerUrl()}${path}`;
|
||||
const mode = store.settings.serverAuthMode ?? "NONE";
|
||||
|
||||
if (mode === "NONE") return { src: url, revoke: () => {} };
|
||||
|
||||
const res = await fetchWithRetry(url, { method: "GET" }, signal);
|
||||
if (!res.ok) throw new Error(`Image fetch failed: ${res.status}`);
|
||||
|
||||
const blob = await res.blob();
|
||||
const src = URL.createObjectURL(blob);
|
||||
return { src, revoke: () => URL.revokeObjectURL(src) };
|
||||
}
|
||||
|
||||
export async function gql<T>(
|
||||
query: string,
|
||||
variables?: Record<string, unknown>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<T> {
|
||||
const tryRefreshAndRetry = async (): Promise<T | null> => {
|
||||
const mode = store.settings.serverAuthMode ?? "NONE";
|
||||
if (mode !== "UI_LOGIN" || boot.skipped) return null;
|
||||
const refreshed = await refreshUiAccessToken(true);
|
||||
if (!refreshed) return null;
|
||||
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
return attempt();
|
||||
};
|
||||
|
||||
const attempt = async (): Promise<T> => {
|
||||
const res = await fetchWithRetry(
|
||||
`${getServerUrl()}/api/graphql`,
|
||||
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query, variables }) },
|
||||
signal,
|
||||
);
|
||||
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
const retried = await tryRefreshAndRetry();
|
||||
if (retried) return retried;
|
||||
}
|
||||
throw new Error(`Suwayomi HTTP ${res.status}`);
|
||||
}
|
||||
const json: GQLResponse<T> = await res.json();
|
||||
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
if (json.errors?.length) {
|
||||
const isAuthError = json.errors.some(e => /unauthorized|unauthenticated/i.test(e.message));
|
||||
if (isAuthError && !boot.skipped) {
|
||||
const retried = await tryRefreshAndRetry();
|
||||
if (retried) return retried;
|
||||
|
||||
boot.sessionExpired = true;
|
||||
boot.loginRequired = true;
|
||||
boot.loginUser = store.settings.serverAuthUser ?? "";
|
||||
await waitForReauth();
|
||||
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
return attempt();
|
||||
}
|
||||
throw new Error(json.errors[0].message);
|
||||
}
|
||||
return json.data;
|
||||
};
|
||||
|
||||
return attempt();
|
||||
}
|
||||
@@ -3,7 +3,7 @@ export const FETCH_CHAPTERS = `
|
||||
fetchChapters(input: { mangaId: $mangaId }) {
|
||||
chapters {
|
||||
id name chapterNumber sourceOrder isRead isDownloaded isBookmarked
|
||||
pageCount mangaId uploadDate realUrl lastPageRead scanlator
|
||||
pageCount mangaId uploadDate realUrl lastPageRead lastReadAt scanlator
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,3 +46,19 @@ export const DELETE_DOWNLOADED_CHAPTERS = `
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_CHAPTER_META = `
|
||||
mutation SetChapterMeta($chapterId: Int!, $key: String!, $value: String!) {
|
||||
setChapterMeta(input: { meta: { chapterId: $chapterId, key: $key, value: $value } }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const DELETE_CHAPTER_META = `
|
||||
mutation DeleteChapterMeta($chapterId: Int!, $key: String!) {
|
||||
deleteChapterMeta(input: { chapterId: $chapterId, key: $key }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,215 @@
|
||||
export const FETCH_EXTENSIONS = `
|
||||
mutation FetchExtensions {
|
||||
fetchExtensions(input: {}) {
|
||||
extensions {
|
||||
apkName pkgName name lang versionName
|
||||
isInstalled isObsolete hasUpdate iconUrl
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_EXTENSION = `
|
||||
mutation UpdateExtension($id: String!, $install: Boolean, $uninstall: Boolean, $update: Boolean) {
|
||||
updateExtension(input: { id: $id, patch: { install: $install, uninstall: $uninstall, update: $update } }) {
|
||||
extension { apkName pkgName name isInstalled hasUpdate }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_EXTENSIONS = `
|
||||
mutation UpdateExtensions($ids: [String!]!, $install: Boolean, $uninstall: Boolean, $update: Boolean) {
|
||||
updateExtensions(input: { ids: $ids, patch: { install: $install, uninstall: $uninstall, update: $update } }) {
|
||||
extensions { apkName pkgName name isInstalled hasUpdate }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const INSTALL_EXTERNAL_EXTENSION = `
|
||||
mutation InstallExternalExtension($url: String!) {
|
||||
installExternalExtension(input: { extensionUrl: $url }) {
|
||||
extension { apkName pkgName name isInstalled }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_SOURCE_PREFERENCE = `
|
||||
mutation UpdateSourcePreference($source: LongString!, $change: SourcePreferenceChangeInput!) {
|
||||
updateSourcePreference(input: { source: $source, change: $change }) {
|
||||
source { id displayName }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_SOURCE_METAS = `
|
||||
mutation SetSourceMetas($input: SetSourceMetasInput!) {
|
||||
setSourceMetas(input: $input) {
|
||||
metas { sourceId key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const DELETE_SOURCE_METAS = `
|
||||
mutation DeleteSourceMetas($input: DeleteSourceMetasInput!) {
|
||||
deleteSourceMetas(input: $input) {
|
||||
metas { sourceId key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_SOURCE_METADATA = `
|
||||
mutation UpdateSourceMetadata(
|
||||
$preUpdateDeleteInput: DeleteSourceMetasInput!
|
||||
$hasPreUpdateDeletions: Boolean!
|
||||
$updateInput: SetSourceMetasInput!
|
||||
$hasUpdates: Boolean!
|
||||
$postUpdateDeleteInput: DeleteSourceMetasInput!
|
||||
$hasPostUpdateDeletions: Boolean!
|
||||
$migrateInput: SetSourceMetasInput!
|
||||
$isMigration: Boolean!
|
||||
) {
|
||||
preUpdateDeletedMeta: deleteSourceMetas(input: $preUpdateDeleteInput) @include(if: $hasPreUpdateDeletions) {
|
||||
metas { sourceId key value }
|
||||
}
|
||||
updatedMeta: setSourceMetas(input: $updateInput) @include(if: $hasUpdates) {
|
||||
metas { sourceId key value }
|
||||
}
|
||||
postUpdateDeletedMeta: deleteSourceMetas(input: $postUpdateDeleteInput) @include(if: $hasPostUpdateDeletions) {
|
||||
metas { sourceId key value }
|
||||
}
|
||||
migrationMeta: setSourceMetas(input: $migrateInput) @include(if: $isMigration) {
|
||||
metas { sourceId key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_SOURCE_META = `
|
||||
mutation SetSourceMeta($sourceId: LongString!, $key: String!, $value: String!) {
|
||||
setSourceMeta(input: { meta: { sourceId: $sourceId, key: $key, value: $value } }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const DELETE_SOURCE_META = `
|
||||
mutation DeleteSourceMeta($sourceId: LongString!, $key: String!) {
|
||||
deleteSourceMeta(input: { sourceId: $sourceId, key: $key }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_CATEGORY_META = `
|
||||
mutation SetCategoryMeta($categoryId: Int!, $key: String!, $value: String!) {
|
||||
setCategoryMeta(input: { meta: { categoryId: $categoryId, key: $key, value: $value } }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const DELETE_CATEGORY_META = `
|
||||
mutation DeleteCategoryMeta($categoryId: Int!, $key: String!) {
|
||||
deleteCategoryMeta(input: { categoryId: $categoryId, key: $key }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_GLOBAL_META = `
|
||||
mutation SetGlobalMeta($key: String!, $value: String!) {
|
||||
setGlobalMeta(input: { meta: { key: $key, value: $value } }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const DELETE_GLOBAL_META = `
|
||||
mutation DeleteGlobalMeta($key: String!) {
|
||||
deleteGlobalMeta(input: { key: $key }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const CLEAR_CACHED_IMAGES = `
|
||||
mutation ClearCachedImages($cachedPages: Boolean, $cachedThumbnails: Boolean, $downloadedThumbnails: Boolean) {
|
||||
clearCachedImages(input: {
|
||||
cachedPages: $cachedPages
|
||||
cachedThumbnails: $cachedThumbnails
|
||||
downloadedThumbnails: $downloadedThumbnails
|
||||
}) {
|
||||
cachedPages cachedThumbnails downloadedThumbnails
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const RESET_SETTINGS = `
|
||||
mutation ResetSettings {
|
||||
resetSettings(input: {}) {
|
||||
settings { extensionRepos }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_EXTENSION_REPOS = `
|
||||
mutation SetExtensionRepos($repos: [String!]!) {
|
||||
setSettings(input: { settings: { extensionRepos: $repos } }) {
|
||||
settings { extensionRepos }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_SERVER_AUTH = `
|
||||
mutation SetServerAuth($authMode: AuthMode!, $authUsername: String!, $authPassword: String!) {
|
||||
setSettings(input: { settings: { authMode: $authMode, authUsername: $authUsername, authPassword: $authPassword } }) {
|
||||
settings { authMode authUsername }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_SOCKS_PROXY = `
|
||||
mutation SetSocksProxy(
|
||||
$socksProxyEnabled: Boolean!
|
||||
$socksProxyHost: String!
|
||||
$socksProxyPort: String!
|
||||
$socksProxyVersion: Int!
|
||||
$socksProxyUsername: String!
|
||||
$socksProxyPassword: String!
|
||||
) {
|
||||
setSettings(input: { settings: {
|
||||
socksProxyEnabled: $socksProxyEnabled
|
||||
socksProxyHost: $socksProxyHost
|
||||
socksProxyPort: $socksProxyPort
|
||||
socksProxyVersion: $socksProxyVersion
|
||||
socksProxyUsername: $socksProxyUsername
|
||||
socksProxyPassword: $socksProxyPassword
|
||||
}}) {
|
||||
settings { socksProxyEnabled socksProxyHost socksProxyPort socksProxyVersion socksProxyUsername }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_FLARESOLVERR = `
|
||||
mutation SetFlareSolverr(
|
||||
$flareSolverrEnabled: Boolean!
|
||||
$flareSolverrUrl: String!
|
||||
$flareSolverrTimeout: Int!
|
||||
$flareSolverrSessionName: String!
|
||||
$flareSolverrSessionTtl: Int!
|
||||
$flareSolverrAsResponseFallback: Boolean!
|
||||
) {
|
||||
setSettings(input: { settings: {
|
||||
flareSolverrEnabled: $flareSolverrEnabled
|
||||
flareSolverrUrl: $flareSolverrUrl
|
||||
flareSolverrTimeout: $flareSolverrTimeout
|
||||
flareSolverrSessionName: $flareSolverrSessionName
|
||||
flareSolverrSessionTtl: $flareSolverrSessionTtl
|
||||
flareSolverrAsResponseFallback: $flareSolverrAsResponseFallback
|
||||
}}) {
|
||||
settings {
|
||||
flareSolverrEnabled flareSolverrUrl flareSolverrTimeout
|
||||
flareSolverrSessionName flareSolverrSessionTtl flareSolverrAsResponseFallback
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -33,6 +33,14 @@ export const UPDATE_MANGA_CATEGORIES = `
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_MANGAS_CATEGORIES = `
|
||||
mutation UpdateMangasCategories($ids: [Int!]!, $addTo: [Int!]!, $removeFrom: [Int!]!) {
|
||||
updateMangasCategories(input: { ids: $ids, patch: { addToCategories: $addTo, removeFromCategories: $removeFrom } }) {
|
||||
mangas { id }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const CREATE_CATEGORY = `
|
||||
mutation CreateCategory($name: String!) {
|
||||
createCategory(input: { name: $name }) {
|
||||
@@ -49,6 +57,14 @@ export const UPDATE_CATEGORY = `
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_CATEGORIES = `
|
||||
mutation UpdateCategories($ids: [Int!]!, $patch: UpdateCategoryPatchInput!) {
|
||||
updateCategories(input: { ids: $ids, patch: $patch }) {
|
||||
categories { id name order default includeInUpdate includeInDownload }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const DELETE_CATEGORY = `
|
||||
mutation DeleteCategory($id: Int!) {
|
||||
deleteCategory(input: { categoryId: $id }) {
|
||||
@@ -65,6 +81,16 @@ export const UPDATE_CATEGORY_ORDER = `
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_CATEGORY_MANGA = `
|
||||
mutation UpdateCategoryManga($categoryId: Int!) {
|
||||
updateCategoryManga(input: { categoryId: $categoryId }) {
|
||||
updateStatus {
|
||||
jobsInfo { isRunning finishedJobs totalJobs }
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_LIBRARY = `
|
||||
mutation UpdateLibrary {
|
||||
updateLibrary(input: {}) {
|
||||
@@ -75,6 +101,26 @@ export const UPDATE_LIBRARY = `
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_LIBRARY_MANGA = `
|
||||
mutation UpdateLibraryManga($mangaId: Int!) {
|
||||
updateLibraryManga(input: { mangaId: $mangaId }) {
|
||||
updateStatus {
|
||||
jobsInfo { isRunning finishedJobs totalJobs }
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const UPDATE_STOP = `
|
||||
mutation UpdateStop {
|
||||
updateStop(input: {}) {
|
||||
updateStatus {
|
||||
jobsInfo { isRunning finishedJobs totalJobs }
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const CREATE_BACKUP = `
|
||||
mutation CreateBackup {
|
||||
createBackup(input: {}) { url }
|
||||
@@ -89,3 +135,19 @@ export const RESTORE_BACKUP = `
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const SET_MANGA_META = `
|
||||
mutation SetMangaMeta($mangaId: Int!, $key: String!, $value: String!) {
|
||||
setMangaMeta(input: { meta: { mangaId: $mangaId, key: $key, value: $value } }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const DELETE_MANGA_META = `
|
||||
mutation DeleteMangaMeta($mangaId: Int!, $key: String!) {
|
||||
deleteMangaMeta(input: { mangaId: $mangaId, key: $key }) {
|
||||
meta { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,130 @@
|
||||
# Mutations
|
||||
|
||||
## Manga (`mutations/manga.ts`)
|
||||
|
||||
| Mutation | Variables | Description |
|
||||
|----------|-----------|-------------|
|
||||
| `FETCH_MANGA` | `id: Int!` | Fetch and refresh manga metadata from its source |
|
||||
| `UPDATE_MANGA` | `id: Int!`, `inLibrary: Boolean` | Update a single manga's library membership |
|
||||
| `UPDATE_MANGAS` | `ids: [Int!]!`, `inLibrary: Boolean` | Bulk-update library membership for multiple manga |
|
||||
| `UPDATE_MANGA_CATEGORIES` | `mangaId: Int!`, `addTo: [Int!]!`, `removeFrom: [Int!]!` | Add or remove a single manga from categories |
|
||||
| `UPDATE_MANGAS_CATEGORIES` | `ids: [Int!]!`, `addTo: [Int!]!`, `removeFrom: [Int!]!` | Bulk add/remove multiple manga from categories |
|
||||
| `CREATE_CATEGORY` | `name: String!` | Create a new category |
|
||||
| `UPDATE_CATEGORY` | `id: Int!`, `name: String` | Update a category's name |
|
||||
| `UPDATE_CATEGORIES` | `ids: [Int!]!`, `patch: UpdateCategoryPatchInput!` | Bulk-update multiple categories |
|
||||
| `DELETE_CATEGORY` | `id: Int!` | Delete a category |
|
||||
| `UPDATE_CATEGORY_ORDER` | `id: Int!`, `position: Int!` | Move a category to a new position |
|
||||
| `UPDATE_CATEGORY_MANGA` | `categoryId: Int!` | Trigger a metadata update for all manga in a category |
|
||||
| `UPDATE_LIBRARY` | — | Trigger a full library metadata refresh |
|
||||
| `UPDATE_LIBRARY_MANGA` | `mangaId: Int!` | Trigger a metadata update for a single manga |
|
||||
| `UPDATE_STOP` | — | Stop the currently running library update job |
|
||||
| `CREATE_BACKUP` | — | Create a backup and return its download URL |
|
||||
| `RESTORE_BACKUP` | `backup: Upload!` | Restore a backup file and return the restore job status |
|
||||
| `SET_MANGA_META` | `mangaId: Int!`, `key: String!`, `value: String!` | Set a key/value meta entry on a manga |
|
||||
| `DELETE_MANGA_META` | `mangaId: Int!`, `key: String!` | Delete a key/value meta entry from a manga |
|
||||
|
||||
---
|
||||
|
||||
## Chapters (`mutations/chapters.ts`)
|
||||
|
||||
| Mutation | Variables | Description |
|
||||
|----------|-----------|-------------|
|
||||
| `FETCH_CHAPTERS` | `mangaId: Int!` | Fetch/refresh the chapter list for a manga from its source |
|
||||
| `FETCH_CHAPTER_PAGES` | `chapterId: Int!` | Fetch the page URLs for a specific chapter |
|
||||
| `MARK_CHAPTER_READ` | `id: Int!`, `isRead: Boolean!` | Mark a single chapter read or unread |
|
||||
| `MARK_CHAPTERS_READ` | `ids: [Int!]!`, `isRead: Boolean!` | Bulk mark chapters read or unread |
|
||||
| `UPDATE_CHAPTERS_PROGRESS` | `ids: [Int!]!`, `isRead: Boolean`, `isBookmarked: Boolean`, `lastPageRead: Int` | Bulk update read state, bookmark state, and last page read |
|
||||
| `DELETE_DOWNLOADED_CHAPTERS` | `ids: [Int!]!` | Delete downloaded chapter files |
|
||||
| `SET_CHAPTER_META` | `chapterId: Int!`, `key: String!`, `value: String!` | Set a key/value meta entry on a chapter |
|
||||
| `DELETE_CHAPTER_META` | `chapterId: Int!`, `key: String!` | Delete a key/value meta entry from a chapter |
|
||||
|
||||
---
|
||||
|
||||
## Downloads (`mutations/downloads.ts`)
|
||||
|
||||
| Mutation | Variables | Description |
|
||||
|----------|-----------|-------------|
|
||||
| `ENQUEUE_DOWNLOAD` | `chapterId: Int!` | Add a single chapter to the download queue |
|
||||
| `ENQUEUE_CHAPTERS_DOWNLOAD` | `chapterIds: [Int!]!` | Add multiple chapters to the download queue |
|
||||
| `DEQUEUE_DOWNLOAD` | `chapterId: Int!` | Remove a single chapter from the download queue |
|
||||
| `DEQUEUE_CHAPTERS_DOWNLOAD` | `chapterIds: [Int!]!` | Remove multiple chapters from the download queue |
|
||||
| `REORDER_DOWNLOAD` | `chapterId: Int!`, `to: Int!` | Move a queued chapter to a new position |
|
||||
| `START_DOWNLOADER` | — | Start the downloader |
|
||||
| `STOP_DOWNLOADER` | — | Stop the downloader |
|
||||
| `CLEAR_DOWNLOADER` | — | Clear all items from the download queue |
|
||||
| `FETCH_SOURCE_MANGA` | `source: LongString!`, `type: FetchSourceMangaType!`, `page: Int!`, `query: String`, `filters: [FilterChangeInput!]` | Fetch manga from a source (browse/search) with pagination |
|
||||
| `SET_DOWNLOADS_PATH` | `path: String!` | Set the downloads directory path |
|
||||
| `SET_LOCAL_SOURCE_PATH` | `path: String!` | Set the local source directory path |
|
||||
|
||||
---
|
||||
|
||||
## Extensions (`mutations/extensions.ts`)
|
||||
|
||||
| Mutation | Variables | Description |
|
||||
|----------|-----------|-------------|
|
||||
| `FETCH_EXTENSIONS` | — | Fetch the latest extension list from configured repos |
|
||||
| `UPDATE_EXTENSION` | `id: String!`, `install: Boolean`, `uninstall: Boolean`, `update: Boolean` | Install, uninstall, or update a single extension |
|
||||
| `UPDATE_EXTENSIONS` | `ids: [String!]!`, `install: Boolean`, `uninstall: Boolean`, `update: Boolean` | Bulk install, uninstall, or update multiple extensions |
|
||||
| `INSTALL_EXTERNAL_EXTENSION` | `url: String!` | Install an extension from an external APK URL |
|
||||
| `UPDATE_SOURCE_PREFERENCE` | `source: LongString!`, `change: SourcePreferenceChangeInput!` | Update a source-specific preference value |
|
||||
| `SET_SOURCE_META` | `sourceId: LongString!`, `key: String!`, `value: String!` | Set a key/value meta entry on a source |
|
||||
| `DELETE_SOURCE_META` | `sourceId: LongString!`, `key: String!` | Delete a key/value meta entry from a source |
|
||||
| `SET_CATEGORY_META` | `categoryId: Int!`, `key: String!`, `value: String!` | Set a key/value meta entry on a category |
|
||||
| `DELETE_CATEGORY_META` | `categoryId: Int!`, `key: String!` | Delete a key/value meta entry from a category |
|
||||
| `SET_GLOBAL_META` | `key: String!`, `value: String!` | Set a global key/value meta entry |
|
||||
| `DELETE_GLOBAL_META` | `key: String!` | Delete a global key/value meta entry |
|
||||
| `CLEAR_CACHED_IMAGES` | `cachedPages: Boolean`, `cachedThumbnails: Boolean`, `downloadedThumbnails: Boolean` | Selectively clear cached page images, cached thumbnails, or downloaded thumbnails |
|
||||
| `RESET_SETTINGS` | — | Reset all server settings to defaults |
|
||||
| `UPDATE_WEBUI` | — | Trigger a WebUI update and return live status |
|
||||
| `RESET_WEBUI_UPDATE_STATUS` | — | Reset the WebUI update status back to idle |
|
||||
| `SET_EXTENSION_REPOS` | `repos: [String!]!` | Set the list of extension repository URLs |
|
||||
| `SET_SERVER_AUTH` | `authMode: AuthMode!`, `authUsername: String!`, `authPassword: String!` | Configure server auth mode and credentials |
|
||||
| `SET_SOCKS_PROXY` | `socksProxyEnabled: Boolean!`, `socksProxyHost: String!`, `socksProxyPort: String!`, `socksProxyVersion: Int!`, `socksProxyUsername: String!`, `socksProxyPassword: String!` | Configure SOCKS proxy settings |
|
||||
| `SET_FLARESOLVERR` | `flareSolverrEnabled: Boolean!`, `flareSolverrUrl: String!`, `flareSolverrTimeout: Int!`, `flareSolverrSessionName: String!`, `flareSolverrSessionTtl: Int!`, `flareSolverrAsResponseFallback: Boolean!` | Configure FlareSolverr integration |
|
||||
|
||||
---
|
||||
|
||||
## Tracking (`mutations/tracking.ts`)
|
||||
|
||||
| Mutation | Variables | Description |
|
||||
|----------|-----------|-------------|
|
||||
| `BIND_TRACK` | `mangaId: Int!`, `trackerId: Int!`, `remoteId: LongString!` | Bind a manga to a remote tracker entry |
|
||||
| `UPDATE_TRACK` | `recordId: Int!`, `status: Int`, `lastChapterRead: Float`, `scoreString: String`, `startDate: LongString`, `finishDate: LongString`, `private: Boolean` | Update tracking progress, status, score, and dates |
|
||||
| `UNBIND_TRACK` | `recordId: Int!` | Unbind a manga from a tracker record |
|
||||
| `FETCH_TRACK` | `recordId: Int!` | Refresh a track record from the remote tracker |
|
||||
| `TRACK_PROGRESS` | `mangaId: Int!` | Sync current reading progress to all bound trackers for a manga |
|
||||
| `LOGIN_TRACKER_OAUTH` | `trackerId: Int!`, `callbackUrl: String!` | Initiate OAuth login for a tracker |
|
||||
| `LOGIN_TRACKER_CREDENTIALS` | `trackerId: Int!`, `username: String!`, `password: String!` | Log into a tracker with username and password |
|
||||
| `LOGOUT_TRACKER` | `trackerId: Int!` | Log out of a tracker |
|
||||
| `CONNECT_KOSYNC` | `username: String!`, `password: String!`, `serverAddress: String!` | Connect a KOReader sync account |
|
||||
| `LOGOUT_KOSYNC` | — | Disconnect the KOReader sync account |
|
||||
| `PULL_KOSYNC_PROGRESS` | `chapterId: Int!` | Pull reading progress from KOReader sync for a chapter |
|
||||
| `PUSH_KOSYNC_PROGRESS` | `chapterId: Int!` | Push reading progress to KOReader sync for a chapter |
|
||||
| `LOGIN_USER` | `username: String!`, `password: String!` | Authenticate and return access + refresh tokens |
|
||||
| `REFRESH_TOKEN` | — | Refresh the current access token |
|
||||
|
||||
---
|
||||
|
||||
## New in Preview
|
||||
|
||||
Mutations now available and not yet wired to any feature in Moku:
|
||||
|
||||
| Mutation | Potential Feature |
|
||||
|----------|-------------------|
|
||||
| `UPDATE_MANGAS_CATEGORIES` | Bulk category editor — move/assign multiple manga at once |
|
||||
| `UPDATE_CATEGORIES` | Bulk category settings — toggle update/download flags for multiple categories at once |
|
||||
| `UPDATE_CATEGORY_MANGA` | Per-category refresh button — update only one category's manga |
|
||||
| `UPDATE_LIBRARY_MANGA` | Single manga refresh — trigger from series detail without a full library update |
|
||||
| `UPDATE_STOP` | Cancel button for library update jobs |
|
||||
| `UPDATE_EXTENSIONS` | Bulk extension updater — "update all" button in extensions page |
|
||||
| `UPDATE_SOURCE_PREFERENCE` | Source settings page — persist source-specific preferences |
|
||||
| `SET_SOURCE_META` / `DELETE_SOURCE_META` | Per-source client state — store browse position, last filter, etc. |
|
||||
| `SET_CATEGORY_META` / `DELETE_CATEGORY_META` | Per-category client state — store sort/filter preferences per category |
|
||||
| `SET_CHAPTER_META` / `DELETE_CHAPTER_META` | Per-chapter client state — annotations, custom notes |
|
||||
| `SET_GLOBAL_META` / `DELETE_GLOBAL_META` | Server-synced app state — replace local persistence for settings that should roam |
|
||||
| `CLEAR_CACHED_IMAGES` | Storage settings — granular cache clearing (pages, thumbnails, downloaded) |
|
||||
| `RESET_SETTINGS` | Settings page — factory reset button |
|
||||
| `UPDATE_WEBUI` / `RESET_WEBUI_UPDATE_STATUS` | WebUI update flow in settings — trigger and monitor update progress |
|
||||
| `TRACK_PROGRESS` | One-tap sync — push current reading position to all trackers without opening tracking panel |
|
||||
| `CONNECT_KOSYNC` / `LOGOUT_KOSYNC` | KOReader sync settings section — connect/disconnect account |
|
||||
| `PULL_KOSYNC_PROGRESS` / `PUSH_KOSYNC_PROGRESS` | KOReader sync — manual pull/push per chapter, or auto-sync on chapter open/close |
|
||||
@@ -1,6 +1,6 @@
|
||||
const TRACK_RECORD_FRAGMENT = `
|
||||
id trackerId remoteId title status score displayScore
|
||||
lastChapterRead totalChapters remoteUrl startDate finishDate private
|
||||
lastChapterRead totalChapters remoteUrl startDate finishDate private libraryId
|
||||
`;
|
||||
|
||||
export const BIND_TRACK = `
|
||||
@@ -15,7 +15,7 @@ export const UPDATE_TRACK = `
|
||||
mutation UpdateTrack($recordId: Int!, $status: Int, $lastChapterRead: Float, $scoreString: String, $startDate: LongString, $finishDate: LongString, $private: Boolean) {
|
||||
updateTrack(input: { recordId: $recordId, status: $status, lastChapterRead: $lastChapterRead, scoreString: $scoreString, startDate: $startDate, finishDate: $finishDate, private: $private }) {
|
||||
trackRecord {
|
||||
id trackerId status score displayScore lastChapterRead totalChapters startDate finishDate private
|
||||
id trackerId status score displayScore lastChapterRead totalChapters startDate finishDate private libraryId
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,17 @@ export const FETCH_TRACK = `
|
||||
mutation FetchTrack($recordId: Int!) {
|
||||
fetchTrack(input: { recordId: $recordId }) {
|
||||
trackRecord {
|
||||
id trackerId status score displayScore lastChapterRead totalChapters startDate finishDate
|
||||
id trackerId status score displayScore lastChapterRead totalChapters startDate finishDate libraryId
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const TRACK_PROGRESS = `
|
||||
mutation TrackProgress($mangaId: Int!) {
|
||||
trackProgress(input: { mangaId: $mangaId }) {
|
||||
trackRecords {
|
||||
id trackerId lastChapterRead status
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,7 +53,7 @@ export const LOGIN_TRACKER_OAUTH = `
|
||||
mutation LoginTrackerOAuth($trackerId: Int!, $callbackUrl: String!) {
|
||||
loginTrackerOAuth(input: { trackerId: $trackerId, callbackUrl: $callbackUrl }) {
|
||||
isLoggedIn
|
||||
tracker { id name isLoggedIn authUrl }
|
||||
tracker { id name isLoggedIn isTokenExpired authUrl }
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -52,7 +62,7 @@ export const LOGIN_TRACKER_CREDENTIALS = `
|
||||
mutation LoginTrackerCredentials($trackerId: Int!, $username: String!, $password: String!) {
|
||||
loginTrackerCredentials(input: { trackerId: $trackerId, username: $username, password: $password }) {
|
||||
isLoggedIn
|
||||
tracker { id name isLoggedIn authUrl }
|
||||
tracker { id name isLoggedIn isTokenExpired authUrl }
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -60,21 +70,58 @@ export const LOGIN_TRACKER_CREDENTIALS = `
|
||||
export const LOGOUT_TRACKER = `
|
||||
mutation LogoutTracker($trackerId: Int!) {
|
||||
logoutTracker(input: { trackerId: $trackerId }) {
|
||||
tracker { id name isLoggedIn authUrl }
|
||||
tracker { id name isLoggedIn isTokenExpired authUrl }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const CONNECT_KOSYNC = `
|
||||
mutation ConnectKoSync($username: String!, $password: String!, $serverAddress: String!) {
|
||||
connectKoSyncAccount(input: { username: $username, password: $password, serverAddress: $serverAddress }) {
|
||||
isConnected
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const LOGOUT_KOSYNC = `
|
||||
mutation LogoutKoSync {
|
||||
logoutKoSyncAccount(input: {}) {
|
||||
isConnected
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const PULL_KOSYNC_PROGRESS = `
|
||||
mutation PullKoSyncProgress($chapterId: Int!) {
|
||||
pullKoSyncProgress(input: { chapterId: $chapterId }) {
|
||||
chapter { id lastPageRead isRead }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const PUSH_KOSYNC_PROGRESS = `
|
||||
mutation PushKoSyncProgress($chapterId: Int!) {
|
||||
pushKoSyncProgress(input: { chapterId: $chapterId }) {
|
||||
chapter { id lastPageRead isRead }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const LOGIN_USER = `
|
||||
mutation Login($username: String!, $password: String!) {
|
||||
login(input: { username: $username, password: $password }) {
|
||||
accessToken refreshToken
|
||||
mutation Login($username: String!, $password: String!, $clientMutationId: String) {
|
||||
login(input: { username: $username, password: $password, clientMutationId: $clientMutationId }) {
|
||||
accessToken
|
||||
refreshToken
|
||||
clientMutationId
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const REFRESH_TOKEN = `
|
||||
mutation RefreshToken {
|
||||
refreshToken { accessToken }
|
||||
mutation RefreshToken($refreshToken: String!, $clientMutationId: String) {
|
||||
refreshToken(input: { refreshToken: $refreshToken, clientMutationId: $clientMutationId }) {
|
||||
accessToken
|
||||
clientMutationId
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -2,6 +2,12 @@ export const GET_RECENTLY_UPDATED = `
|
||||
query GetRecentlyUpdated {
|
||||
chapters(orderBy: FETCHED_AT, orderByType: DESC, first: 300) {
|
||||
nodes {
|
||||
id
|
||||
name
|
||||
chapterNumber
|
||||
sourceOrder
|
||||
isRead
|
||||
lastPageRead
|
||||
mangaId
|
||||
fetchedAt
|
||||
manga { id title thumbnailUrl inLibrary }
|
||||
@@ -15,7 +21,7 @@ export const GET_CHAPTERS = `
|
||||
chapters(condition: { mangaId: $mangaId }) {
|
||||
nodes {
|
||||
id name chapterNumber sourceOrder isRead isDownloaded isBookmarked
|
||||
pageCount mangaId uploadDate realUrl lastPageRead scanlator
|
||||
pageCount mangaId uploadDate realUrl lastPageRead lastReadAt scanlator
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ export const GET_DOWNLOAD_STATUS = `
|
||||
downloadStatus {
|
||||
state
|
||||
queue {
|
||||
progress state
|
||||
progress state tries
|
||||
chapter {
|
||||
id name pageCount mangaId
|
||||
manga { id title thumbnailUrl }
|
||||
@@ -0,0 +1,117 @@
|
||||
export const GET_LOCAL_MANGA = `
|
||||
query GetLocalManga {
|
||||
mangas(condition: { sourceId: "0" }) {
|
||||
nodes { id title thumbnailUrl inLibrary }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const GET_EXTENSIONS = `
|
||||
query GetExtensions {
|
||||
extensions {
|
||||
nodes {
|
||||
apkName pkgName name lang versionName
|
||||
isInstalled isObsolete hasUpdate iconUrl
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const GET_SOURCES = `
|
||||
query GetSources {
|
||||
sources {
|
||||
nodes {
|
||||
id name lang displayName iconUrl isNsfw
|
||||
isConfigurable supportsLatest
|
||||
extension { pkgName }
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const GET_SOURCE_SETTINGS = `
|
||||
query GetSourceSettings($id: LongString!) {
|
||||
source(id: $id) {
|
||||
id
|
||||
displayName
|
||||
preferences {
|
||||
... on CheckBoxPreference {
|
||||
type: __typename
|
||||
CheckBoxTitle: title
|
||||
CheckBoxSummary: summary
|
||||
CheckBoxDefault: default
|
||||
CheckBoxCurrentValue: currentValue
|
||||
key
|
||||
}
|
||||
... on SwitchPreference {
|
||||
type: __typename
|
||||
SwitchPreferenceTitle: title
|
||||
SwitchPreferenceSummary: summary
|
||||
SwitchPreferenceDefault: default
|
||||
SwitchPreferenceCurrentValue: currentValue
|
||||
key
|
||||
}
|
||||
... on ListPreference {
|
||||
type: __typename
|
||||
ListPreferenceTitle: title
|
||||
ListPreferenceSummary: summary
|
||||
ListPreferenceDefault: default
|
||||
ListPreferenceCurrentValue: currentValue
|
||||
entries
|
||||
entryValues
|
||||
key
|
||||
}
|
||||
... on EditTextPreference {
|
||||
type: __typename
|
||||
EditTextPreferenceTitle: title
|
||||
EditTextPreferenceSummary: summary
|
||||
EditTextPreferenceDefault: default
|
||||
EditTextPreferenceCurrentValue: currentValue
|
||||
dialogTitle
|
||||
dialogMessage
|
||||
key
|
||||
}
|
||||
... on MultiSelectListPreference {
|
||||
type: __typename
|
||||
MultiSelectListPreferenceTitle: title
|
||||
MultiSelectListPreferenceSummary: summary
|
||||
MultiSelectListPreferenceDefault: default
|
||||
MultiSelectListPreferenceCurrentValue: currentValue
|
||||
entries
|
||||
entryValues
|
||||
key
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const GET_MIGRATABLE_SOURCES = `
|
||||
query GetMigratableSources {
|
||||
mangas(condition: { inLibrary: true }) {
|
||||
nodes {
|
||||
sourceId
|
||||
source {
|
||||
id name lang displayName iconUrl isNsfw isConfigurable supportsLatest
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const GET_SETTINGS = `
|
||||
query GetSettings {
|
||||
settings { extensionRepos }
|
||||
}
|
||||
`;
|
||||
|
||||
export const GET_SERVER_SECURITY = `
|
||||
query GetServerSecurity {
|
||||
settings {
|
||||
authMode authUsername
|
||||
socksProxyEnabled socksProxyHost socksProxyPort socksProxyVersion socksProxyUsername
|
||||
flareSolverrEnabled flareSolverrUrl flareSolverrTimeout
|
||||
flareSolverrSessionName flareSolverrSessionTtl flareSolverrAsResponseFallback
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -3,3 +3,5 @@ export * from "./chapters";
|
||||
export * from "./downloads";
|
||||
export * from "./extensions";
|
||||
export * from "./tracking";
|
||||
export * from "./updater";
|
||||
export * from "./meta";
|
||||
@@ -2,10 +2,15 @@ export const GET_LIBRARY = `
|
||||
query GetLibrary {
|
||||
mangas(condition: { inLibrary: true }) {
|
||||
nodes {
|
||||
id title thumbnailUrl inLibrary downloadCount unreadCount
|
||||
id title thumbnailUrl inLibrary downloadCount unreadCount bookmarkCount
|
||||
description status author artist genre
|
||||
inLibraryAt lastFetchedAt chaptersLastFetchedAt thumbnailUrlLastFetched
|
||||
source { id name displayName }
|
||||
chapters { totalCount }
|
||||
latestFetchedChapter { id uploadDate }
|
||||
latestUploadedChapter { id uploadDate }
|
||||
lastReadChapter { id chapterNumber }
|
||||
firstUnreadChapter { id chapterNumber }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +28,11 @@ export const GET_MANGA = `
|
||||
query GetManga($id: Int!) {
|
||||
manga(id: $id) {
|
||||
id title description thumbnailUrl status author artist genre inLibrary realUrl
|
||||
inLibraryAt lastFetchedAt thumbnailUrlLastFetched updateStrategy
|
||||
source { id name displayName }
|
||||
lastReadChapter { id chapterNumber lastPageRead }
|
||||
firstUnreadChapter { id chapterNumber }
|
||||
highestNumberedChapter { id chapterNumber }
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -58,12 +67,17 @@ export const GET_DOWNLOADS_PATH = `
|
||||
export const LIBRARY_UPDATE_STATUS = `
|
||||
query LibraryUpdateStatus {
|
||||
libraryUpdateStatus {
|
||||
jobsInfo { isRunning finishedJobs totalJobs skippedMangasCount }
|
||||
jobsInfo {
|
||||
isRunning finishedJobs totalJobs skippedMangasCount skippedCategoriesCount
|
||||
}
|
||||
mangaUpdates {
|
||||
status
|
||||
manga { id title thumbnailUrl unreadCount }
|
||||
}
|
||||
}
|
||||
lastUpdateTimestamp {
|
||||
timestamp
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
export const GET_META = `
|
||||
query GetMeta($key: String!) {
|
||||
meta(key: $key) {
|
||||
key value
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const GET_METAS = `
|
||||
query GetMetas {
|
||||
metas {
|
||||
nodes { key value }
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,117 @@
|
||||
# Queries
|
||||
|
||||
## Manga (`queries/manga.ts`)
|
||||
|
||||
| Query | Variables | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `GET_LIBRARY` | — | All in-library manga with metadata, source, chapter counts, download count, unread count, bookmark count, and read progress anchors (`lastReadChapter`, `firstUnreadChapter`) |
|
||||
| `GET_ALL_MANGA` | — | Minimal manga list — id, title, thumbnail, library flag, download count |
|
||||
| `GET_MANGA` | `id: Int!` | Full detail for a single manga — includes `updateStrategy`, `lastReadChapter`, `firstUnreadChapter`, `highestNumberedChapter` |
|
||||
| `GET_CATEGORIES` | — | All categories with order/settings and their assigned manga (minimal fields) |
|
||||
| `GET_DOWNLOADED_CHAPTERS_PAGES` | — | Page counts for all downloaded chapters — used for storage stats |
|
||||
| `GET_DOWNLOADS_PATH` | — | `downloadsPath` and `localSourcePath` from settings |
|
||||
| `LIBRARY_UPDATE_STATUS` | — | Current library update job (`jobsInfo`, `mangaUpdates`) plus `lastUpdateTimestamp` for server-side update timing |
|
||||
| `GET_RESTORE_STATUS` | `id: String!` | Backup restore job status by job ID — `mangaProgress`, `state`, `totalManga` |
|
||||
| `VALIDATE_BACKUP` | `backup: Upload!` | Validate a backup file before restore — returns missing sources and trackers |
|
||||
| `MANGAS_BY_GENRE` | `filter: MangaFilterInput`, `first: Int`, `offset: Int` | Paginated manga filtered by genre, ordered by `IN_LIBRARY_AT DESC` |
|
||||
|
||||
---
|
||||
|
||||
## Chapters (`queries/chapters.ts`)
|
||||
|
||||
| Query | Variables | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `GET_RECENTLY_UPDATED` | — | Latest 300 chapters ordered by `FETCHED_AT DESC` with parent manga info |
|
||||
| `GET_CHAPTERS` | `mangaId: Int!` | All chapters for a manga — includes `lastReadAt`, `lastPageRead`, read/download/bookmark state, page count, scanlator |
|
||||
|
||||
---
|
||||
|
||||
## Downloads (`queries/downloads.ts`)
|
||||
|
||||
| Query | Variables | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `GET_DOWNLOAD_STATUS` | — | Downloader state (`DownloaderState` enum) and full queue with chapter and manga info |
|
||||
|
||||
---
|
||||
|
||||
## Extensions (`queries/extensions.ts`)
|
||||
|
||||
| Query | Variables | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `GET_LOCAL_MANGA` | — | Manga from the local source (`sourceId: "0"`) |
|
||||
| `GET_EXTENSIONS` | — | All extensions — install status, update flag, obsolete flag, metadata |
|
||||
| `GET_SOURCES` | — | All sources — id, name, lang, display name, icon, NSFW flag, `isConfigurable`, `supportsLatest`, `baseUrl` |
|
||||
| `GET_SETTINGS` | — | `extensionRepos` from settings |
|
||||
| `GET_SERVER_SECURITY` | — | Full security config — auth mode, SOCKS proxy settings, FlareSolverr settings |
|
||||
|
||||
---
|
||||
|
||||
## Tracking (`queries/tracking.ts`)
|
||||
|
||||
| Query | Variables | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `GET_TRACKERS` | — | All trackers with login state, token expiry, capability flags (`supportsPrivateTracking`, `supportsReadingDates`, `supportsTrackDeletion`), scores, and statuses |
|
||||
| `GET_MANGA_TRACK_RECORDS` | `mangaId: Int!` | All track records for a specific manga — includes `libraryId`, score, dates, privacy flag |
|
||||
| `SEARCH_TRACKER` | `trackerId: Int!`, `query: String!` | Search a tracker by query string — returns id, title, cover, summary, publishing info |
|
||||
| `GET_ALL_TRACKER_RECORDS` | — | All trackers and their full record lists with associated manga — includes `isTokenExpired`, `libraryId` |
|
||||
| `GET_TRACKER_RECORDS` | `trackerId: Int!` | Records for a specific tracker with associated manga |
|
||||
|
||||
---
|
||||
|
||||
## Updater (`queries/updater.ts`)
|
||||
|
||||
| Query | Variables | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `GET_ABOUT_SERVER` | — | Server name, version, build type, build time, GitHub and Discord links |
|
||||
| `GET_ABOUT_WEBUI` | — | WebUI channel, tag, and last update timestamp |
|
||||
| `CHECK_FOR_SERVER_UPDATES` | — | Available server updates — channel, tag, download URL |
|
||||
| `CHECK_FOR_WEBUI_UPDATE` | — | Available WebUI updates — channel and tag |
|
||||
| `GET_WEBUI_UPDATE_STATUS` | — | Live WebUI update state (`UpdateState` enum), progress percent, and info block |
|
||||
|
||||
---
|
||||
|
||||
## Meta (`queries/meta.ts`)
|
||||
|
||||
| Query | Variables | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `GET_META` | `key: String!` | Single server-side key/value meta entry |
|
||||
| `GET_METAS` | — | All global meta entries as a node list |
|
||||
|
||||
---
|
||||
|
||||
## KoSync (`queries/kosync.ts`)
|
||||
|
||||
| Query | Variables | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `GET_KOSYNC_STATUS` | — | KOReader sync connection status |
|
||||
|
||||
---
|
||||
|
||||
## New in Preview
|
||||
|
||||
Queries and fields now available but not yet wired to any feature in Moku:
|
||||
|
||||
| Query / Field | Potential Feature |
|
||||
|---------------|-------------------|
|
||||
| `GET_ABOUT_SERVER` | About page — server version, build info, links to GitHub and Discord |
|
||||
| `GET_ABOUT_WEBUI` | About page — WebUI version and release channel |
|
||||
| `CHECK_FOR_SERVER_UPDATES` | Update available banner or settings badge |
|
||||
| `CHECK_FOR_WEBUI_UPDATE` | Update available banner or settings badge |
|
||||
| `GET_WEBUI_UPDATE_STATUS` | Update progress indicator in settings |
|
||||
| `GET_META` / `GET_METAS` | Server-side persistence — sync app state across clients without local storage |
|
||||
| `GET_KOSYNC_STATUS` | KOReader sync settings section — show connection state |
|
||||
| `trackRecords` (top-level) | Flat tracker record browser — filter by score, privacy, tracker |
|
||||
| `category` (single by id) | Direct category detail without fetching all categories |
|
||||
| `chapter` (single by id) | Direct chapter lookup without fetching full manga chapter list |
|
||||
| `source` (single by id) | Source detail page — preferences, filters, browse |
|
||||
| `tracker` (single by id) | Individual tracker detail — statuses, records |
|
||||
| `trackRecord` (single by id) | Direct track record lookup for deep linking |
|
||||
| `lastUpdateTimestamp` | Stale data detection — poll before refetching library |
|
||||
| `MangaType.hasDuplicateChapters` | Library health view — flag manga with duplicate chapter numbers |
|
||||
| `MangaType.age` / `chaptersAge` | Stale manga indicator — highlight series with no updates in N days |
|
||||
| `MangaType.initialized` | Loading skeleton gating — skip detail render until manga is fully fetched |
|
||||
| `SourceType.isConfigurable` | Source list — show gear icon only when source is configurable |
|
||||
| `SourceType.supportsLatest` | Source browse UI — conditionally show Latest tab |
|
||||
| `TrackerType.supportsTrackDeletion` | Tracking panel — show remove button only when tracker supports it |
|
||||
| `TrackerType.supportsReadingDates` | Tracking panel — show date fields only when tracker supports them |
|
||||
| `TrackerType.isTokenExpired` | Re-auth prompt — detect expired tokens before a request fails |
|
||||
@@ -2,7 +2,9 @@ export const GET_TRACKERS = `
|
||||
query GetTrackers {
|
||||
trackers {
|
||||
nodes {
|
||||
id name icon isLoggedIn authUrl supportsPrivateTracking scores
|
||||
id name icon isLoggedIn isTokenExpired authUrl
|
||||
supportsPrivateTracking supportsReadingDates supportsTrackDeletion
|
||||
scores
|
||||
statuses { value name }
|
||||
}
|
||||
}
|
||||
@@ -15,7 +17,7 @@ export const GET_MANGA_TRACK_RECORDS = `
|
||||
trackRecords {
|
||||
nodes {
|
||||
id trackerId remoteId title status score displayScore
|
||||
lastChapterRead totalChapters remoteUrl startDate finishDate private
|
||||
lastChapterRead totalChapters remoteUrl startDate finishDate private libraryId
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,12 +39,12 @@ export const GET_ALL_TRACKER_RECORDS = `
|
||||
query GetAllTrackerRecords {
|
||||
trackers {
|
||||
nodes {
|
||||
id name icon isLoggedIn scores
|
||||
id name icon isLoggedIn isTokenExpired scores
|
||||
statuses { value name }
|
||||
trackRecords {
|
||||
nodes {
|
||||
id trackerId title status displayScore lastChapterRead
|
||||
totalChapters remoteUrl private
|
||||
totalChapters remoteUrl private libraryId
|
||||
manga { id title thumbnailUrl inLibrary }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export const GET_ABOUT_SERVER = `
|
||||
query GetAboutServer {
|
||||
aboutServer {
|
||||
name version buildType buildTime github discord
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const GET_ABOUT_WEBUI = `
|
||||
query GetAboutWebUI {
|
||||
aboutWebUI {
|
||||
channel tag updateTimestamp
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const CHECK_FOR_SERVER_UPDATES = `
|
||||
query CheckForServerUpdates {
|
||||
checkForServerUpdates {
|
||||
channel tag url
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -1,32 +1,30 @@
|
||||
import type { Attachment } from "svelte/attachments";
|
||||
|
||||
/**
|
||||
* {@attach selectPortal(triggerEl)}
|
||||
*
|
||||
* Moves the decorated element to <body> and positions it below `triggerEl`.
|
||||
* The element stays reactive — Svelte still owns its DOM, we just re-parent it.
|
||||
*
|
||||
* The portalled menu element is stored on `triggerEl.__selectMenuEl` so that
|
||||
* the outside-click guard in Settings.svelte can exclude it from dismissal.
|
||||
*/
|
||||
export function selectPortal(triggerEl: HTMLElement & { __selectMenuEl?: HTMLElement | null }): Attachment {
|
||||
return (menuEl: HTMLElement) => {
|
||||
// Position & move to body
|
||||
function position() {
|
||||
const zoom = parseFloat(document.documentElement.style.zoom) / 100 || 1;
|
||||
const r = triggerEl.getBoundingClientRect();
|
||||
|
||||
const top = r.bottom / zoom + 4;
|
||||
const right = r.right / zoom;
|
||||
const width = menuEl.offsetWidth;
|
||||
const left = Math.max(8, right - width);
|
||||
|
||||
menuEl.style.position = "fixed";
|
||||
menuEl.style.top = `${r.bottom + 4}px`;
|
||||
menuEl.style.left = `${r.right - menuEl.offsetWidth}px`;
|
||||
// clamp to viewport left edge
|
||||
const left = parseFloat(menuEl.style.left);
|
||||
if (left < 8) menuEl.style.left = "8px";
|
||||
menuEl.style.top = `${top}px`;
|
||||
menuEl.style.left = `${left}px`;
|
||||
}
|
||||
|
||||
menuEl.style.visibility = "hidden";
|
||||
document.body.appendChild(menuEl);
|
||||
triggerEl.__selectMenuEl = menuEl;
|
||||
position();
|
||||
|
||||
// Reposition on scroll / resize while open
|
||||
requestAnimationFrame(() => {
|
||||
position();
|
||||
menuEl.style.visibility = "";
|
||||
});
|
||||
|
||||
window.addEventListener("scroll", position, true);
|
||||
window.addEventListener("resize", position);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export { shouldHideNsfw, shouldHideSource, dedupeSourcesByLang } from "@core/util";
|
||||
|
||||
export function buildFilter<T>(...predicates: ((item: T) => boolean)[]): (item: T) => boolean {
|
||||
return (item) => predicates.every((p) => p(item));
|
||||
}
|
||||
@@ -0,0 +1,629 @@
|
||||
import { store, updateSettings } from "@store/state.svelte";
|
||||
|
||||
export type AuthMode = "NONE" | "BASIC_AUTH" | "UI_LOGIN";
|
||||
|
||||
export class AuthRequiredError extends Error {
|
||||
constructor(msg = "Authentication required") {
|
||||
super(msg);
|
||||
this.name = "AuthRequiredError";
|
||||
}
|
||||
}
|
||||
|
||||
const TOKEN_KEY = "moku_access_token";
|
||||
const UI_SESSION_KEY = "moku_ui_auth_session";
|
||||
const TOKEN_REFRESH_SKEW_MS = 30_000;
|
||||
const AUTH_DEBUG = Boolean((import.meta as ImportMeta & { env?: { DEV?: boolean } }).env?.DEV);
|
||||
|
||||
interface StoredAccessToken {
|
||||
base: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
interface StoredUiAuthSession {
|
||||
base: string;
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
clientMutationId?: string;
|
||||
accessExpiresAt?: number | null;
|
||||
refreshExpiresAt?: number | null;
|
||||
}
|
||||
|
||||
interface JwtSettings {
|
||||
jwtAudience?: string | null;
|
||||
jwtRefreshExpiry?: string | null;
|
||||
jwtTokenExpiry?: string | null;
|
||||
}
|
||||
|
||||
export interface UiAuthDebugStatus {
|
||||
mode: AuthMode;
|
||||
serverBase: string;
|
||||
hasSession: boolean;
|
||||
hasRefreshToken: boolean;
|
||||
accessExpiresAt: number | null;
|
||||
refreshExpiresAt: number | null;
|
||||
accessExpiresInMs: number | null;
|
||||
refreshExpiresInMs: number | null;
|
||||
shouldRefreshSoon: boolean;
|
||||
refreshInFlight: boolean;
|
||||
skewMs: number;
|
||||
}
|
||||
|
||||
let _accessToken: string | null = null;
|
||||
let _accessTokenBase: string | null = null;
|
||||
let _uiSession: StoredUiAuthSession | null = null;
|
||||
let _refreshPromise: Promise<string | null> | null = null;
|
||||
let _jwtSettingsBase: string | null = null;
|
||||
let _jwtSettings: JwtSettings | null = null;
|
||||
let _jwtSettingsFetchedAt = 0;
|
||||
|
||||
function authDebug(event: string, fields?: Record<string, unknown>) {
|
||||
if (!AUTH_DEBUG) return;
|
||||
if (fields) {
|
||||
console.debug(`[auth] ${event}`, fields);
|
||||
return;
|
||||
}
|
||||
console.debug(`[auth] ${event}`);
|
||||
}
|
||||
|
||||
function parseIsoDuration(duration: string): number | null {
|
||||
try {
|
||||
const match = duration.match(
|
||||
/^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:([\d.]+)S)?)?$/
|
||||
);
|
||||
if (!match) return null;
|
||||
const [, years, months, days, hours, minutes, seconds] = match;
|
||||
let ms = 0;
|
||||
if (years) ms += parseInt(years) * 365.25 * 24 * 60 * 60 * 1000;
|
||||
if (months) ms += parseInt(months) * 30.44 * 24 * 60 * 60 * 1000;
|
||||
if (days) ms += parseInt(days) * 24 * 60 * 60 * 1000;
|
||||
if (hours) ms += parseInt(hours) * 60 * 60 * 1000;
|
||||
if (minutes) ms += parseInt(minutes) * 60 * 1000;
|
||||
if (seconds) ms += parseFloat(seconds) * 1000;
|
||||
return ms;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeJwtExpiryMs(token: string): number | null {
|
||||
try {
|
||||
const payload = token.split(".")[1];
|
||||
if (!payload) return null;
|
||||
const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), "=");
|
||||
const decoded = atob(padded);
|
||||
const json = JSON.parse(decoded) as { exp?: number };
|
||||
return typeof json.exp === "number" ? json.exp * 1000 : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isExpired(expiresAt?: number | null, skewMs = TOKEN_REFRESH_SKEW_MS): boolean {
|
||||
if (!expiresAt || !Number.isFinite(expiresAt)) return false;
|
||||
return Date.now() >= expiresAt - skewMs;
|
||||
}
|
||||
|
||||
function withExpiryFromSettings(
|
||||
accessToken: string,
|
||||
jwt: JwtSettings | null,
|
||||
): Pick<StoredUiAuthSession, "accessExpiresAt" | "refreshExpiresAt"> {
|
||||
const now = Date.now();
|
||||
const accessExpiresAt =
|
||||
decodeJwtExpiryMs(accessToken)
|
||||
?? (typeof jwt?.jwtTokenExpiry === "string" ? now + (parseIsoDuration(jwt.jwtTokenExpiry) ?? 0) : null);
|
||||
const refreshExpiresAt =
|
||||
typeof jwt?.jwtRefreshExpiry === "string" ? now + (parseIsoDuration(jwt.jwtRefreshExpiry) ?? 0) : null;
|
||||
return { accessExpiresAt, refreshExpiresAt };
|
||||
}
|
||||
|
||||
async function fetchJwtSettings(base: string): Promise<JwtSettings | null> {
|
||||
const res = await fetchAuthenticated(
|
||||
`${base}/api/graphql`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: gqlBody(
|
||||
`query GetJWTSettings {
|
||||
settings {
|
||||
jwtAudience
|
||||
jwtRefreshExpiry
|
||||
jwtTokenExpiry
|
||||
}
|
||||
}`,
|
||||
),
|
||||
},
|
||||
timeoutSignal(5000),
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
authDebug("JWT settings fetch failed", { status: res.status });
|
||||
return null;
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
if (json?.errors?.length) {
|
||||
authDebug("JWT settings query error", { errors: json.errors });
|
||||
return null;
|
||||
}
|
||||
|
||||
const settings = json?.data?.settings;
|
||||
if (!settings || typeof settings !== "object") {
|
||||
authDebug("JWT settings missing or invalid", { settings });
|
||||
return null;
|
||||
}
|
||||
|
||||
authDebug("JWT settings fetched", {
|
||||
hasAudience: !!settings.jwtAudience,
|
||||
tokenExpiry: settings.jwtTokenExpiry,
|
||||
refreshExpiry: settings.jwtRefreshExpiry,
|
||||
});
|
||||
|
||||
return {
|
||||
jwtAudience: typeof settings.jwtAudience === "string" ? settings.jwtAudience : null,
|
||||
jwtRefreshExpiry: typeof settings.jwtRefreshExpiry === "string" ? settings.jwtRefreshExpiry : null,
|
||||
jwtTokenExpiry: typeof settings.jwtTokenExpiry === "string" ? settings.jwtTokenExpiry : null,
|
||||
};
|
||||
}
|
||||
|
||||
async function getJwtSettings(force = false): Promise<JwtSettings | null> {
|
||||
const base = getServerBase();
|
||||
const freshEnough = Date.now() - _jwtSettingsFetchedAt < 60_000;
|
||||
if (!force && _jwtSettingsBase === base && _jwtSettings && freshEnough) return _jwtSettings;
|
||||
|
||||
const jwt = await fetchJwtSettings(base);
|
||||
_jwtSettingsBase = base;
|
||||
_jwtSettings = jwt;
|
||||
_jwtSettingsFetchedAt = Date.now();
|
||||
return jwt;
|
||||
}
|
||||
|
||||
export const uiAuth = {
|
||||
getSession: () => {
|
||||
const base = getServerBase();
|
||||
if (_uiSession && _uiSession.base === base) return _uiSession;
|
||||
|
||||
const stored = readStoredSession();
|
||||
if (!stored) return null;
|
||||
if (stored.base !== base) {
|
||||
sessionStorage.removeItem(UI_SESSION_KEY);
|
||||
sessionStorage.removeItem(TOKEN_KEY);
|
||||
_uiSession = null;
|
||||
_accessToken = null;
|
||||
_accessTokenBase = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
_uiSession = stored;
|
||||
_accessToken = stored.accessToken;
|
||||
_accessTokenBase = stored.base;
|
||||
return _uiSession;
|
||||
},
|
||||
setSession: (session: Omit<StoredUiAuthSession, "base">) => {
|
||||
const base = getServerBase();
|
||||
_uiSession = { ...session, base };
|
||||
_accessToken = session.accessToken;
|
||||
_accessTokenBase = base;
|
||||
sessionStorage.setItem(UI_SESSION_KEY, JSON.stringify(_uiSession));
|
||||
sessionStorage.removeItem(TOKEN_KEY);
|
||||
},
|
||||
getToken: () => {
|
||||
const session = uiAuth.getSession();
|
||||
if (!session) return null;
|
||||
|
||||
if (isExpired(session.accessExpiresAt, 0)) return null;
|
||||
|
||||
const base = getServerBase();
|
||||
if (_accessToken && _accessTokenBase === base) return _accessToken;
|
||||
const stored = readStoredToken();
|
||||
if (!stored) return null;
|
||||
if (stored.base !== base) {
|
||||
sessionStorage.removeItem(TOKEN_KEY);
|
||||
sessionStorage.removeItem(UI_SESSION_KEY);
|
||||
_accessToken = null;
|
||||
_accessTokenBase = null;
|
||||
_uiSession = null;
|
||||
return null;
|
||||
}
|
||||
_accessToken = stored.token;
|
||||
_accessTokenBase = stored.base;
|
||||
return _accessToken;
|
||||
},
|
||||
setToken: (t: string) => {
|
||||
const existing = uiAuth.getSession();
|
||||
if (existing?.refreshToken) {
|
||||
uiAuth.setSession({
|
||||
...existing,
|
||||
accessToken: t,
|
||||
...withExpiryFromSettings(t, _jwtSettings),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const base = getServerBase();
|
||||
_accessToken = t;
|
||||
_accessTokenBase = base;
|
||||
sessionStorage.setItem(TOKEN_KEY, JSON.stringify({ base, token: t }));
|
||||
},
|
||||
setLoginSession: (payload: { accessToken: string; refreshToken: string; clientMutationId?: string }, jwt: JwtSettings | null) => {
|
||||
uiAuth.setSession({
|
||||
accessToken: payload.accessToken,
|
||||
refreshToken: payload.refreshToken,
|
||||
clientMutationId: payload.clientMutationId,
|
||||
...withExpiryFromSettings(payload.accessToken, jwt),
|
||||
});
|
||||
},
|
||||
updateAccessToken: (payload: { accessToken: string; clientMutationId?: string }, jwt: JwtSettings | null) => {
|
||||
const existing = uiAuth.getSession();
|
||||
if (!existing?.refreshToken) {
|
||||
uiAuth.setToken(payload.accessToken);
|
||||
return;
|
||||
}
|
||||
uiAuth.setSession({
|
||||
...existing,
|
||||
accessToken: payload.accessToken,
|
||||
clientMutationId: payload.clientMutationId ?? existing.clientMutationId,
|
||||
...withExpiryFromSettings(payload.accessToken, jwt),
|
||||
refreshToken: existing.refreshToken,
|
||||
});
|
||||
},
|
||||
clearToken: () => {
|
||||
_accessToken = null;
|
||||
_accessTokenBase = null;
|
||||
_uiSession = null;
|
||||
sessionStorage.removeItem(TOKEN_KEY);
|
||||
sessionStorage.removeItem(UI_SESSION_KEY);
|
||||
},
|
||||
};
|
||||
|
||||
export const authSession = {
|
||||
clearTokens() {
|
||||
_refreshPromise = null;
|
||||
_jwtSettings = null;
|
||||
_jwtSettingsBase = null;
|
||||
_jwtSettingsFetchedAt = 0;
|
||||
uiAuth.clearToken();
|
||||
},
|
||||
hasSession(): boolean {
|
||||
const mode = store.settings.serverAuthMode ?? "NONE";
|
||||
if (mode === "UI_LOGIN") return uiAuth.getSession() !== null;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
function getServerBase(): string {
|
||||
const url = store.settings.serverUrl;
|
||||
return typeof url === "string" && url.trim() ? url.replace(/\/$/, "") : "http://127.0.0.1:4567";
|
||||
}
|
||||
|
||||
function readStoredToken(): StoredAccessToken | null {
|
||||
const session = readStoredSession();
|
||||
if (session) return { base: session.base, token: session.accessToken };
|
||||
|
||||
const raw = sessionStorage.getItem(TOKEN_KEY);
|
||||
if (raw?.trim()) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed?.base === "string" && typeof parsed?.token === "string")
|
||||
return { base: parsed.base, token: parsed.token };
|
||||
} catch {}
|
||||
|
||||
const migrated = { base: getServerBase(), token: raw.trim() };
|
||||
sessionStorage.setItem(TOKEN_KEY, JSON.stringify(migrated));
|
||||
return migrated;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function readStoredSession(): StoredUiAuthSession | null {
|
||||
const raw = sessionStorage.getItem(UI_SESSION_KEY);
|
||||
if (raw?.trim()) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed?.base === "string" && typeof parsed?.accessToken === "string") {
|
||||
return {
|
||||
base: parsed.base,
|
||||
accessToken: parsed.accessToken,
|
||||
refreshToken: typeof parsed.refreshToken === "string" ? parsed.refreshToken : undefined,
|
||||
clientMutationId: typeof parsed.clientMutationId === "string" ? parsed.clientMutationId : undefined,
|
||||
accessExpiresAt: typeof parsed.accessExpiresAt === "number" ? parsed.accessExpiresAt : null,
|
||||
refreshExpiresAt: typeof parsed.refreshExpiresAt === "number" ? parsed.refreshExpiresAt : null,
|
||||
};
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const legacy = sessionStorage.getItem(TOKEN_KEY);
|
||||
if (!legacy?.trim()) return null;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(legacy);
|
||||
if (typeof parsed?.base === "string" && typeof parsed?.token === "string") {
|
||||
const migrated: StoredUiAuthSession = { base: parsed.base, accessToken: parsed.token };
|
||||
sessionStorage.setItem(UI_SESSION_KEY, JSON.stringify(migrated));
|
||||
return migrated;
|
||||
}
|
||||
} catch {}
|
||||
|
||||
const migrated: StoredUiAuthSession = { base: getServerBase(), accessToken: legacy.trim() };
|
||||
sessionStorage.setItem(UI_SESSION_KEY, JSON.stringify(migrated));
|
||||
return migrated;
|
||||
}
|
||||
|
||||
function timeoutSignal(ms: number): AbortSignal {
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), ms);
|
||||
return controller.signal;
|
||||
}
|
||||
|
||||
function basicHeader(user: string, pass: string): Record<string, string> {
|
||||
return { Authorization: `Basic ${btoa(`${user}:${pass}`)}` };
|
||||
}
|
||||
|
||||
function bearerHeader(token: string): Record<string, string> {
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
function gqlBody(query: string, variables?: Record<string, unknown>): string {
|
||||
return JSON.stringify({ query, ...(variables ? { variables } : {}) });
|
||||
}
|
||||
|
||||
export async function fetchAuthenticated(
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
signal?: AbortSignal,
|
||||
skipped = false,
|
||||
): Promise<Response> {
|
||||
const mode = store.settings.serverAuthMode ?? "NONE";
|
||||
const baseHeaders = (init.headers ?? {}) as Record<string, string>;
|
||||
|
||||
if (mode === "BASIC_AUTH") {
|
||||
const user = store.settings.serverAuthUser?.trim() ?? "";
|
||||
const pass = store.settings.serverAuthPass?.trim() ?? "";
|
||||
return fetch(url, {
|
||||
...init, signal, credentials: "omit",
|
||||
headers: { ...baseHeaders, ...(user && pass ? basicHeader(user, pass) : {}) },
|
||||
});
|
||||
}
|
||||
|
||||
if (mode === "UI_LOGIN") {
|
||||
const token = await getUIAccessToken();
|
||||
if (!token) {
|
||||
if (skipped) return fetch(url, { ...init, signal, credentials: "omit", headers: baseHeaders });
|
||||
throw new AuthRequiredError();
|
||||
}
|
||||
|
||||
let res = await fetch(url, {
|
||||
...init, signal, credentials: "omit",
|
||||
headers: { ...baseHeaders, ...bearerHeader(token) },
|
||||
});
|
||||
|
||||
if (res.status !== 401 || skipped) return res;
|
||||
|
||||
const refreshed = await refreshUiAccessToken(true);
|
||||
if (!refreshed) return res;
|
||||
|
||||
res = await fetch(url, {
|
||||
...init, signal, credentials: "omit",
|
||||
headers: { ...baseHeaders, ...bearerHeader(refreshed) },
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
return fetch(url, { ...init, signal, credentials: "omit" });
|
||||
}
|
||||
|
||||
export async function getUIAccessToken(forceRefresh = false): Promise<string | null> {
|
||||
const session = uiAuth.getSession();
|
||||
if (!session) return null;
|
||||
if (forceRefresh || isExpired(session.accessExpiresAt)) {
|
||||
return refreshUiAccessToken(true);
|
||||
}
|
||||
return session.accessToken;
|
||||
}
|
||||
|
||||
export async function refreshUiAccessToken(force = false): Promise<string | null> {
|
||||
const session = uiAuth.getSession();
|
||||
if (!session) return null;
|
||||
if (!session.refreshToken) {
|
||||
if (force && isExpired(session.accessExpiresAt, 0)) return null;
|
||||
return session.accessToken;
|
||||
}
|
||||
|
||||
if (!force && !isExpired(session.accessExpiresAt)) return session.accessToken;
|
||||
if (isExpired(session.refreshExpiresAt)) {
|
||||
authDebug("refresh skipped: refresh token expired", {
|
||||
force,
|
||||
refreshExpiresAt: session.refreshExpiresAt ?? null,
|
||||
});
|
||||
uiAuth.clearToken();
|
||||
return null;
|
||||
}
|
||||
|
||||
if (_refreshPromise) {
|
||||
authDebug("refresh joined existing request");
|
||||
return _refreshPromise;
|
||||
}
|
||||
|
||||
authDebug("refresh start", {
|
||||
force,
|
||||
accessExpiresAt: session.accessExpiresAt ?? null,
|
||||
refreshExpiresAt: session.refreshExpiresAt ?? null,
|
||||
});
|
||||
|
||||
_refreshPromise = (async () => {
|
||||
const base = getServerBase();
|
||||
const jwt = await getJwtSettings().catch(() => null);
|
||||
|
||||
const res = await fetch(`${base}/api/graphql`, {
|
||||
method: "POST",
|
||||
credentials: "omit",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: gqlBody(
|
||||
`mutation RefreshToken($refreshToken: String!, $clientMutationId: String) {
|
||||
refreshToken(input: { refreshToken: $refreshToken, clientMutationId: $clientMutationId }) {
|
||||
accessToken
|
||||
clientMutationId
|
||||
}
|
||||
}`,
|
||||
{ refreshToken: session.refreshToken, clientMutationId: session.clientMutationId ?? undefined },
|
||||
),
|
||||
signal: timeoutSignal(5000),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
authDebug("refresh rejected by server", { status: res.status });
|
||||
uiAuth.clearToken();
|
||||
return null;
|
||||
}
|
||||
authDebug("refresh failed with HTTP error", { status: res.status });
|
||||
throw new Error(`Token refresh failed (${res.status})`);
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
const refreshed = json?.data?.refreshToken;
|
||||
const nextAccessToken: string | undefined = refreshed?.accessToken;
|
||||
if (!nextAccessToken) {
|
||||
const msg = json?.errors?.[0]?.message;
|
||||
if (msg && /unauthorized|unauthenticated|forbidden/i.test(msg)) {
|
||||
authDebug("refresh rejected by GraphQL error", { message: msg });
|
||||
uiAuth.clearToken();
|
||||
return null;
|
||||
}
|
||||
authDebug("refresh returned no access token", { message: msg ?? null });
|
||||
throw new Error(msg ?? "Token refresh failed");
|
||||
}
|
||||
|
||||
uiAuth.updateAccessToken(
|
||||
{
|
||||
accessToken: nextAccessToken,
|
||||
clientMutationId: typeof refreshed?.clientMutationId === "string"
|
||||
? refreshed.clientMutationId
|
||||
: session.clientMutationId,
|
||||
},
|
||||
jwt,
|
||||
);
|
||||
authDebug("refresh success", {
|
||||
nextAccessExpiresAt: uiAuth.getSession()?.accessExpiresAt ?? null,
|
||||
});
|
||||
return nextAccessToken;
|
||||
})()
|
||||
.catch((e: unknown) => {
|
||||
authDebug("refresh threw error", {
|
||||
message: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
throw e;
|
||||
})
|
||||
.finally(() => {
|
||||
_refreshPromise = null;
|
||||
});
|
||||
|
||||
return _refreshPromise;
|
||||
}
|
||||
|
||||
export function getUiAuthDebugStatus(now = Date.now()): UiAuthDebugStatus {
|
||||
const session = uiAuth.getSession();
|
||||
const accessExpiresAt = session?.accessExpiresAt ?? null;
|
||||
const refreshExpiresAt = session?.refreshExpiresAt ?? null;
|
||||
|
||||
return {
|
||||
mode: (store.settings.serverAuthMode ?? "NONE") as AuthMode,
|
||||
serverBase: getServerBase(),
|
||||
hasSession: !!session,
|
||||
hasRefreshToken: !!session?.refreshToken,
|
||||
accessExpiresAt,
|
||||
refreshExpiresAt,
|
||||
accessExpiresInMs: accessExpiresAt ? accessExpiresAt - now : null,
|
||||
refreshExpiresInMs: refreshExpiresAt ? refreshExpiresAt - now : null,
|
||||
shouldRefreshSoon: isExpired(accessExpiresAt),
|
||||
refreshInFlight: _refreshPromise !== null,
|
||||
skewMs: TOKEN_REFRESH_SKEW_MS,
|
||||
};
|
||||
}
|
||||
|
||||
export async function loginUI(user: string, pass: string): Promise<void> {
|
||||
const res = await fetch(`${getServerBase()}/api/graphql`, {
|
||||
method: "POST", credentials: "omit",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: gqlBody(
|
||||
`mutation Login($username: String!, $password: String!) {
|
||||
login(input: { username: $username, password: $password }) {
|
||||
accessToken
|
||||
refreshToken
|
||||
clientMutationId
|
||||
}
|
||||
}`,
|
||||
{ username: user, password: pass },
|
||||
),
|
||||
signal: timeoutSignal(8000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Login request failed (${res.status})`);
|
||||
const json = await res.json();
|
||||
const payload = json?.data?.login;
|
||||
const accessToken: string | undefined = payload?.accessToken;
|
||||
const refreshToken: string | undefined = payload?.refreshToken;
|
||||
if (!accessToken || !refreshToken) throw new Error(json?.errors?.[0]?.message ?? "Login failed");
|
||||
|
||||
authDebug("login success", { user });
|
||||
|
||||
const preliminarySession = {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
clientMutationId: typeof payload?.clientMutationId === "string" ? payload.clientMutationId : undefined,
|
||||
};
|
||||
|
||||
uiAuth.setLoginSession(preliminarySession, null);
|
||||
updateSettings({ serverAuthMode: "UI_LOGIN", serverAuthUser: user, serverAuthPass: "" });
|
||||
|
||||
const jwt = await getJwtSettings(true).catch(() => null);
|
||||
uiAuth.setLoginSession(preliminarySession, jwt);
|
||||
}
|
||||
|
||||
export async function loginBasic(user: string, pass: string): Promise<void> {
|
||||
const res = await fetch(`${getServerBase()}/api/graphql`, {
|
||||
method: "POST", credentials: "omit",
|
||||
headers: { "Content-Type": "application/json", ...basicHeader(user, pass) },
|
||||
body: gqlBody("{ __typename }"),
|
||||
signal: timeoutSignal(5000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Authentication failed (${res.status})`);
|
||||
updateSettings({ serverAuthMode: "BASIC_AUTH", serverAuthUser: user, serverAuthPass: pass });
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
uiAuth.clearToken();
|
||||
updateSettings({ serverAuthPass: "", serverAuthMode: "NONE" });
|
||||
}
|
||||
|
||||
export async function probeServer(): Promise<"ok" | "auth_required" | "unreachable"> {
|
||||
const base = getServerBase();
|
||||
const mode = store.settings.serverAuthMode ?? "NONE";
|
||||
const s = store.settings;
|
||||
const token = mode === "UI_LOGIN" ? await getUIAccessToken() : null;
|
||||
|
||||
if (mode === "UI_LOGIN" && !token) return "auth_required";
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (mode === "BASIC_AUTH") {
|
||||
const user = s.serverAuthUser?.trim() ?? "";
|
||||
const pass = s.serverAuthPass?.trim() ?? "";
|
||||
if (user && pass) Object.assign(headers, basicHeader(user, pass));
|
||||
} else if (mode === "UI_LOGIN" && token) {
|
||||
Object.assign(headers, bearerHeader(token));
|
||||
}
|
||||
|
||||
const res = await fetch(`${base}/api/graphql`, {
|
||||
method: "POST", credentials: "omit", headers,
|
||||
body: gqlBody("{ __typename }"),
|
||||
signal: timeoutSignal(5000),
|
||||
});
|
||||
|
||||
if (res.ok) return "ok";
|
||||
if (res.status === 401) return "auth_required";
|
||||
return "unreachable";
|
||||
} catch {
|
||||
return "unreachable";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import {
|
||||
persistSettings,
|
||||
persistLibrary,
|
||||
persistUpdates,
|
||||
} from "@core/persistence/persist";
|
||||
|
||||
const STORE_FILES = ["settings.json", "library.json", "updates.json"] as const;
|
||||
|
||||
export async function exportAppData(): Promise<void> {
|
||||
const entries: [string, string][] = await invoke("read_store_files", {
|
||||
names: [...STORE_FILES],
|
||||
});
|
||||
|
||||
const zip = buildZip(
|
||||
entries.map(([name, content]) => ({
|
||||
name,
|
||||
bytes: new TextEncoder().encode(content),
|
||||
}))
|
||||
);
|
||||
|
||||
await invoke("export_app_data", { bytes: Array.from(zip) });
|
||||
}
|
||||
|
||||
export async function importAppData(): Promise<void> {
|
||||
const raw: number[] = await invoke("import_app_data");
|
||||
const files = parseZip(new Uint8Array(raw));
|
||||
|
||||
const decode = (name: string) => {
|
||||
const bytes = files.get(name);
|
||||
if (!bytes) throw new Error(`Backup is missing ${name}`);
|
||||
return JSON.parse(new TextDecoder().decode(bytes));
|
||||
};
|
||||
|
||||
const s = decode("settings.json");
|
||||
const l = decode("library.json");
|
||||
const u = decode("updates.json");
|
||||
|
||||
await Promise.all([
|
||||
persistSettings({
|
||||
settings: s.settings ?? null,
|
||||
storeVersion: s.storeVersion ?? 1,
|
||||
}),
|
||||
persistLibrary({
|
||||
history: l.history ?? [],
|
||||
bookmarks: l.bookmarks ?? [],
|
||||
markers: l.markers ?? [],
|
||||
readLog: l.readLog ?? [],
|
||||
readingStats: l.readingStats ?? null,
|
||||
dailyReadCounts: l.dailyReadCounts ?? {},
|
||||
}),
|
||||
persistUpdates({
|
||||
libraryUpdates: u.libraryUpdates ?? [],
|
||||
lastLibraryRefresh: u.lastLibraryRefresh ?? 0,
|
||||
acknowledgedUpdateIds: u.acknowledgedUpdateIds ?? [],
|
||||
}),
|
||||
]);
|
||||
|
||||
await showExitModal();
|
||||
invoke("exit_app");
|
||||
}
|
||||
|
||||
function showExitModal(): Promise<void> {
|
||||
return new Promise(resolve => {
|
||||
const backdrop = document.createElement("div");
|
||||
backdrop.className = "s-backdrop";
|
||||
backdrop.style.cssText = "z-index:99999";
|
||||
|
||||
const modal = document.createElement("div");
|
||||
modal.style.cssText = [
|
||||
"background:var(--bg-surface)",
|
||||
"border:1px solid var(--border-base)",
|
||||
"border-radius:var(--radius-2xl)",
|
||||
"box-shadow:0 0 0 1px rgba(255,255,255,0.04) inset,0 24px 80px rgba(0,0,0,0.7),0 8px 24px rgba(0,0,0,0.4)",
|
||||
"width:min(400px,calc(100vw - 40px))",
|
||||
"display:flex",
|
||||
"flex-direction:column",
|
||||
"overflow:hidden",
|
||||
"animation:s-scale-in 0.2s cubic-bezier(0.16,1,0.3,1) both",
|
||||
].join(";");
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.style.cssText = "padding:var(--sp-4) var(--sp-5) var(--sp-3);border-bottom:1px solid var(--border-dim)";
|
||||
|
||||
const title = document.createElement("p");
|
||||
title.style.cssText = "margin:0;font-size:var(--text-sm);font-weight:var(--weight-medium);color:var(--text-primary);letter-spacing:0.01em";
|
||||
title.textContent = "Import complete";
|
||||
header.appendChild(title);
|
||||
|
||||
const body = document.createElement("div");
|
||||
body.style.cssText = "padding:var(--sp-4) var(--sp-5);display:flex;flex-direction:column;gap:var(--sp-2)";
|
||||
|
||||
const sub = document.createElement("p");
|
||||
sub.style.cssText = "margin:0;font-family:var(--font-ui);font-size:var(--text-xs);color:var(--text-faint);letter-spacing:var(--tracking-wide);line-height:var(--leading-snug)";
|
||||
sub.textContent = "Your settings have been restored. Moku will close so you can relaunch with the imported data.";
|
||||
|
||||
const counter = document.createElement("p");
|
||||
counter.style.cssText = "margin:0;font-family:var(--font-ui);font-size:var(--text-xs);color:var(--text-faint);letter-spacing:var(--tracking-wide)";
|
||||
counter.textContent = "Closing in 3…";
|
||||
|
||||
body.append(sub, counter);
|
||||
|
||||
const footer = document.createElement("div");
|
||||
footer.style.cssText = "padding:var(--sp-3) var(--sp-5);border-top:1px solid var(--border-dim);display:flex;justify-content:flex-end";
|
||||
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "s-btn s-btn-danger";
|
||||
btn.textContent = "Close now";
|
||||
|
||||
footer.appendChild(btn);
|
||||
modal.append(header, body, footer);
|
||||
backdrop.appendChild(modal);
|
||||
document.body.appendChild(backdrop);
|
||||
|
||||
let secs = 3;
|
||||
const tick = setInterval(() => {
|
||||
secs--;
|
||||
counter.textContent = secs > 0 ? `Closing in ${secs}…` : "Closing…";
|
||||
if (secs <= 0) { clearInterval(tick); backdrop.remove(); resolve(); }
|
||||
}, 1000);
|
||||
|
||||
btn.addEventListener("click", () => { clearInterval(tick); backdrop.remove(); resolve(); });
|
||||
});
|
||||
}
|
||||
|
||||
export async function autoBackupAppData(): Promise<void> {
|
||||
try {
|
||||
const entries: [string, string][] = await invoke("read_store_files", {
|
||||
names: [...STORE_FILES],
|
||||
});
|
||||
const zip = buildZip(
|
||||
entries.map(([name, content]) => ({
|
||||
name,
|
||||
bytes: new TextEncoder().encode(content),
|
||||
}))
|
||||
);
|
||||
await invoke("auto_backup_app_data", { bytes: Array.from(zip) });
|
||||
} catch (e) {
|
||||
console.warn("[moku] auto-backup failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
function crc32(data: Uint8Array): number {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of data) {
|
||||
crc ^= byte;
|
||||
for (let j = 0; j < 8; j++) {
|
||||
crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
|
||||
}
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function localHeader(name: Uint8Array, data: Uint8Array): Uint8Array {
|
||||
const buf = new ArrayBuffer(30 + name.byteLength);
|
||||
const v = new DataView(buf);
|
||||
v.setUint32(0, 0x04034b50, true);
|
||||
v.setUint16(4, 20, true);
|
||||
v.setUint16(6, 0, true);
|
||||
v.setUint16(8, 0, true);
|
||||
v.setUint16(10, 0, true);
|
||||
v.setUint16(12, 0, true);
|
||||
v.setUint32(14, crc32(data), true);
|
||||
v.setUint32(18, data.byteLength, true);
|
||||
v.setUint32(22, data.byteLength, true);
|
||||
v.setUint16(26, name.byteLength, true);
|
||||
v.setUint16(28, 0, true);
|
||||
new Uint8Array(buf).set(name, 30);
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
function centralHeader(name: Uint8Array, data: Uint8Array, offset: number): Uint8Array {
|
||||
const buf = new ArrayBuffer(46 + name.byteLength);
|
||||
const v = new DataView(buf);
|
||||
v.setUint32(0, 0x02014b50, true);
|
||||
v.setUint16(4, 20, true);
|
||||
v.setUint16(6, 20, true);
|
||||
v.setUint16(8, 0, true);
|
||||
v.setUint16(10, 0, true);
|
||||
v.setUint16(12, 0, true);
|
||||
v.setUint16(14, 0, true);
|
||||
v.setUint32(16, crc32(data), true);
|
||||
v.setUint32(20, data.byteLength, true);
|
||||
v.setUint32(24, data.byteLength, true);
|
||||
v.setUint16(28, name.byteLength, true);
|
||||
v.setUint16(30, 0, true);
|
||||
v.setUint16(32, 0, true);
|
||||
v.setUint16(34, 0, true);
|
||||
v.setUint16(36, 0, true);
|
||||
v.setUint32(38, 0, true);
|
||||
v.setUint32(42, offset, true);
|
||||
new Uint8Array(buf).set(name, 46);
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
function eocd(count: number, cdSize: number, cdOffset: number): Uint8Array {
|
||||
const buf = new ArrayBuffer(22);
|
||||
const v = new DataView(buf);
|
||||
v.setUint32(0, 0x06054b50, true);
|
||||
v.setUint16(4, 0, true);
|
||||
v.setUint16(6, 0, true);
|
||||
v.setUint16(8, count, true);
|
||||
v.setUint16(10, count, true);
|
||||
v.setUint32(12, cdSize, true);
|
||||
v.setUint32(16, cdOffset, true);
|
||||
v.setUint16(20, 0, true);
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
function buildZip(files: { name: string; bytes: Uint8Array }[]): Uint8Array {
|
||||
const enc = new TextEncoder();
|
||||
const parts: Uint8Array[] = [];
|
||||
const offsets: number[] = [];
|
||||
let pos = 0;
|
||||
|
||||
for (const { name, bytes } of files) {
|
||||
const nameBytes = enc.encode(name);
|
||||
const lh = localHeader(nameBytes, bytes);
|
||||
offsets.push(pos);
|
||||
parts.push(lh, bytes);
|
||||
pos += lh.byteLength + bytes.byteLength;
|
||||
}
|
||||
|
||||
const cdParts = files.map(({ name, bytes }, i) =>
|
||||
centralHeader(enc.encode(name), bytes, offsets[i])
|
||||
);
|
||||
const cd = concat(cdParts);
|
||||
|
||||
return concat([...parts, cd, eocd(files.length, cd.byteLength, pos)]);
|
||||
}
|
||||
|
||||
function parseZip(data: Uint8Array): Map<string, Uint8Array> {
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
const files = new Map<string, Uint8Array>();
|
||||
let pos = 0;
|
||||
|
||||
while (pos + 30 <= data.byteLength && view.getUint32(pos, true) === 0x04034b50) {
|
||||
const fnLen = view.getUint16(pos + 26, true);
|
||||
const exLen = view.getUint16(pos + 28, true);
|
||||
const cSize = view.getUint32(pos + 18, true);
|
||||
const name = new TextDecoder().decode(data.subarray(pos + 30, pos + 30 + fnLen));
|
||||
const start = pos + 30 + fnLen + exLen;
|
||||
files.set(name, data.subarray(start, start + cSize));
|
||||
pos = start + cSize;
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
function concat(arrays: Uint8Array[]): Uint8Array {
|
||||
const total = arrays.reduce((n, a) => n + a.byteLength, 0);
|
||||
const out = new Uint8Array(total);
|
||||
let pos = 0;
|
||||
for (const a of arrays) { out.set(a, pos); pos += a.byteLength; }
|
||||
return out;
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
|
||||
import { store } from "@store/state.svelte";
|
||||
import { getUIAccessToken } from "@core/auth";
|
||||
|
||||
const cache = new Map<string, string>();
|
||||
const inflight = new Map<string, Promise<string>>();
|
||||
const MAX_CONCURRENT = 6;
|
||||
let active = 0;
|
||||
let active = 0;
|
||||
let drainScheduled = false;
|
||||
let clearing = false;
|
||||
|
||||
interface QueueEntry {
|
||||
url: string;
|
||||
@@ -16,16 +18,27 @@ interface QueueEntry {
|
||||
|
||||
const queue: QueueEntry[] = [];
|
||||
|
||||
function getAuthHeaders(): Record<string, string> {
|
||||
const user = store.settings.serverAuthUser?.trim() ?? "";
|
||||
const pass = store.settings.serverAuthPass?.trim() ?? "";
|
||||
return user && pass ? { Authorization: `Basic ${btoa(`${user}:${pass}`)}` } : {};
|
||||
async function getAuthHeaders(): Promise<Record<string, string>> {
|
||||
const mode = store.settings.serverAuthMode ?? "NONE";
|
||||
if (mode === "UI_LOGIN") {
|
||||
const token = await getUIAccessToken();
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
}
|
||||
if (mode === "BASIC_AUTH") {
|
||||
const user = store.settings.serverAuthUser?.trim() ?? "";
|
||||
const pass = store.settings.serverAuthPass?.trim() ?? "";
|
||||
return user && pass ? { Authorization: `Basic ${btoa(`${user}:${pass}`)}` } : {};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
async function doFetch(url: string): Promise<string> {
|
||||
const res = await tauriFetch(url, { method: "GET", headers: getAuthHeaders() });
|
||||
const headers = await getAuthHeaders();
|
||||
const res = await tauriFetch(url, { method: "GET", headers });
|
||||
if (!res.ok) throw new Error(`${res.status}`);
|
||||
const blobUrl = URL.createObjectURL(await res.blob());
|
||||
const blob = await res.blob();
|
||||
if (clearing) throw new DOMException("Cancelled", "AbortError");
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
cache.set(url, blobUrl);
|
||||
return blobUrl;
|
||||
}
|
||||
@@ -47,7 +60,7 @@ function drain() {
|
||||
active++;
|
||||
doFetch(entry.url)
|
||||
.then(entry.resolve, entry.reject)
|
||||
.finally(() => { inflight.delete(entry.url); active--; drain(); });
|
||||
.finally(() => { active--; drain(); });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +71,12 @@ function scheduleDrain() {
|
||||
}
|
||||
|
||||
function enqueue(url: string, priority: number): Promise<string> {
|
||||
const promise = new Promise<string>((resolve, reject) => { insertSorted({ url, priority, resolve, reject }); });
|
||||
const promise = new Promise<string>((resolve, reject) => {
|
||||
insertSorted({ url, priority, resolve, reject });
|
||||
}).catch(err => {
|
||||
inflight.delete(url);
|
||||
return Promise.reject(err);
|
||||
});
|
||||
inflight.set(url, promise);
|
||||
scheduleDrain();
|
||||
return promise;
|
||||
@@ -98,7 +116,19 @@ export function deprioritizeQueue(): void {
|
||||
queue.sort((a, b) => b.priority - a.priority);
|
||||
}
|
||||
|
||||
export function cancelQueuedFetches(): void {
|
||||
const dropped = queue.splice(0);
|
||||
for (const entry of dropped) {
|
||||
inflight.delete(entry.url);
|
||||
entry.reject(new DOMException("Cancelled", "AbortError"));
|
||||
}
|
||||
}
|
||||
|
||||
export function clearBlobCache(): void {
|
||||
clearing = true;
|
||||
cancelQueuedFetches();
|
||||
cache.forEach(blob => URL.revokeObjectURL(blob));
|
||||
cache.clear();
|
||||
inflight.clear();
|
||||
clearing = false;
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
interface MemEntry<T> {
|
||||
value: T;
|
||||
expiresAt: number;
|
||||
key: string;
|
||||
}
|
||||
|
||||
export class MemoryCache<T> {
|
||||
readonly #cap: number;
|
||||
readonly #ttl: number;
|
||||
readonly #map = new Map<string, MemEntry<T>>();
|
||||
|
||||
constructor(capacity: number, ttlMs: number) {
|
||||
this.#cap = capacity;
|
||||
this.#ttl = ttlMs;
|
||||
}
|
||||
|
||||
get(key: string): T | undefined {
|
||||
const entry = this.#map.get(key);
|
||||
if (!entry) return undefined;
|
||||
if (Date.now() > entry.expiresAt) { this.#map.delete(key); return undefined; }
|
||||
this.#map.delete(key);
|
||||
this.#map.set(key, entry);
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
set(key: string, value: T): void {
|
||||
if (this.#map.has(key)) this.#map.delete(key);
|
||||
else if (this.#map.size >= this.#cap) this.#map.delete(this.#map.keys().next().value!);
|
||||
this.#map.set(key, { value, expiresAt: Date.now() + this.#ttl, key });
|
||||
}
|
||||
|
||||
has(key: string): boolean {
|
||||
const entry = this.#map.get(key);
|
||||
if (!entry) return false;
|
||||
if (Date.now() > entry.expiresAt) { this.#map.delete(key); return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
delete(key: string): void { this.#map.delete(key); }
|
||||
|
||||
clear(): void { this.#map.clear(); }
|
||||
|
||||
get size(): number { return this.#map.size; }
|
||||
}
|
||||
+20
-15
@@ -1,18 +1,23 @@
|
||||
import { gql, plainThumbUrl } from "@api/client";
|
||||
import { getBlobUrl, preloadBlobUrls } from "@core/cache/imageCache";
|
||||
import { dedupeRequest } from "@core/async/batchRequests";
|
||||
import { FETCH_CHAPTER_PAGES } from "@api/mutations/chapters";
|
||||
import { gql, getServerUrl } from "@api/client";
|
||||
import { getBlobUrl, preloadBlobUrls } from "@core/cache/imageCache";
|
||||
import { dedupeRequest } from "@core/async/batchRequests";
|
||||
import { FETCH_CHAPTER_PAGES } from "@api/mutations/chapters";
|
||||
|
||||
const pageCache = new Map<number, string[]>();
|
||||
const inflight = new Map<number, Promise<string[]>>();
|
||||
const resolvedUrlCache = new Map<string, Promise<string>>();
|
||||
const preloadedUrls = new Set<string>();
|
||||
const aspectCache = new Map<string, number>();
|
||||
|
||||
export function resolveUrl(url: string, useBlob: boolean, priority = 0): Promise<string> {
|
||||
if (!useBlob) return Promise.resolve(url);
|
||||
if (!resolvedUrlCache.has(url)) resolvedUrlCache.set(url, getBlobUrl(url, priority));
|
||||
return resolvedUrlCache.get(url)!;
|
||||
const cached = resolvedUrlCache.get(url);
|
||||
if (cached) return cached;
|
||||
const p = getBlobUrl(url, priority).catch(err => {
|
||||
resolvedUrlCache.delete(url);
|
||||
return Promise.reject(err);
|
||||
});
|
||||
resolvedUrlCache.set(url, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
export function fetchPages(
|
||||
@@ -29,11 +34,8 @@ export function fetchPages(
|
||||
const p = dedupeRequest(`chapter-pages:${chapterId}`, () =>
|
||||
gql<{ fetchChapterPages: { pages: string[] } }>(FETCH_CHAPTER_PAGES, { chapterId })
|
||||
.then(d => {
|
||||
const urls = d.fetchChapterPages.pages.map(p => plainThumbUrl(p));
|
||||
if (useBlob) {
|
||||
if (urls[priorityPage]) getBlobUrl(urls[priorityPage], urls.length + 999);
|
||||
preloadBlobUrls(urls.filter((_, i) => i !== priorityPage), urls.length);
|
||||
}
|
||||
const urls = d.fetchChapterPages.pages.map(p => p.startsWith("http") ? p : `${getServerUrl()}${p}`);
|
||||
if (useBlob && urls[priorityPage]) getBlobUrl(urls[priorityPage], 999);
|
||||
pageCache.set(chapterId, urls);
|
||||
return urls;
|
||||
})
|
||||
@@ -60,11 +62,15 @@ export function measureAspect(url: string, useBlob: boolean): Promise<number> {
|
||||
}
|
||||
|
||||
export function preloadImage(url: string, useBlob: boolean): void {
|
||||
if (preloadedUrls.has(url)) return;
|
||||
preloadedUrls.add(url);
|
||||
if (useBlob) { preloadBlobUrls([url], 0); return; }
|
||||
resolveUrl(url, useBlob).then(src => { new Image().src = src; }).catch(() => {});
|
||||
}
|
||||
|
||||
export function clearResolvedUrlCache(): void {
|
||||
resolvedUrlCache.clear();
|
||||
aspectCache.clear();
|
||||
}
|
||||
|
||||
export function clearPageCache(chapterId?: number): void {
|
||||
if (chapterId !== undefined) {
|
||||
pageCache.delete(chapterId);
|
||||
@@ -73,7 +79,6 @@ export function clearPageCache(chapterId?: number): void {
|
||||
pageCache.clear();
|
||||
inflight.clear();
|
||||
resolvedUrlCache.clear();
|
||||
preloadedUrls.clear();
|
||||
aspectCache.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
interface Entry<T> {
|
||||
promise: Promise<T>;
|
||||
fetchedAt: number;
|
||||
fetcher?: () => Promise<T>;
|
||||
ttl?: number;
|
||||
}
|
||||
|
||||
const store = new Map<string, Entry<unknown>>();
|
||||
const subs = new Map<string, Set<() => void>>();
|
||||
const groups = new Map<string, Set<string>>();
|
||||
const keyToGroups = new Map<string, Set<string>>();
|
||||
const groups = new Map<string, Set<string>>();
|
||||
|
||||
export const DEFAULT_TTL_MS = 5 * 60 * 1_000;
|
||||
|
||||
@@ -16,6 +19,16 @@ function registerGroups(key: string, group?: string | string[]) {
|
||||
for (const tag of Array.isArray(group) ? group : [group]) {
|
||||
if (!groups.has(tag)) groups.set(tag, new Set());
|
||||
groups.get(tag)!.add(key);
|
||||
if (!keyToGroups.has(key)) keyToGroups.set(key, new Set());
|
||||
keyToGroups.get(key)!.add(tag);
|
||||
}
|
||||
}
|
||||
|
||||
function unregisterKey(key: string) {
|
||||
const tags = keyToGroups.get(key);
|
||||
if (tags) {
|
||||
for (const tag of tags) groups.get(tag)?.delete(key);
|
||||
keyToGroups.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,14 +40,20 @@ export const cache = {
|
||||
if (err?.name !== "AbortError") store.delete(key);
|
||||
return Promise.reject(err);
|
||||
}) as Promise<T>;
|
||||
store.set(key, { promise, fetchedAt: Date.now() });
|
||||
store.set(key, { promise, fetchedAt: Date.now(), fetcher: fetcher as () => Promise<unknown>, ttl });
|
||||
registerGroups(key, group);
|
||||
promise.then(() => notify(key)).catch(() => {});
|
||||
return promise;
|
||||
},
|
||||
|
||||
set<T>(key: string, value: T, group?: string | string[]) {
|
||||
store.set(key, { promise: Promise.resolve(value), fetchedAt: Date.now() });
|
||||
const existing = store.get(key) as Entry<T> | undefined;
|
||||
store.set(key, {
|
||||
promise: Promise.resolve(value),
|
||||
fetchedAt: Date.now(),
|
||||
fetcher: existing?.fetcher,
|
||||
ttl: existing?.ttl,
|
||||
});
|
||||
registerGroups(key, group);
|
||||
notify(key);
|
||||
},
|
||||
@@ -43,10 +62,38 @@ export const cache = {
|
||||
const existing = store.get(key) as Entry<T> | undefined;
|
||||
if (!existing) return;
|
||||
const next = existing.promise.then(fn);
|
||||
store.set(key, { promise: next, fetchedAt: Date.now() });
|
||||
store.set(key, { ...existing, promise: next, fetchedAt: Date.now() });
|
||||
next.then(() => notify(key)).catch(() => {});
|
||||
},
|
||||
|
||||
refresh<T>(key: string): Promise<T> | undefined {
|
||||
const existing = store.get(key) as Entry<T> | undefined;
|
||||
if (!existing?.fetcher) return undefined;
|
||||
const promise = (existing.fetcher as () => Promise<T>)().catch(err => {
|
||||
if (err?.name !== "AbortError") store.delete(key);
|
||||
return Promise.reject(err);
|
||||
});
|
||||
store.set(key, { ...existing, promise: promise as Promise<unknown>, fetchedAt: Date.now() });
|
||||
promise.then(() => notify(key)).catch(() => {});
|
||||
return promise;
|
||||
},
|
||||
|
||||
refreshGroup(tag: string): void {
|
||||
const keys = groups.get(tag);
|
||||
if (!keys) return;
|
||||
for (const key of [...keys]) {
|
||||
const existing = store.get(key);
|
||||
if (existing?.fetcher) {
|
||||
const promise = existing.fetcher().catch(err => {
|
||||
if (err?.name !== "AbortError") store.delete(key);
|
||||
return Promise.reject(err);
|
||||
});
|
||||
store.set(key, { ...existing, promise, fetchedAt: Date.now() });
|
||||
promise.then(() => notify(key)).catch(() => {});
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
has(key: string): boolean { return store.has(key); },
|
||||
|
||||
ageOf(key: string): number | undefined {
|
||||
@@ -54,18 +101,35 @@ export const cache = {
|
||||
return e ? Date.now() - e.fetchedAt : undefined;
|
||||
},
|
||||
|
||||
clear(key: string) { store.delete(key); notify(key); },
|
||||
isStale(key: string): boolean {
|
||||
const e = store.get(key);
|
||||
if (!e) return true;
|
||||
return Date.now() - e.fetchedAt >= (e.ttl ?? DEFAULT_TTL_MS);
|
||||
},
|
||||
|
||||
clear(key: string) {
|
||||
unregisterKey(key);
|
||||
store.delete(key);
|
||||
notify(key);
|
||||
},
|
||||
|
||||
clearGroup(tag: string) {
|
||||
const keys = groups.get(tag);
|
||||
if (!keys) return;
|
||||
for (const key of keys) { store.delete(key); notify(key); }
|
||||
for (const key of [...keys]) {
|
||||
keyToGroups.get(key)?.delete(tag);
|
||||
if (keyToGroups.get(key)?.size === 0) keyToGroups.delete(key);
|
||||
store.delete(key);
|
||||
notify(key);
|
||||
}
|
||||
groups.delete(tag);
|
||||
},
|
||||
|
||||
clearAll() {
|
||||
const allKeys = [...store.keys()];
|
||||
store.clear(); groups.clear();
|
||||
store.clear();
|
||||
groups.clear();
|
||||
keyToGroups.clear();
|
||||
allKeys.forEach(notify);
|
||||
},
|
||||
|
||||
@@ -83,6 +147,7 @@ export const CACHE_GROUPS = {
|
||||
|
||||
export const CACHE_KEYS = {
|
||||
LIBRARY: "library",
|
||||
RECENT_UPDATES: "recent_updates",
|
||||
ALL_MANGA: "all_manga_unfiltered",
|
||||
CATEGORIES: "categories",
|
||||
SEARCH: "search_all_manga",
|
||||
@@ -159,3 +224,18 @@ export function getTopSources<T extends { id: string }>(sources: T[]): T[] {
|
||||
}
|
||||
return sources.slice(0, MAX_FRECENCY_SOURCES);
|
||||
}
|
||||
|
||||
export async function refreshMangaCache(mangaId: number, thumbnailUrl?: string): Promise<void> {
|
||||
const didRefresh = cache.refresh(CACHE_KEYS.MANGA(mangaId));
|
||||
if (!didRefresh) cache.clear(CACHE_KEYS.MANGA(mangaId));
|
||||
|
||||
cache.clear(CACHE_KEYS.CHAPTERS(mangaId));
|
||||
cache.clear(CACHE_KEYS.LIBRARY);
|
||||
cache.clear(CACHE_KEYS.ALL_MANGA);
|
||||
|
||||
if (thumbnailUrl) {
|
||||
const { revokeBlobUrl, getBlobUrl } = await import("@core/cache/imageCache");
|
||||
revokeBlobUrl(thumbnailUrl);
|
||||
getBlobUrl(thumbnailUrl, 999).catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { store, linkManga } from "@store/state.svelte";
|
||||
import type { Manga } from "@types";
|
||||
|
||||
export function autoLinkLibrary(focal: Manga, allManga: Manga[]): Promise<number> {
|
||||
return new Promise((resolve) => {
|
||||
const worker = new Worker(
|
||||
new URL("./autoLinkWorker.ts", import.meta.url),
|
||||
{ type: "module" },
|
||||
);
|
||||
|
||||
worker.onmessage = (e: MessageEvent<number[]>) => {
|
||||
const matches = e.data;
|
||||
for (const id of matches) linkManga(focal.id, id);
|
||||
worker.terminate();
|
||||
resolve(matches.length);
|
||||
};
|
||||
|
||||
worker.onerror = () => { worker.terminate(); resolve(0); };
|
||||
|
||||
worker.postMessage({
|
||||
focalTitle: focal.title,
|
||||
focalId: focal.id,
|
||||
allManga: allManga.map(m => ({ id: m.id, title: m.title })),
|
||||
linkedIds: store.settings.mangaLinks?.[focal.id] ?? [],
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
interface WorkerMsg {
|
||||
focalTitle: string;
|
||||
focalId: number;
|
||||
allManga: { id: number; title: string }[];
|
||||
linkedIds: number[];
|
||||
}
|
||||
|
||||
function titleSimilarity(a: string, b: string): number {
|
||||
const norm = (s: string) =>
|
||||
s.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter(Boolean);
|
||||
const wa = new Set(norm(a));
|
||||
const wb = new Set(norm(b));
|
||||
if (!wa.size || !wb.size) return 0;
|
||||
const intersection = [...wa].filter(w => wb.has(w)).length;
|
||||
return intersection / new Set([...wa, ...wb]).size;
|
||||
}
|
||||
|
||||
self.onmessage = (e: MessageEvent<WorkerMsg>) => {
|
||||
const { focalTitle, focalId, allManga, linkedIds } = e.data;
|
||||
const matches: number[] = [];
|
||||
|
||||
for (const m of allManga) {
|
||||
if (m.id === focalId) continue;
|
||||
if (linkedIds.includes(m.id)) continue;
|
||||
if (titleSimilarity(focalTitle, m.title) >= 0.65) matches.push(m.id);
|
||||
}
|
||||
|
||||
self.postMessage(matches);
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
const THUMB_SIZE = 16;
|
||||
const DUPE_THRESH = 0.12;
|
||||
|
||||
const hashCache = new Map<string, Uint8ClampedArray>();
|
||||
|
||||
function toGray(data: Uint8ClampedArray, pixels: number): Uint8ClampedArray {
|
||||
const gray = new Uint8ClampedArray(pixels);
|
||||
for (let i = 0; i < pixels; i++) {
|
||||
const o = i * 4;
|
||||
gray[i] = (data[o] * 299 + data[o + 1] * 587 + data[o + 2] * 114) / 1000;
|
||||
}
|
||||
return gray;
|
||||
}
|
||||
|
||||
function loadThumb(url: string): Promise<Uint8ClampedArray> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.crossOrigin = "anonymous";
|
||||
img.onload = () => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = THUMB_SIZE;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.drawImage(img, 0, 0, THUMB_SIZE, THUMB_SIZE);
|
||||
resolve(toGray(ctx.getImageData(0, 0, THUMB_SIZE, THUMB_SIZE).data, THUMB_SIZE * THUMB_SIZE));
|
||||
};
|
||||
img.onerror = reject;
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
function similarity(a: Uint8ClampedArray, b: Uint8ClampedArray): number {
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++) diff += Math.abs(a[i] - b[i]);
|
||||
return diff / (a.length * 255);
|
||||
}
|
||||
|
||||
export async function getHash(url: string): Promise<Uint8ClampedArray | null> {
|
||||
if (hashCache.has(url)) return hashCache.get(url)!;
|
||||
try {
|
||||
const thumb = await loadThumb(url);
|
||||
hashCache.set(url, thumb);
|
||||
return thumb;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function areDuplicates(a: Uint8ClampedArray, b: Uint8ClampedArray): boolean {
|
||||
return similarity(a, b) <= DUPE_THRESH;
|
||||
}
|
||||
|
||||
export function clearHashCache(): void {
|
||||
hashCache.clear();
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { store } from "@store/state.svelte";
|
||||
import { searchWithScore } from "@core/algorithms/search";
|
||||
import { getHash, areDuplicates } from "@core/cover/coverHash";
|
||||
|
||||
type CoverManga = { id: number; thumbnailUrl: string; source?: { displayName: string } | null };
|
||||
|
||||
export type CoverCandidate = {
|
||||
mangaId: number;
|
||||
url: string;
|
||||
label: string;
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
const FUZZY_SCORE_THRESHOLD = 0.65;
|
||||
|
||||
function normalizeUrl(url: string): string {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
u.search = "";
|
||||
return u.href.toLowerCase();
|
||||
} catch {
|
||||
return url.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
export function resolvedCover(mangaId: number, ownUrl: string): string {
|
||||
return store.settings.mangaPrefs?.[mangaId]?.coverUrl ?? ownUrl;
|
||||
}
|
||||
|
||||
function fuzzyMatchIds(
|
||||
mangaId: number,
|
||||
title: string,
|
||||
mangaById: Map<number, CoverManga & { title: string }>,
|
||||
): number[] {
|
||||
const results = searchWithScore(
|
||||
[...mangaById.values()].filter(m => m.id !== mangaId),
|
||||
title,
|
||||
m => m.title,
|
||||
);
|
||||
return results
|
||||
.filter(r => r.score >= FUZZY_SCORE_THRESHOLD)
|
||||
.map(r => r.item.id);
|
||||
}
|
||||
|
||||
export function coverCandidatesSync(
|
||||
mangaId: number,
|
||||
title: string,
|
||||
ownUrl: string,
|
||||
mangaById: Map<number, CoverManga & { title: string }>,
|
||||
): CoverCandidate[] {
|
||||
const linkedIds = store.getLinkedMangaIds(mangaId);
|
||||
const fuzzyIds = fuzzyMatchIds(mangaId, title, mangaById);
|
||||
const current = store.settings.mangaPrefs?.[mangaId]?.coverUrl ?? ownUrl;
|
||||
|
||||
const allIds = Array.from(new Set([...linkedIds, ...fuzzyIds]));
|
||||
|
||||
const raw: { mangaId: number; url: string; label: string }[] = [
|
||||
{ mangaId, url: ownUrl, label: "This source" },
|
||||
...allIds.flatMap(id => {
|
||||
const m = mangaById.get(id);
|
||||
return m ? [{ mangaId: m.id, url: m.thumbnailUrl, label: m.source?.displayName ?? `ID ${m.id}` }] : [];
|
||||
}),
|
||||
];
|
||||
|
||||
const seen = new Set<string>();
|
||||
return raw
|
||||
.filter(c => {
|
||||
const key = normalizeUrl(c.url);
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
})
|
||||
.map(c => ({ ...c, isActive: normalizeUrl(c.url) === normalizeUrl(current) }));
|
||||
}
|
||||
|
||||
export async function dedupeByImage(candidates: CoverCandidate[]): Promise<CoverCandidate[]> {
|
||||
const hashes = await Promise.all(candidates.map(c => getHash(c.url)));
|
||||
|
||||
const groups: number[][] = [];
|
||||
|
||||
for (let i = 0; i < candidates.length; i++) {
|
||||
const hi = hashes[i];
|
||||
const existing = hi
|
||||
? groups.find(g => { const hj = hashes[g[0]]; return hj ? areDuplicates(hi, hj) : false; })
|
||||
: undefined;
|
||||
if (existing) existing.push(i);
|
||||
else groups.push([i]);
|
||||
}
|
||||
|
||||
return groups.map(group => {
|
||||
const active = group.find(i => candidates[i].isActive) ?? group[0];
|
||||
const labels = [...new Set(group.map(i => candidates[i].label))];
|
||||
return { ...candidates[active], label: labels.join(" · ") };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export { getHash, areDuplicates, clearHashCache } from "./coverHash";
|
||||
export { resolvedCover, coverCandidatesSync, dedupeByImage } from "./coverResolver";
|
||||
export type { CoverCandidate } from "./coverResolver";
|
||||
export { autoLinkLibrary } from "./autoLink";
|
||||
@@ -12,6 +12,7 @@ export interface Keybinds {
|
||||
openSettings: string;
|
||||
toggleBookmark: string;
|
||||
toggleMarker: string;
|
||||
toggleAutoScroll: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_KEYBINDS: Keybinds = {
|
||||
@@ -28,6 +29,7 @@ export const DEFAULT_KEYBINDS: Keybinds = {
|
||||
openSettings: "o",
|
||||
toggleBookmark: "m",
|
||||
toggleMarker: "n",
|
||||
toggleAutoScroll: "s",
|
||||
};
|
||||
|
||||
export const KEYBIND_LABELS: Record<keyof Keybinds, string> = {
|
||||
@@ -44,4 +46,5 @@ export const KEYBIND_LABELS: Record<keyof Keybinds, string> = {
|
||||
openSettings: "Open settings",
|
||||
toggleBookmark: "Toggle bookmark",
|
||||
toggleMarker: "Toggle marker",
|
||||
toggleAutoScroll: "Toggle auto scroll",
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
const VAULT_KEY = "moku-credential-vault";
|
||||
const SALT_ITERATIONS = 200_000;
|
||||
const KEY_USAGE: KeyUsage[] = ["encrypt", "decrypt"];
|
||||
|
||||
export interface VaultPayload {
|
||||
refreshToken?: string;
|
||||
basicUser?: string;
|
||||
basicPass?: string;
|
||||
authMode: "UI_LOGIN" | "BASIC_AUTH" | "NONE";
|
||||
}
|
||||
|
||||
interface StoredVault {
|
||||
salt: string;
|
||||
iv: string;
|
||||
data: string;
|
||||
}
|
||||
|
||||
function toB64(buf: ArrayBuffer): string {
|
||||
return btoa(String.fromCharCode(...new Uint8Array(buf)));
|
||||
}
|
||||
|
||||
function fromB64(s: string): Uint8Array {
|
||||
return Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
||||
}
|
||||
|
||||
async function deriveKey(pin: string, salt: Uint8Array): Promise<CryptoKey> {
|
||||
const enc = new TextEncoder();
|
||||
const keyMat = await crypto.subtle.importKey("raw", enc.encode(pin), "PBKDF2", false, ["deriveKey"]);
|
||||
return crypto.subtle.deriveKey(
|
||||
{ name: "PBKDF2", salt, iterations: SALT_ITERATIONS, hash: "SHA-256" },
|
||||
keyMat,
|
||||
{ name: "AES-GCM", length: 256 },
|
||||
false,
|
||||
KEY_USAGE,
|
||||
);
|
||||
}
|
||||
|
||||
export function vaultExists(): boolean {
|
||||
return !!localStorage.getItem(VAULT_KEY);
|
||||
}
|
||||
|
||||
export async function lockVault(pin: string, payload: VaultPayload): Promise<void> {
|
||||
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const key = await deriveKey(pin, salt);
|
||||
|
||||
const enc = new TextEncoder();
|
||||
const cipher = await crypto.subtle.encrypt(
|
||||
{ name: "AES-GCM", iv },
|
||||
key,
|
||||
enc.encode(JSON.stringify(payload)),
|
||||
);
|
||||
|
||||
localStorage.setItem(VAULT_KEY, JSON.stringify({
|
||||
salt: toB64(salt),
|
||||
iv: toB64(iv),
|
||||
data: toB64(cipher),
|
||||
} satisfies StoredVault));
|
||||
}
|
||||
|
||||
export async function unlockVault(pin: string): Promise<VaultPayload | null> {
|
||||
const raw = localStorage.getItem(VAULT_KEY);
|
||||
if (!raw) return null;
|
||||
|
||||
try {
|
||||
const stored = JSON.parse(raw) as StoredVault;
|
||||
const key = await deriveKey(pin, fromB64(stored.salt));
|
||||
const plain = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: fromB64(stored.iv) },
|
||||
key,
|
||||
fromB64(stored.data),
|
||||
);
|
||||
return JSON.parse(new TextDecoder().decode(plain)) as VaultPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function clearVault(): void {
|
||||
localStorage.removeItem(VAULT_KEY);
|
||||
}
|
||||
|
||||
export async function rekeyVault(oldPin: string, newPin: string): Promise<boolean> {
|
||||
const payload = await unlockVault(oldPin);
|
||||
if (!payload) return false;
|
||||
await lockVault(newPin, payload);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { loadAllStores, persistSettings, persistLibrary, persistUpdates } from "./persist";
|
||||
export type { PersistedData } from "./persist";
|
||||
|
||||
export { vaultExists, lockVault, unlockVault, clearVault, rekeyVault } from "./credentialVault";
|
||||
export type { VaultPayload } from "./credentialVault";
|
||||
@@ -0,0 +1,166 @@
|
||||
import { LazyStore } from "@tauri-apps/plugin-store";
|
||||
|
||||
const settingsStore = new LazyStore("settings.json", { autoSave: false });
|
||||
const libraryStore = new LazyStore("library.json", { autoSave: false });
|
||||
const updatesStore = new LazyStore("updates.json", { autoSave: false });
|
||||
const backupsStore = new LazyStore("backups.json", { autoSave: false });
|
||||
|
||||
export interface PersistedData {
|
||||
settings: any;
|
||||
storeVersion: number | null;
|
||||
history: any[];
|
||||
bookmarks: any[];
|
||||
markers: any[];
|
||||
readLog: any[];
|
||||
readingStats: any | null;
|
||||
dailyReadCounts: Record<string, number>;
|
||||
libraryUpdates: any[];
|
||||
lastLibraryRefresh: number;
|
||||
acknowledgedUpdateIds: number[];
|
||||
}
|
||||
|
||||
export async function loadAllStores(): Promise<PersistedData> {
|
||||
const migrated = await migrateFromLocalStorage();
|
||||
if (migrated) return migrated;
|
||||
|
||||
const [sv, s, hist, bk, mk, rl, rs, dc, lu, llr, au] = await Promise.all([
|
||||
settingsStore.get<number>("storeVersion"),
|
||||
settingsStore.get<any>("settings"),
|
||||
libraryStore.get<any[]>("history"),
|
||||
libraryStore.get<any[]>("bookmarks"),
|
||||
libraryStore.get<any[]>("markers"),
|
||||
libraryStore.get<any[]>("readLog"),
|
||||
libraryStore.get<any>("readingStats"),
|
||||
libraryStore.get<Record<string, number>>("dailyReadCounts"),
|
||||
updatesStore.get<any[]>("libraryUpdates"),
|
||||
updatesStore.get<number>("lastLibraryRefresh"),
|
||||
updatesStore.get<number[]>("acknowledgedUpdateIds"),
|
||||
]);
|
||||
|
||||
return {
|
||||
storeVersion: sv ?? null,
|
||||
settings: s ?? null,
|
||||
history: hist ?? [],
|
||||
bookmarks: bk ?? [],
|
||||
markers: mk ?? [],
|
||||
readLog: rl ?? [],
|
||||
readingStats: rs ?? null,
|
||||
dailyReadCounts: dc ?? {},
|
||||
libraryUpdates: lu ?? [],
|
||||
lastLibraryRefresh: llr ?? 0,
|
||||
acknowledgedUpdateIds: au ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
async function migrateFromLocalStorage(): Promise<PersistedData | null> {
|
||||
try {
|
||||
const raw = localStorage.getItem("moku-store");
|
||||
if (!raw) return null;
|
||||
const data = JSON.parse(raw);
|
||||
|
||||
await Promise.all([
|
||||
persistSettings({ settings: data.settings ?? null, storeVersion: data.storeVersion ?? 1 }),
|
||||
persistLibrary({
|
||||
history: data.history ?? [],
|
||||
bookmarks: data.bookmarks ?? [],
|
||||
markers: data.markers ?? [],
|
||||
readLog: data.readLog ?? [],
|
||||
readingStats: data.readingStats ?? null,
|
||||
dailyReadCounts: data.dailyReadCounts ?? {},
|
||||
}),
|
||||
persistUpdates({
|
||||
libraryUpdates: data.libraryUpdates ?? [],
|
||||
lastLibraryRefresh: data.lastLibraryRefresh ?? 0,
|
||||
acknowledgedUpdateIds: data.acknowledgedUpdateIds ?? [],
|
||||
}),
|
||||
]);
|
||||
|
||||
localStorage.removeItem("moku-store");
|
||||
|
||||
return {
|
||||
storeVersion: data.storeVersion ?? null,
|
||||
settings: data.settings ?? null,
|
||||
history: data.history ?? [],
|
||||
bookmarks: data.bookmarks ?? [],
|
||||
markers: data.markers ?? [],
|
||||
readLog: data.readLog ?? [],
|
||||
readingStats: data.readingStats ?? null,
|
||||
dailyReadCounts: data.dailyReadCounts ?? {},
|
||||
libraryUpdates: data.libraryUpdates ?? [],
|
||||
lastLibraryRefresh: data.lastLibraryRefresh ?? 0,
|
||||
acknowledgedUpdateIds: data.acknowledgedUpdateIds ?? [],
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function persistSettings(data: { settings: any; storeVersion: number }) {
|
||||
await Promise.all([
|
||||
settingsStore.set("settings", data.settings),
|
||||
settingsStore.set("storeVersion", data.storeVersion),
|
||||
]);
|
||||
await settingsStore.save();
|
||||
}
|
||||
|
||||
export async function persistLibrary(data: {
|
||||
history: any[];
|
||||
bookmarks: any[];
|
||||
markers: any[];
|
||||
readLog: any[];
|
||||
readingStats: any;
|
||||
dailyReadCounts: Record<string, number>;
|
||||
}) {
|
||||
await Promise.all([
|
||||
libraryStore.set("history", data.history),
|
||||
libraryStore.set("bookmarks", data.bookmarks),
|
||||
libraryStore.set("markers", data.markers),
|
||||
libraryStore.set("readLog", data.readLog),
|
||||
libraryStore.set("readingStats", data.readingStats),
|
||||
libraryStore.set("dailyReadCounts", data.dailyReadCounts),
|
||||
]);
|
||||
await libraryStore.save();
|
||||
}
|
||||
|
||||
export async function persistUpdates(data: {
|
||||
libraryUpdates: any[];
|
||||
lastLibraryRefresh: number;
|
||||
acknowledgedUpdateIds: number[];
|
||||
}) {
|
||||
await Promise.all([
|
||||
updatesStore.set("libraryUpdates", data.libraryUpdates),
|
||||
updatesStore.set("lastLibraryRefresh", data.lastLibraryRefresh),
|
||||
updatesStore.set("acknowledgedUpdateIds", data.acknowledgedUpdateIds),
|
||||
]);
|
||||
await updatesStore.save();
|
||||
}
|
||||
|
||||
export interface BackupEntry { url: string; name: string; }
|
||||
|
||||
export async function loadBackups(): Promise<BackupEntry[]> {
|
||||
const fromStore = await backupsStore.get<BackupEntry[]>("backupList");
|
||||
if (fromStore) return fromStore;
|
||||
try {
|
||||
const raw = localStorage.getItem("moku_backups");
|
||||
if (!raw) return [];
|
||||
const migrated: BackupEntry[] = JSON.parse(raw);
|
||||
await persistBackups(migrated);
|
||||
localStorage.removeItem("moku_backups");
|
||||
return migrated;
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
export async function persistBackups(list: BackupEntry[]): Promise<void> {
|
||||
await backupsStore.set("backupList", list);
|
||||
await backupsStore.save();
|
||||
}
|
||||
|
||||
export async function resetAuthSettings(): Promise<void> {
|
||||
const current = await settingsStore.get<any>("settings") ?? {};
|
||||
current.serverAuthMode = "NONE";
|
||||
current.serverAuthUser = "";
|
||||
current.serverAuthPass = "";
|
||||
await settingsStore.set("settings", current);
|
||||
await settingsStore.save();
|
||||
localStorage.removeItem("moku-credential-vault");
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './idle';
|
||||
export * from './zoom';
|
||||
export * from './touchscreen';
|
||||
@@ -0,0 +1,234 @@
|
||||
export interface LongPressOptions {
|
||||
onLongPress: (e: PointerEvent) => void;
|
||||
duration?: number;
|
||||
moveThreshold?: number;
|
||||
}
|
||||
|
||||
export function longPress(node: HTMLElement, opts: LongPressOptions) {
|
||||
const { onLongPress, duration = 500, moveThreshold = 8 } = opts;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let startX = 0, startY = 0;
|
||||
let fired = false;
|
||||
|
||||
function start(e: PointerEvent) {
|
||||
if (e.button !== 0 && e.pointerType === "mouse") return;
|
||||
startX = e.clientX; startY = e.clientY; fired = false;
|
||||
timer = setTimeout(() => { timer = null; fired = true; onLongPress(e); }, duration);
|
||||
}
|
||||
function move(e: PointerEvent) {
|
||||
if (!timer) return;
|
||||
const dx = e.clientX - startX, dy = e.clientY - startY;
|
||||
if (Math.sqrt(dx * dx + dy * dy) > moveThreshold) cancel();
|
||||
}
|
||||
function cancel() { if (timer) { clearTimeout(timer); timer = null; } }
|
||||
|
||||
node.addEventListener("pointerdown", start);
|
||||
node.addEventListener("pointermove", move);
|
||||
node.addEventListener("pointerup", cancel);
|
||||
node.addEventListener("pointerleave", cancel);
|
||||
node.addEventListener("pointercancel",cancel);
|
||||
|
||||
return {
|
||||
get fired() { return fired; },
|
||||
destroy() {
|
||||
cancel();
|
||||
node.removeEventListener("pointerdown", start);
|
||||
node.removeEventListener("pointermove", move);
|
||||
node.removeEventListener("pointerup", cancel);
|
||||
node.removeEventListener("pointerleave", cancel);
|
||||
node.removeEventListener("pointercancel",cancel);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface TapOptions {
|
||||
onTap: (e: PointerEvent) => void;
|
||||
onDoubleTap?: (e: PointerEvent) => void;
|
||||
doubleTapGap?: number;
|
||||
}
|
||||
|
||||
export function tap(node: HTMLElement, opts: TapOptions) {
|
||||
const { onTap, onDoubleTap, doubleTapGap = 300 } = opts;
|
||||
let lastTap = 0;
|
||||
let pending: ReturnType<typeof setTimeout> | null = null;
|
||||
let startX = 0, startY = 0;
|
||||
const SLOP = 8;
|
||||
|
||||
function down(e: PointerEvent) { startX = e.clientX; startY = e.clientY; }
|
||||
function up(e: PointerEvent) {
|
||||
const dx = e.clientX - startX, dy = e.clientY - startY;
|
||||
if (Math.sqrt(dx * dx + dy * dy) > SLOP) return;
|
||||
const now = Date.now();
|
||||
if (onDoubleTap && now - lastTap < doubleTapGap) {
|
||||
if (pending) { clearTimeout(pending); pending = null; }
|
||||
onDoubleTap(e);
|
||||
lastTap = 0;
|
||||
} else {
|
||||
lastTap = now;
|
||||
if (onDoubleTap) {
|
||||
pending = setTimeout(() => { pending = null; onTap(e); }, doubleTapGap);
|
||||
} else {
|
||||
onTap(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
node.addEventListener("pointerdown", down);
|
||||
node.addEventListener("pointerup", up);
|
||||
return { destroy() {
|
||||
node.removeEventListener("pointerdown", down);
|
||||
node.removeEventListener("pointerup", up);
|
||||
}};
|
||||
}
|
||||
|
||||
export interface SwipeOptions {
|
||||
onSwipeLeft?: (e: PointerEvent) => void;
|
||||
onSwipeRight?: (e: PointerEvent) => void;
|
||||
onSwipeUp?: (e: PointerEvent) => void;
|
||||
onSwipeDown?: (e: PointerEvent) => void;
|
||||
threshold?: number;
|
||||
lockAxis?: boolean;
|
||||
}
|
||||
|
||||
export function swipe(node: HTMLElement, opts: SwipeOptions) {
|
||||
const { onSwipeLeft, onSwipeRight, onSwipeUp, onSwipeDown, threshold = 40, lockAxis = true } = opts;
|
||||
let startX = 0, startY = 0, active = false;
|
||||
|
||||
function down(e: PointerEvent) {
|
||||
if (e.pointerType === "mouse") return;
|
||||
startX = e.clientX; startY = e.clientY; active = true;
|
||||
node.setPointerCapture(e.pointerId);
|
||||
}
|
||||
function up(e: PointerEvent) {
|
||||
if (!active) return; active = false;
|
||||
const dx = e.clientX - startX, dy = e.clientY - startY;
|
||||
const ax = Math.abs(dx), ay = Math.abs(dy);
|
||||
if (Math.max(ax, ay) < threshold) return;
|
||||
if (lockAxis && ax > ay) {
|
||||
if (dx < 0) onSwipeLeft?.(e); else onSwipeRight?.(e);
|
||||
} else if (lockAxis && ay >= ax) {
|
||||
if (dy < 0) onSwipeUp?.(e); else onSwipeDown?.(e);
|
||||
} else {
|
||||
if (ax >= ay) { if (dx < 0) onSwipeLeft?.(e); else onSwipeRight?.(e); }
|
||||
else { if (dy < 0) onSwipeUp?.(e); else onSwipeDown?.(e); }
|
||||
}
|
||||
}
|
||||
function cancel() { active = false; }
|
||||
|
||||
node.addEventListener("pointerdown", down);
|
||||
node.addEventListener("pointerup", up);
|
||||
node.addEventListener("pointercancel", cancel);
|
||||
return { destroy() {
|
||||
node.removeEventListener("pointerdown", down);
|
||||
node.removeEventListener("pointerup", up);
|
||||
node.removeEventListener("pointercancel", cancel);
|
||||
}};
|
||||
}
|
||||
|
||||
export interface PinchOptions {
|
||||
onPinch: (scale: number, origin: { x: number; y: number }) => void;
|
||||
onPinchEnd?: (scale: number) => void;
|
||||
}
|
||||
|
||||
export interface PinchGestureOptions {
|
||||
onPinch: (scale: number, origin: { x: number; y: number }) => void;
|
||||
onPinchEnd?: (scale: number) => void;
|
||||
}
|
||||
|
||||
export interface PinchGesture {
|
||||
onPointerDown: (e: PointerEvent) => void;
|
||||
onPointerMove: (e: PointerEvent) => void;
|
||||
onPointerUp: (e: PointerEvent) => void;
|
||||
isPinching: () => boolean;
|
||||
}
|
||||
|
||||
export function createPinchGesture(opts: PinchGestureOptions): PinchGesture {
|
||||
const { onPinch, onPinchEnd } = opts;
|
||||
const pointers = new Map<number, PointerEvent>();
|
||||
let initDist = 0;
|
||||
|
||||
function pdist(a: PointerEvent, b: PointerEvent) {
|
||||
const dx = a.clientX - b.clientX, dy = a.clientY - b.clientY;
|
||||
return Math.sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
function pmid(a: PointerEvent, b: PointerEvent) {
|
||||
return { x: (a.clientX + b.clientX) / 2, y: (a.clientY + b.clientY) / 2 };
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
pointers.set(e.pointerId, e);
|
||||
if (pointers.size === 2) {
|
||||
const [a, b] = [...pointers.values()];
|
||||
initDist = pdist(a, b);
|
||||
}
|
||||
}
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (!pointers.has(e.pointerId)) return;
|
||||
pointers.set(e.pointerId, e);
|
||||
if (pointers.size !== 2 || initDist === 0) return;
|
||||
const [a, b] = [...pointers.values()];
|
||||
onPinch(pdist(a, b) / initDist, pmid(a, b));
|
||||
}
|
||||
function onPointerUp(e: PointerEvent) {
|
||||
if (pointers.size === 2 && onPinchEnd) {
|
||||
const [a, b] = [...pointers.values()];
|
||||
onPinchEnd(pdist(a, b) / initDist);
|
||||
}
|
||||
pointers.delete(e.pointerId);
|
||||
initDist = 0;
|
||||
}
|
||||
|
||||
return { onPointerDown, onPointerMove, onPointerUp, isPinching: () => pointers.size >= 2 };
|
||||
}
|
||||
|
||||
export function pinch(node: HTMLElement, opts: PinchOptions) {
|
||||
const gesture = createPinchGesture(opts);
|
||||
function down(e: PointerEvent) { node.setPointerCapture(e.pointerId); gesture.onPointerDown(e); }
|
||||
node.addEventListener("pointerdown", down);
|
||||
node.addEventListener("pointermove", gesture.onPointerMove);
|
||||
node.addEventListener("pointerup", gesture.onPointerUp);
|
||||
node.addEventListener("pointercancel", gesture.onPointerUp);
|
||||
return { destroy() {
|
||||
node.removeEventListener("pointerdown", down);
|
||||
node.removeEventListener("pointermove", gesture.onPointerMove);
|
||||
node.removeEventListener("pointerup", gesture.onPointerUp);
|
||||
node.removeEventListener("pointercancel", gesture.onPointerUp);
|
||||
}};
|
||||
}
|
||||
|
||||
export interface DragScrollOptions {
|
||||
direction?: "x" | "y" | "both";
|
||||
onDragStart?: () => void;
|
||||
onDragEnd?: () => void;
|
||||
}
|
||||
|
||||
export function dragScroll(node: HTMLElement, opts: DragScrollOptions = {}) {
|
||||
const { direction = "both", onDragStart, onDragEnd } = opts;
|
||||
let active = false, startX = 0, startY = 0, scrollX = 0, scrollY = 0;
|
||||
|
||||
function down(e: PointerEvent) {
|
||||
if (e.pointerType === "mouse") return;
|
||||
active = true;
|
||||
startX = e.clientX; startY = e.clientY;
|
||||
scrollX = node.scrollLeft; scrollY = node.scrollTop;
|
||||
node.setPointerCapture(e.pointerId);
|
||||
onDragStart?.();
|
||||
}
|
||||
function move(e: PointerEvent) {
|
||||
if (!active) return;
|
||||
if (direction !== "x") node.scrollTop = scrollY - (e.clientY - startY);
|
||||
if (direction !== "y") node.scrollLeft = scrollX - (e.clientX - startX);
|
||||
}
|
||||
function up() { if (active) { active = false; onDragEnd?.(); } }
|
||||
|
||||
node.addEventListener("pointerdown", down);
|
||||
node.addEventListener("pointermove", move);
|
||||
node.addEventListener("pointerup", up);
|
||||
node.addEventListener("pointercancel", up);
|
||||
return { destroy() {
|
||||
node.removeEventListener("pointerdown", down);
|
||||
node.removeEventListener("pointermove", move);
|
||||
node.removeEventListener("pointerup", up);
|
||||
node.removeEventListener("pointercancel", up);
|
||||
}};
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
import type { Manga, Source } from "@types";
|
||||
import type { Settings } from "@types";
|
||||
|
||||
// ── Class utility ─────────────────────────────────────────────────────────────
|
||||
import type { Settings } from "@types";
|
||||
|
||||
export { clsx as cn } from "clsx";
|
||||
|
||||
// ── Time / formatting ─────────────────────────────────────────────────────────
|
||||
|
||||
export function timeAgo(ts: number): string {
|
||||
const diff = Date.now() - ts, m = Math.floor(diff / 60000);
|
||||
if (m < 1) return "Just now";
|
||||
@@ -33,85 +29,95 @@ export function formatReadTime(m: number): string {
|
||||
return r === 0 ? `${h}h` : `${h}h ${r}m`;
|
||||
}
|
||||
|
||||
// ── NSFW filtering ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Default genre substrings used when no user-configured list is available.
|
||||
* Stored as settings.nsfwFilteredTags; editable in Settings > Content.
|
||||
*/
|
||||
export const DEFAULT_NSFW_TAGS = [
|
||||
"adult",
|
||||
"mature",
|
||||
"hentai",
|
||||
"ecchi",
|
||||
"erotic", // catches "erotica", "erotic content", "erotic manga"
|
||||
"pornograph", // catches "pornographic", "pornography"
|
||||
"18+",
|
||||
"smut",
|
||||
"lemon",
|
||||
"explicit",
|
||||
"sexual violence",
|
||||
const STRICT_TAGS: string[] = [
|
||||
"adult", "mature", "hentai", "ecchi", "erotic", "pornograph",
|
||||
"18+", "smut", "explicit", "sexual violence",
|
||||
"gore", "guro", "graphic violence", "torture", "body horror",
|
||||
];
|
||||
|
||||
/**
|
||||
* Returns true if the manga's genre list contains any of the given substrings.
|
||||
* Falls back to DEFAULT_NSFW_TAGS if no tag list is provided.
|
||||
*/
|
||||
export function isNsfwManga(
|
||||
manga: { genre?: string[] | null },
|
||||
tags: string[] = DEFAULT_NSFW_TAGS,
|
||||
): boolean {
|
||||
return (manga.genre ?? []).some(g =>
|
||||
tags.some(sub => g.toLowerCase().trim().includes(sub))
|
||||
);
|
||||
const MODERATE_TAGS: string[] = [
|
||||
"adult", "mature", "hentai", "ecchi", "erotic", "pornograph",
|
||||
"18+", "smut", "explicit", "sexual violence",
|
||||
];
|
||||
|
||||
type ContentFilterSettings = Pick<
|
||||
Settings,
|
||||
"contentLevel" | "sourceOverridesEnabled" | "nsfwAllowedSourceIds" | "nsfwBlockedSourceIds"
|
||||
>;
|
||||
|
||||
function blockedTagsForSettings(settings: ContentFilterSettings): string[] {
|
||||
if (settings.contentLevel === "strict") return STRICT_TAGS;
|
||||
if (settings.contentLevel === "moderate") return MODERATE_TAGS;
|
||||
return [];
|
||||
}
|
||||
|
||||
function genreMatchesBlocklist(genre: string[], blockedTags: string[]): boolean {
|
||||
if (!blockedTags.length) return false;
|
||||
return genre.some(g => {
|
||||
const norm = g.toLowerCase().trim();
|
||||
return blockedTags.some(tag => {
|
||||
const idx = norm.indexOf(tag);
|
||||
if (idx === -1) return false;
|
||||
const before = idx === 0 || /\W/.test(norm[idx - 1]);
|
||||
const after = idx + tag.length === norm.length || /\W/.test(norm[idx + tag.length]);
|
||||
return before && after;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Single authoritative NSFW gate used by all views.
|
||||
* Returns true when the manga should be HIDDEN. Priority order:
|
||||
* 1. Source in blockedSourceIds → always hidden, even when showNsfw is on.
|
||||
* 2. showNsfw globally enabled → only blocked sources are hidden.
|
||||
* 3. Source in allowedSourceIds → skip isNsfw flag, but genre tags still apply.
|
||||
* 4. source.isNsfw flag → hidden.
|
||||
* 5. Genre tag match → hidden.
|
||||
*
|
||||
* Usage: items.filter(m => !shouldHideNsfw(m, settings))
|
||||
*/
|
||||
export function shouldHideNsfw(
|
||||
manga: Pick<Manga, "genre" | "source">,
|
||||
settings: Pick<Settings, "showNsfw" | "nsfwFilteredTags" | "nsfwAllowedSourceIds" | "nsfwBlockedSourceIds">,
|
||||
settings: ContentFilterSettings,
|
||||
): boolean {
|
||||
const srcId = manga.source?.id;
|
||||
if (settings.contentLevel === "unrestricted") return false;
|
||||
|
||||
if (srcId && settings.nsfwBlockedSourceIds.includes(srcId)) return true;
|
||||
if (settings.showNsfw) return false;
|
||||
const srcId = manga.source?.id;
|
||||
const blocked = settings.sourceOverridesEnabled ? (settings.nsfwBlockedSourceIds ?? []) : [];
|
||||
const allowed = settings.sourceOverridesEnabled ? (settings.nsfwAllowedSourceIds ?? []) : [];
|
||||
|
||||
if (srcId && blocked.includes(srcId)) return true;
|
||||
|
||||
const sourceAllowed = !!(srcId && allowed.includes(srcId));
|
||||
|
||||
const sourceAllowed = !!(srcId && settings.nsfwAllowedSourceIds.includes(srcId));
|
||||
if (!sourceAllowed && manga.source?.isNsfw) return true;
|
||||
|
||||
return isNsfwManga(manga, settings.nsfwFilteredTags);
|
||||
return genreMatchesBlocklist(manga.genre ?? [], blockedTagsForSettings(settings));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate for Source objects — parallel to shouldHideNsfw for manga.
|
||||
* Usage: sources.filter(s => !shouldHideSource(s, settings))
|
||||
*/
|
||||
export function shouldHideSource(
|
||||
source: Pick<Source, "id" | "isNsfw">,
|
||||
settings: Pick<Settings, "showNsfw" | "nsfwAllowedSourceIds" | "nsfwBlockedSourceIds">,
|
||||
settings: ContentFilterSettings,
|
||||
): boolean {
|
||||
if (settings.nsfwBlockedSourceIds.includes(source.id)) return true;
|
||||
if (settings.nsfwAllowedSourceIds.includes(source.id)) return false;
|
||||
return !settings.showNsfw && source.isNsfw;
|
||||
if (settings.contentLevel === "unrestricted") return false;
|
||||
|
||||
if (settings.sourceOverridesEnabled) {
|
||||
if ((settings.nsfwBlockedSourceIds ?? []).includes(source.id)) return true;
|
||||
if ((settings.nsfwAllowedSourceIds ?? []).includes(source.id)) return false;
|
||||
}
|
||||
|
||||
return source.isNsfw;
|
||||
}
|
||||
|
||||
// ── Source deduplication ──────────────────────────────────────────────────────
|
||||
export function dedupeSourcesByLang(
|
||||
sources: Source[],
|
||||
preferredLang: string,
|
||||
settings: ContentFilterSettings,
|
||||
applyHide = false,
|
||||
): Source[] {
|
||||
const map = new Map<string, Source>();
|
||||
for (const s of sources) {
|
||||
if (s.id === "0") continue;
|
||||
if (applyHide && shouldHideSource(s, settings)) continue;
|
||||
const existing = map.get(s.name);
|
||||
if (!existing) { map.set(s.name, s); continue; }
|
||||
const existingPref = existing.lang === preferredLang;
|
||||
const newPref = s.lang === preferredLang;
|
||||
if (newPref && !existingPref) map.set(s.name, s);
|
||||
else if (!existingPref && !newPref && s.lang < existing.lang) map.set(s.name, s);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Deduplicates sources by name. When multiple sources share a name,
|
||||
* the preferred language wins; otherwise falls back to alphabetical by lang.
|
||||
* The local source (id "0") is always excluded.
|
||||
*/
|
||||
export function dedupeSources(sources: Source[], preferredLang: string): Source[] {
|
||||
const byName = new Map<string, Source[]>();
|
||||
for (const src of sources) {
|
||||
@@ -127,9 +133,6 @@ export function dedupeSources(sources: Source[], preferredLang: string): Source[
|
||||
return picked;
|
||||
}
|
||||
|
||||
// ── Manga deduplication ───────────────────────────────────────────────────────
|
||||
|
||||
/** Strips punctuation, articles, and source suffixes for fuzzy title matching. */
|
||||
export function normalizeTitle(title: string): string {
|
||||
return title
|
||||
.toLowerCase()
|
||||
@@ -140,39 +143,21 @@ export function normalizeTitle(title: string): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Strips all non-alphanumeric chars and collapses whitespace. */
|
||||
function norm(s: string): string {
|
||||
return s.toLowerCase().replace(/[^a-z0-9]/g, " ").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* First 200 normalized chars of a description — reliable cross-source fingerprint.
|
||||
* Returns null if too short (< 60 chars) to be a trustworthy signal.
|
||||
*/
|
||||
function descFingerprint(desc: string | null | undefined): string | null {
|
||||
if (!desc) return null;
|
||||
const n = norm(desc);
|
||||
return n.length >= 60 ? n.slice(0, 200) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized author + artist concatenation for tie-breaking.
|
||||
* Returns null if no author info available.
|
||||
*/
|
||||
function authorFingerprint(author?: string | null, artist?: string | null): string | null {
|
||||
const parts = [author, artist].filter(Boolean).map(s => norm(s!));
|
||||
return parts.length ? parts.sort().join("|") : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deduplicates manga across sources using title, description, and author signals,
|
||||
* plus explicit user-defined links (settings.mangaLinks).
|
||||
*
|
||||
* When two entries match, the better one is kept:
|
||||
* - Library membership wins over non-library.
|
||||
* - Otherwise higher downloadCount wins.
|
||||
* - Otherwise first occurrence wins.
|
||||
*/
|
||||
export function dedupeMangaByTitle<T extends {
|
||||
id: number;
|
||||
title: string;
|
||||
@@ -228,9 +213,6 @@ export function dedupeMangaByTitle<T extends {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lossless deduplication by ID only. Preserves first occurrence.
|
||||
*/
|
||||
export function dedupeMangaById<T extends { id: number }>(items: T[]): T[] {
|
||||
const seen = new Set<number>();
|
||||
const out: T[] = [];
|
||||
@@ -32,6 +32,4 @@
|
||||
|
||||
--dot-active: var(--accent);
|
||||
--dot-inactive: var(--text-faint);
|
||||
|
||||
--bg-image: none;
|
||||
}
|
||||
@@ -8,5 +8,6 @@
|
||||
--sp-8: 32px;
|
||||
--sp-10: 40px;
|
||||
|
||||
--sidebar-width: 52px;
|
||||
--sidebar-width: 52px;
|
||||
--titlebar-height: 36px;
|
||||
}
|
||||
+13
-6
@@ -5,8 +5,10 @@
|
||||
import { runConcurrent } from "@core/async/batchRequests";
|
||||
import { shouldHideNsfw, shouldHideSource, dedupeMangaById, dedupeMangaByTitle } from "@core/util";
|
||||
import { store } from "@store/state.svelte";
|
||||
import { preloadBlobUrls } from "@core/cache/imageCache";
|
||||
import Thumbnail from "@shared/manga/Thumbnail.svelte";
|
||||
import type { Manga, Source } from "@types";
|
||||
import type { CachedManga } from "@features/discover/lib/searchFilter";
|
||||
|
||||
interface Props {
|
||||
allSources: Source[];
|
||||
@@ -16,12 +18,14 @@
|
||||
pendingPrefill: string;
|
||||
popularResults: (Manga & { _priority: number })[];
|
||||
popularLoading: boolean;
|
||||
sourceCache: Map<number, CachedManga>;
|
||||
onPrefillConsumed: () => void;
|
||||
onPreview: (m: Manga) => void;
|
||||
}
|
||||
let {
|
||||
allSources, availableLangs, hasMultipleLangs, loadingSources,
|
||||
pendingPrefill, popularResults, popularLoading,
|
||||
sourceCache,
|
||||
onPrefillConsumed, onPreview,
|
||||
}: Props = $props();
|
||||
|
||||
@@ -72,7 +76,7 @@
|
||||
let filtered = allSources;
|
||||
if (kw_selectedLangs.size > 0)
|
||||
filtered = filtered.filter((s) => kw_selectedLangs.has(s.lang));
|
||||
if (!store.settings.showNsfw)
|
||||
if (store.settings.contentLevel !== "unrestricted")
|
||||
filtered = filtered.filter((s) => !shouldHideSource(s, store.settings));
|
||||
return filtered;
|
||||
}
|
||||
@@ -99,6 +103,10 @@
|
||||
);
|
||||
if (ctrl.signal.aborted) return;
|
||||
const mangas = d.fetchSourceManga.mangas.filter((m) => !shouldHideNsfw(m, store.settings));
|
||||
preloadBlobUrls(
|
||||
mangas.map((m) => sourceCache.get(m.id)?.thumbnailUrl ?? m.thumbnailUrl),
|
||||
12,
|
||||
);
|
||||
const next = [...kw_results];
|
||||
next[idx] = { ...next[idx], mangas, loading: false };
|
||||
kw_results = next;
|
||||
@@ -276,7 +284,6 @@
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
.keywordBar { padding: var(--sp-3) var(--sp-4) var(--sp-2); flex-shrink: 0; display: flex; flex-direction: column; gap: var(--sp-2); }
|
||||
.searchBar { display: flex; align-items: center; gap: var(--sp-2); background: var(--bg-raised); border: 1px solid var(--border-dim); border-radius: var(--radius-lg); padding: var(--sp-2) var(--sp-3); transition: border-color var(--t-base); }
|
||||
.searchBar:focus-within { border-color: var(--border-strong); }
|
||||
@@ -308,12 +315,12 @@
|
||||
|
||||
.srchCard { background: none; border: none; padding: 0; cursor: pointer; text-align: left; }
|
||||
.srchCard:hover .srchCoverWrap { filter: brightness(1.08) saturate(1.05); }
|
||||
.srchCoverWrap { position: relative; aspect-ratio: 2/3; overflow: hidden; border-radius: var(--radius-md); background: var(--bg-raised); border: 1px solid var(--border-dim); transform: translateZ(0); transition: filter var(--t-base); contain: layout style; }
|
||||
.srchGradient { position: absolute; inset: 0; background: linear-gradient(to top, rgba(0,0,0,0.82) 0%, rgba(0,0,0,0.15) 50%, transparent 72%); pointer-events: none; }
|
||||
.srchFooter { position: absolute; bottom: 0; left: 0; right: 0; padding: var(--sp-2); pointer-events: none; }
|
||||
.srchCoverWrap { position: relative; aspect-ratio: 2/3; overflow: hidden; border-radius: var(--radius-md); background: var(--bg-raised); border: 1px solid var(--border-dim); transform: translateZ(0); transition: filter var(--t-base); }
|
||||
.srchGradient { position: absolute; inset: 0; z-index: 1; background: linear-gradient(to top, rgba(0,0,0,0.82) 0%, rgba(0,0,0,0.15) 50%, transparent 72%); pointer-events: none; }
|
||||
.srchFooter { position: absolute; bottom: 0; left: 0; right: 0; z-index: 2; padding: var(--sp-2); pointer-events: none; }
|
||||
.srchTitle { font-size: var(--text-xs); font-weight: var(--weight-medium); color: rgba(255,255,255,0.92); line-height: var(--leading-snug); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-shadow: 0 1px 4px rgba(0,0,0,0.7); }
|
||||
.srchSource { font-family: var(--font-ui); font-size: 9px; color: rgba(255,255,255,0.45); letter-spacing: var(--tracking-wide); margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.inLibBadge { position: absolute; top: var(--sp-2); left: var(--sp-2); font-family: var(--font-ui); font-size: 9px; letter-spacing: var(--tracking-wide); background: var(--accent-muted); color: var(--accent-fg); border: 1px solid var(--accent-dim); border-radius: var(--radius-sm); padding: 1px 5px; }
|
||||
.inLibBadge { position: absolute; top: var(--sp-2); left: var(--sp-2); z-index: 2; font-family: var(--font-ui); font-size: 9px; letter-spacing: var(--tracking-wide); background: var(--accent-muted); color: var(--accent-fg); border: 1px solid var(--accent-dim); border-radius: var(--radius-sm); padding: 1px 5px; }
|
||||
|
||||
.skCard { display: flex; flex-direction: column; gap: var(--sp-2); flex-shrink: 0; width: 100%; }
|
||||
@keyframes shimmer { from { background-position: -200% 0 } to { background-position: 200% 0 } }
|
||||
+4
-1
@@ -8,7 +8,7 @@
|
||||
import { deprioritizeQueue } from "@core/cache/imageCache";
|
||||
import { dedupeSourcesByLang }from "@core/algorithms/filter";
|
||||
import { shouldHideNsfw } from "@core/util";
|
||||
import { store, setSearchPrefill, setPreviewManga } from "@store/state.svelte";
|
||||
import { store, setSearchPrefill, setPreviewManga, setSearchQuery } from "@store/state.svelte";
|
||||
import {
|
||||
toCachedManga,
|
||||
type CachedManga,
|
||||
@@ -287,6 +287,9 @@
|
||||
{pendingPrefill}
|
||||
popularResults={popular_results}
|
||||
popularLoading={popular_loading}
|
||||
{sourceCache}
|
||||
query={store.searchQuery}
|
||||
onQueryChange={setSearchQuery}
|
||||
onPrefillConsumed={() => (pendingPrefill = "")}
|
||||
onPreview={setPreviewManga}
|
||||
/>
|
||||
+1
-5
@@ -49,7 +49,6 @@ export interface CachedManga {
|
||||
genreEnriched: boolean;
|
||||
}
|
||||
|
||||
|
||||
export const COMMON_GENRES = [
|
||||
"Action", "Adventure", "Comedy", "Drama", "Fantasy", "Romance",
|
||||
"Sci-Fi", "Slice of Life", "Horror", "Mystery", "Thriller", "Sports",
|
||||
@@ -66,7 +65,6 @@ export const MANGA_STATUSES: { value: string; label: string }[] = [
|
||||
{ value: "UNKNOWN", label: "Unknown" },
|
||||
];
|
||||
|
||||
|
||||
export function buildTagFilter(
|
||||
tags: string[],
|
||||
mode: TagMode,
|
||||
@@ -90,13 +88,12 @@ export function buildTagFilter(
|
||||
return { and: [genrePart, statusPart] };
|
||||
}
|
||||
|
||||
|
||||
export function filterSourceCache(
|
||||
sourceCache: Map<number, CachedManga>,
|
||||
tags: string[],
|
||||
mode: TagMode,
|
||||
statuses: string[],
|
||||
settings: Pick<Settings, "showNsfw" | "nsfwFilteredTags" | "nsfwAllowedSourceIds" | "nsfwBlockedSourceIds">,
|
||||
settings: Pick<Settings, "contentLevel" | "sourceOverridesEnabled" | "nsfwAllowedSourceIds" | "nsfwBlockedSourceIds">,
|
||||
): CachedManga[] {
|
||||
return [...sourceCache.values()].filter((m) => {
|
||||
if (shouldHideNsfw(m as any, settings)) return false;
|
||||
@@ -118,7 +115,6 @@ export function filterSourceCache(
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export function toCachedManga(
|
||||
m: { id: number; title: string; thumbnailUrl: string; inLibrary: boolean; genre?: string[]; status?: string },
|
||||
srcId: string,
|
||||
+12
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { CircleNotch, ArrowClockwise, X } from "phosphor-svelte";
|
||||
import Thumbnail from "@shared/manga/Thumbnail.svelte";
|
||||
import { longPress } from "@core/ui/touchscreen";
|
||||
import type { DownloadQueueItem } from "@types/index";
|
||||
import { pageProgress } from "../lib/downloadQueue";
|
||||
|
||||
@@ -24,6 +25,12 @@
|
||||
const prog = $derived(pageProgress(item.progress, pages));
|
||||
const isError = $derived(item.state === "ERROR");
|
||||
const pct = $derived(Math.round(item.progress * 100));
|
||||
|
||||
function rowLongPress(node: HTMLElement) {
|
||||
return longPress(node, {
|
||||
onLongPress() { onSelect(item.chapter.id, { shiftKey: false, ctrlKey: true, metaKey: false } as MouseEvent); },
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
@@ -32,7 +39,12 @@
|
||||
class:row-error={isError}
|
||||
class:row-selected={isSelected}
|
||||
class:row-removing={isRemoving}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
tabindex="0"
|
||||
use:rowLongPress
|
||||
onclick={(e) => { e.stopPropagation(); onSelect(item.chapter.id, e); }}
|
||||
onkeydown={(e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); onSelect(item.chapter.id, e as unknown as MouseEvent); } }}
|
||||
>
|
||||
{#if manga?.thumbnailUrl}
|
||||
<div class="thumb">
|
||||
@@ -0,0 +1,98 @@
|
||||
<script lang="ts">
|
||||
import { CircleNotch } from "phosphor-svelte";
|
||||
import DownloadItem from "./DownloadItem.svelte";
|
||||
import type { DownloadQueueItem } from "@types/index";
|
||||
|
||||
interface Props {
|
||||
queue: DownloadQueueItem[];
|
||||
loading: boolean;
|
||||
isRunning: boolean;
|
||||
dequeueing: Set<number>;
|
||||
selected: Set<number>;
|
||||
onRemove: (chapterId: number) => void;
|
||||
onRetry: (chapterId: number) => void;
|
||||
onReorder: (chapterId: number, dir: "up" | "down") => void;
|
||||
onReorderEdge: (chapterId: number, edge: "top" | "bottom") => void;
|
||||
onSelect: (chapterId: number, e: MouseEvent) => void;
|
||||
}
|
||||
|
||||
const {
|
||||
queue, loading, isRunning, dequeueing, selected,
|
||||
onRemove, onRetry, onReorder, onReorderEdge, onSelect,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
{#if loading}
|
||||
<div class="list">
|
||||
{#each Array(5) as _, i (i)}
|
||||
<div class="sk-row">
|
||||
<div class="sk-thumb skeleton"></div>
|
||||
|
||||
<div class="sk-info">
|
||||
<div class="skeleton sk-title"></div>
|
||||
<div class="skeleton sk-chapter"></div>
|
||||
<div class="sk-progress-row">
|
||||
<div class="skeleton sk-bar"></div>
|
||||
<div class="skeleton sk-pages"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sk-right">
|
||||
<div class="skeleton sk-state"></div>
|
||||
<div class="sk-actions">
|
||||
<div class="skeleton sk-btn"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else if queue.length === 0}
|
||||
<div class="empty">Queue is empty.</div>
|
||||
{:else}
|
||||
<div class="list">
|
||||
{#each queue as item, i (item.chapter.id)}
|
||||
<DownloadItem
|
||||
{item}
|
||||
isActive={i === 0 && isRunning}
|
||||
isRemoving={dequeueing.has(item.chapter.id)}
|
||||
isSelected={selected.has(item.chapter.id)}
|
||||
{onRemove}
|
||||
{onRetry}
|
||||
{onReorder}
|
||||
{onReorderEdge}
|
||||
{onSelect}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.list { display: flex; flex-direction: column; gap: var(--sp-2); }
|
||||
.empty { display: flex; align-items: center; justify-content: center; height: 160px; color: var(--text-faint); font-family: var(--font-ui); font-size: var(--text-xs); letter-spacing: var(--tracking-wide); }
|
||||
|
||||
@keyframes shimmer { from { background-position: -200% 0 } to { background-position: 200% 0 } }
|
||||
.skeleton {
|
||||
border-radius: var(--radius-sm);
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
color-mix(in srgb, var(--bg-overlay, var(--bg-elevated)) 90%, var(--text-primary) 6%) 20%,
|
||||
color-mix(in srgb, var(--bg-elevated, var(--bg-overlay)) 76%, var(--text-primary) 16%) 50%,
|
||||
color-mix(in srgb, var(--bg-overlay, var(--bg-elevated)) 90%, var(--text-primary) 6%) 80%
|
||||
);
|
||||
background-size: 220% 100%;
|
||||
animation: shimmer 1.45s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.sk-row { display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3); background: var(--bg-raised); border: 1px solid var(--border-dim); border-radius: var(--radius-md); pointer-events: none; }
|
||||
.sk-thumb { width: 36px; height: 54px; flex-shrink: 0; }
|
||||
.sk-info { flex: 1; display: flex; flex-direction: column; gap: 5px; overflow: hidden; min-width: 0; }
|
||||
.sk-title { height: 12px; width: clamp(120px, 55%, 280px); }
|
||||
.sk-chapter { height: 10px; width: clamp(80px, 35%, 200px); }
|
||||
.sk-progress-row { display: flex; align-items: center; gap: var(--sp-2); }
|
||||
.sk-bar { flex: 1; height: 2px; }
|
||||
.sk-pages { width: 28px; height: 9px; }
|
||||
.sk-right { display: flex; flex-direction: column; align-items: flex-end; gap: var(--sp-1); flex-shrink: 0; }
|
||||
.sk-state { width: 54px; height: 9px; }
|
||||
.sk-actions { display: flex; gap: 2px; }
|
||||
.sk-btn { width: 20px; height: 20px; border-radius: var(--radius-sm); }
|
||||
</style>
|
||||
+5
-8
@@ -115,7 +115,7 @@
|
||||
</div>
|
||||
|
||||
<div class="bar-wrap">
|
||||
<div class="status-bar" onclick={handleClickOff} role="presentation">
|
||||
<div class="status-bar" role="none">
|
||||
<div class="status-dot" class:active={downloadStore.isRunning}></div>
|
||||
<span class="status-text">
|
||||
{downloadStore.togglingPlay
|
||||
@@ -127,7 +127,7 @@
|
||||
<button class="sel-action-btn" disabled={downloadStore.batchWorking} onclick={(e) => { e.stopPropagation(); downloadStore.reorderSelectedToEdge("top"); }} title="Move to top">
|
||||
<ArrowLineUp size={12} weight="bold" />
|
||||
</button>
|
||||
<div class="move-step" onclick={(e) => e.stopPropagation()} role="presentation">
|
||||
<div class="move-step" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()} role="none">
|
||||
<button class="sel-action-btn" disabled={downloadStore.batchWorking} onclick={(e) => { e.stopPropagation(); downloadStore.reorderSelected("up", moveBy); }} title="Move up">
|
||||
<CaretUp size={12} weight="bold" />
|
||||
</button>
|
||||
@@ -168,7 +168,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content" onclick={handleClickOff}>
|
||||
<div class="content" role="none" onclick={handleClickOff} onkeydown={(e) => e.key === 'Escape' && handleClickOff()}>
|
||||
<DownloadQueue
|
||||
queue={downloadStore.queue}
|
||||
loading={downloadStore.loading}
|
||||
@@ -204,9 +204,6 @@
|
||||
.sel-controls { display: flex; align-items: center; gap: var(--sp-2); }
|
||||
.status-bar { cursor: default; }
|
||||
.bar-sep { width: 1px; height: 12px; background: var(--border-dim); flex-shrink: 0; }
|
||||
.sel-count { font-family: var(--font-ui); font-size: var(--text-xs); color: var(--text-secondary); letter-spacing: var(--tracking-wide); white-space: nowrap; }
|
||||
.sel-text-btn { font-family: var(--font-ui); font-size: var(--text-xs); color: var(--text-faint); background: none; border: none; cursor: pointer; padding: 2px 4px; border-radius: var(--radius-sm); transition: color var(--t-base); white-space: nowrap; }
|
||||
.sel-text-btn:hover { color: var(--text-primary); }
|
||||
.sel-action-btn { display: flex; align-items: center; gap: 4px; font-family: var(--font-ui); font-size: var(--text-xs); padding: 3px 8px; border-radius: var(--radius-sm); border: 1px solid var(--border-dim); background: var(--bg-overlay); color: var(--text-muted); cursor: pointer; transition: color var(--t-base), border-color var(--t-base), background var(--t-base); white-space: nowrap; }
|
||||
.sel-action-btn:hover:not(:disabled) { color: var(--text-primary); border-color: var(--border-strong); }
|
||||
.sel-action-btn:disabled { opacity: 0.35; cursor: not-allowed; }
|
||||
@@ -214,8 +211,8 @@
|
||||
|
||||
.content { flex: 1; overflow-y: auto; padding: 0 var(--sp-6) var(--sp-6); display: flex; flex-direction: column; gap: var(--sp-4); }
|
||||
|
||||
.icon-btn { display: flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: var(--radius-md); border: 1px solid var(--border-dim); color: var(--text-muted); background: none; cursor: pointer; transition: color var(--t-base), border-color var(--t-base), background var(--t-base); }
|
||||
.icon-btn:hover:not(:disabled):not(.active) { color: var(--text-secondary); border-color: var(--border-strong); background: var(--bg-raised); }
|
||||
.icon-btn { display: flex; align-items: center; justify-content: center; width: 30px; height: 30px; border-radius: var(--radius-md); border: 1px solid var(--border-dim); background: var(--bg-raised); color: var(--text-faint); cursor: pointer; flex-shrink: 0; transition: color var(--t-base), border-color var(--t-base), background var(--t-base); }
|
||||
.icon-btn:hover:not(:disabled):not(.active) { color: var(--text-primary); border-color: var(--border-strong); }
|
||||
.icon-btn.active:hover:not(:disabled) { border-color: var(--accent); background: var(--accent-muted); }
|
||||
.icon-btn:disabled { opacity: 0.3; cursor: default; }
|
||||
.icon-btn.loading { border-color: var(--accent-dim); color: var(--accent-fg); background: var(--accent-muted); }
|
||||
+12
@@ -65,6 +65,18 @@ export function reorderSelectedToEdge(
|
||||
return edge === "top" ? [...pinned, ...rest] : [...rest, ...pinned];
|
||||
}
|
||||
|
||||
const AVG_BYTES_PER_PAGE = 1_500_000;
|
||||
|
||||
export function estimateQueueBytes(queue: DownloadQueueItem[]): number {
|
||||
let total = 0;
|
||||
for (const item of queue) {
|
||||
const pages = item.chapter.pageCount ?? 0;
|
||||
const remaining = pages - Math.round(item.progress * pages);
|
||||
total += remaining * AVG_BYTES_PER_PAGE;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
export function formatEta(seconds: number): string {
|
||||
if (seconds < 60) return `~${Math.ceil(seconds)}s`;
|
||||
if (seconds < 3600) return `~${Math.ceil(seconds / 60)}m`;
|
||||
+78
-11
@@ -5,14 +5,16 @@ import {
|
||||
DEQUEUE_DOWNLOAD, DEQUEUE_CHAPTERS_DOWNLOAD,
|
||||
ENQUEUE_DOWNLOAD, REORDER_DOWNLOAD,
|
||||
} from "@api/mutations";
|
||||
import { addToast, setActiveDownloads } from "@store/state.svelte";
|
||||
import { addToast, setActiveDownloads, store, updateSettings } from "@store/state.svelte";
|
||||
import { boot } from "@store/boot.svelte";
|
||||
import type { DownloadStatus, DownloadQueueItem } from "@types/index";
|
||||
import {
|
||||
toActiveDownloads, optimisticRemove, optimisticRemoveMany,
|
||||
isRunning, getErrored, calcSpeed, estimateEta,
|
||||
isRunning, getErrored, calcSpeed, estimateEta, estimateQueueBytes,
|
||||
type SpeedSample,
|
||||
} from "../lib/downloadQueue";
|
||||
import { startAutoRetry, type AutoRetryHandle } from "../lib/autoRetry";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
class DownloadStore {
|
||||
status: DownloadStatus | null = $state(null);
|
||||
@@ -22,11 +24,14 @@ class DownloadStore {
|
||||
dequeueing = $state(new Set<number>());
|
||||
selected = $state(new Set<number>());
|
||||
batchWorking = $state(false);
|
||||
pagesPerSec: number | null = $state(null);
|
||||
eta: number | null = $state(null);
|
||||
pagesPerSec: number | null = $state(null);
|
||||
eta: number | null = $state(null);
|
||||
storageWarning: boolean = $state(false);
|
||||
|
||||
toastsEnabled = $state(true);
|
||||
autoRetryEnabled = $state(false);
|
||||
private freeBytes: number | null = null;
|
||||
|
||||
get toastsEnabled() { return store.settings.downloadToastsEnabled ?? true; }
|
||||
get autoRetryEnabled() { return store.settings.downloadAutoRetry ?? false; }
|
||||
|
||||
private lastSample: SpeedSample | null = null;
|
||||
private prevQueue: DownloadQueueItem[] = [];
|
||||
@@ -38,18 +43,19 @@ class DownloadStore {
|
||||
get hasErrored() { return this.erroredIds.size > 0; }
|
||||
|
||||
toggleToasts() {
|
||||
this.toastsEnabled = !this.toastsEnabled;
|
||||
addToast({ kind: "info", title: this.toastsEnabled ? "Notifications enabled" : "Notifications muted", body: this.toastsEnabled ? "You'll be notified when chapters finish downloading" : "Download notifications are silenced", duration: 2500 });
|
||||
const next = !this.toastsEnabled;
|
||||
updateSettings({ downloadToastsEnabled: next });
|
||||
addToast({ kind: "info", title: next ? "Notifications enabled" : "Notifications muted", body: next ? "You'll be notified when chapters finish downloading" : "Download notifications are silenced", duration: 2500 });
|
||||
}
|
||||
|
||||
toggleAutoRetry() {
|
||||
if (this.autoRetryEnabled) {
|
||||
this.autoRetryHnd?.stop();
|
||||
this.autoRetryHnd = null;
|
||||
this.autoRetryEnabled = false;
|
||||
this.autoRetryHnd = null;
|
||||
updateSettings({ downloadAutoRetry: false });
|
||||
addToast({ kind: "info", title: "Auto-retry disabled", body: "Failed downloads will no longer retry automatically", duration: 2500 });
|
||||
} else {
|
||||
this.autoRetryEnabled = true;
|
||||
updateSettings({ downloadAutoRetry: true });
|
||||
this.autoRetryHnd = startAutoRetry(
|
||||
() => this.queue,
|
||||
() => this.isRunning,
|
||||
@@ -80,6 +86,52 @@ class DownloadStore {
|
||||
this.status = ds;
|
||||
setActiveDownloads(toActiveDownloads(ds.queue));
|
||||
this.updateSpeed(ds);
|
||||
this.fetchFreeBytes(ds);
|
||||
}
|
||||
|
||||
private async fetchFreeBytes(ds: DownloadStatus) {
|
||||
const path = store.settings.serverDownloadsPath ?? "";
|
||||
if (!path) return;
|
||||
try {
|
||||
const info = await invoke<{ free_bytes: number }>("get_storage_info", { downloadsPath: path });
|
||||
this.freeBytes = info.free_bytes;
|
||||
this.storageWarning = estimateQueueBytes(ds.queue) > info.free_bytes * 0.95;
|
||||
} catch { }
|
||||
}
|
||||
|
||||
private confirmStorageOverrun(): Promise<boolean> {
|
||||
return new Promise(resolve => {
|
||||
const backdrop = document.createElement("div");
|
||||
backdrop.style.cssText = "position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;animation:s-fade-in 0.15s ease both";
|
||||
const panel = document.createElement("div");
|
||||
panel.style.cssText = "background:var(--bg-surface);border:1px solid var(--border-base);border-radius:var(--radius-2xl);box-shadow:0 24px 80px rgba(0,0,0,0.7),0 0 0 1px rgba(255,255,255,0.04) inset;width:min(380px,calc(100vw - 40px));overflow:hidden;animation:s-scale-in 0.2s cubic-bezier(0.16,1,0.3,1) both";
|
||||
panel.innerHTML = `
|
||||
<div style="padding:var(--sp-4) var(--sp-5) var(--sp-3);border-bottom:1px solid var(--border-dim)">
|
||||
<p style="margin:0;font-size:var(--text-sm);font-weight:var(--weight-medium);color:var(--text-primary);letter-spacing:0.01em">Low disk space</p>
|
||||
</div>
|
||||
<div style="padding:var(--sp-4) var(--sp-5);display:flex;flex-direction:column;gap:var(--sp-2)">
|
||||
<p style="margin:0;font-family:var(--font-ui);font-size:var(--text-xs);color:var(--text-muted);letter-spacing:var(--tracking-wide);line-height:var(--leading-snug)">
|
||||
The download queue is estimated to exceed 95% of your available storage. Download anyway?
|
||||
</p>
|
||||
</div>
|
||||
<div style="padding:var(--sp-3) var(--sp-5);border-top:1px solid var(--border-dim);display:flex;justify-content:flex-end;gap:var(--sp-2)">
|
||||
<button id="_moku-storage-cancel" style="font-family:var(--font-ui);font-size:var(--text-xs);letter-spacing:var(--tracking-wide);padding:5px var(--sp-3);border-radius:var(--radius-sm);border:1px solid var(--border-dim);background:none;color:var(--text-muted);cursor:pointer">Cancel</button>
|
||||
<button id="_moku-storage-confirm" style="font-family:var(--font-ui);font-size:var(--text-xs);letter-spacing:var(--tracking-wide);padding:5px var(--sp-3);border-radius:var(--radius-sm);border:1px solid color-mix(in srgb,var(--color-error) 40%,transparent);background:color-mix(in srgb,var(--color-error) 10%,transparent);color:var(--color-error);cursor:pointer">Download anyway</button>
|
||||
</div>
|
||||
`;
|
||||
backdrop.appendChild(panel);
|
||||
document.body.appendChild(backdrop);
|
||||
function finish(result: boolean) { backdrop.remove(); resolve(result); }
|
||||
panel.querySelector("#_moku-storage-cancel")!.addEventListener("click", () => finish(false));
|
||||
panel.querySelector("#_moku-storage-confirm")!.addEventListener("click", () => finish(true));
|
||||
backdrop.addEventListener("click", (e) => { if (e.target === backdrop) finish(false); });
|
||||
});
|
||||
}
|
||||
|
||||
private async guardStorage(queueAfter: DownloadQueueItem[]): Promise<boolean> {
|
||||
if (this.freeBytes === null) return true;
|
||||
if (estimateQueueBytes(queueAfter) <= this.freeBytes * 0.95) return true;
|
||||
return this.confirmStorageOverrun();
|
||||
}
|
||||
|
||||
private updateSpeed(ds: DownloadStatus) {
|
||||
@@ -104,6 +156,7 @@ class DownloadStore {
|
||||
}
|
||||
|
||||
async poll() {
|
||||
if (boot.sessionExpired) return;
|
||||
gql<{ downloadStatus: DownloadStatus }>(GET_DOWNLOAD_STATUS)
|
||||
.then((d) => this.applyStatus(d.downloadStatus))
|
||||
.catch(console.error)
|
||||
@@ -169,11 +222,21 @@ class DownloadStore {
|
||||
finally { this.batchWorking = false; }
|
||||
}
|
||||
|
||||
async enqueue(chapterId: number): Promise<boolean> {
|
||||
const projected = [...this.queue, { chapter: { id: chapterId, pageCount: 0 }, progress: 0, state: "QUEUED" } as any];
|
||||
if (!(await this.guardStorage(projected))) return false;
|
||||
try { await gql(ENQUEUE_DOWNLOAD, { chapterId }); this.poll(); }
|
||||
catch (e) { console.error(e); }
|
||||
return true;
|
||||
}
|
||||
|
||||
async retryOne(chapterId: number) {
|
||||
if (this.dequeueing.has(chapterId)) return;
|
||||
this.dequeueing = new Set(this.dequeueing).add(chapterId);
|
||||
try {
|
||||
await gql(DEQUEUE_DOWNLOAD, { chapterId });
|
||||
const projected = this.queue.filter(i => i.chapter.id !== chapterId);
|
||||
if (!(await this.guardStorage(projected))) { this.poll(); return; }
|
||||
await gql(ENQUEUE_DOWNLOAD, { chapterId });
|
||||
this.poll();
|
||||
} catch (e) { console.error(e); this.poll(); }
|
||||
@@ -186,6 +249,8 @@ class DownloadStore {
|
||||
const ids = [...this.erroredIds];
|
||||
try {
|
||||
await gql(DEQUEUE_CHAPTERS_DOWNLOAD, { chapterIds: ids });
|
||||
const projected = this.queue.filter(i => !this.erroredIds.has(i.chapter.id));
|
||||
if (!(await this.guardStorage(projected))) { this.poll(); return; }
|
||||
for (const id of ids) await gql(ENQUEUE_DOWNLOAD, { chapterId: id });
|
||||
this.poll();
|
||||
addToast({ kind: "info", title: `Retrying ${ids.length} failed download${ids.length !== 1 ? "s" : ""}`, duration: 3000 });
|
||||
@@ -201,6 +266,8 @@ class DownloadStore {
|
||||
try {
|
||||
if (ids.length > 0) {
|
||||
await gql(DEQUEUE_CHAPTERS_DOWNLOAD, { chapterIds: ids });
|
||||
const projected = this.queue.filter(i => !new Set(ids).has(i.chapter.id));
|
||||
if (!(await this.guardStorage(projected))) { this.poll(); return; }
|
||||
for (const id of ids) await gql(ENQUEUE_DOWNLOAD, { chapterId: id });
|
||||
addToast({ kind: "info", title: `Retrying ${ids.length} failed download${ids.length !== 1 ? "s" : ""}`, duration: 3000 });
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user