Create Kaleido Desktop, a cinematic Plex client for Windows
Tauri 2 shell with a React/TypeScript interface and libmpv playback composed beneath the web view (DirectComposition on Windows). Shared code with per-OS platform modules and configs so macOS and Linux can follow. - Plex sign-in (browser, plex.tv/link or manual), server selection, Plex Home - Home, Movies and TV Shows (Discover, Library, Collections), search, people - Title pages with logos, ratings, cast, extras, seasons and episodes - Direct play with Plex conversion fallback, tracks, markers, autoplay - Metadata editing, artwork, fix match, refresh, analyze and deletion - Resumable offline downloads - App settings and Plex server administration with a live dashboard - Signed updater feed and Forgejo CI Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
70
.forgejo/workflows/release.yml
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
name: Validate and publish Kaleido Desktop
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
# Shared code: typecheck and unit tests for the interface, and a Linux
|
||||
# compile of the Rust core (keeps the cross-platform build honest).
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: node:22-bookworm
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- uses: https://data.forgejo.org/actions/checkout@v4.4.0
|
||||
- name: Interface
|
||||
run: |
|
||||
npm ci
|
||||
npm run typecheck
|
||||
npm test
|
||||
- name: Rust core (Linux)
|
||||
run: |
|
||||
set -eu
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends curl build-essential pkg-config libwebkit2gtk-4.1-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev libmpv-dev libdbus-1-dev
|
||||
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
|
||||
. "$HOME/.cargo/env"
|
||||
mkdir -p dist && cargo check --manifest-path src-tauri/Cargo.toml
|
||||
|
||||
# Signed installers per platform for version tags. Each OS needs a runner with
|
||||
# that label; jobs for platforms without a runner simply wait or can be removed.
|
||||
build:
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs: validate
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: windows
|
||||
runner: windows-latest
|
||||
# - os: macos
|
||||
# runner: macos-latest
|
||||
# - os: linux
|
||||
# runner: ubuntu-latest
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: https://data.forgejo.org/actions/checkout@v4.4.0
|
||||
- name: Build (Windows)
|
||||
if: matrix.os == 'windows'
|
||||
shell: pwsh
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
run: ./scripts/build.ps1
|
||||
- name: Build (macOS / Linux)
|
||||
if: matrix.os != 'windows'
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
run: |
|
||||
sh scripts/fetch-libmpv.sh
|
||||
npm ci
|
||||
npx tauri build
|
||||
- uses: https://data.forgejo.org/actions/upload-artifact@v4
|
||||
with:
|
||||
name: kaleido-${{ matrix.os }}
|
||||
path: src-tauri/target/release/bundle/
|
||||
14
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
node_modules/
|
||||
dist/
|
||||
src-tauri/target/
|
||||
src-tauri/gen/
|
||||
# Native libraries are fetched per OS by scripts/fetch-libmpv.*
|
||||
vendor/mpv/*/
|
||||
!vendor/mpv/README.md
|
||||
# Updater signing key (never commit)
|
||||
.tools/
|
||||
.env
|
||||
.env.*
|
||||
evidence/
|
||||
*.log
|
||||
.claude/
|
||||
27
AGENTS.md
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
# Kaleido Desktop
|
||||
|
||||
## Working rules
|
||||
|
||||
- This is a real desktop Plex client (Tauri 2 + React/TypeScript + libmpv), sibling of the
|
||||
Android TV app at git.elijahkuntz.com/Elijah/Kaleido. Preserve working Plex
|
||||
functionality; never substitute mock content or prototype playback.
|
||||
- Design for mouse and keyboard first. Keep Kaleido's artwork-led look (clear logos,
|
||||
backdrop fading into the page, UltraBlur colour wash, neutral near-black chrome) but
|
||||
don't port remote-control patterns that feel wrong with a pointer.
|
||||
- Keep the interface restrained: no redundant buttons or navigation.
|
||||
- `.env` (`PLEX_SERVER_URL`, `PLEX_TOKEN`) is for local testing only. Never print,
|
||||
commit or embed credentials. `.tools/updater.key` signs updates; never commit or
|
||||
replace it.
|
||||
- Shared code goes in `src/` and `src-tauri/src/`; anything OS-specific goes in
|
||||
`src-tauri/src/platform/<os>.rs` or `tauri.<os>.conf.json`.
|
||||
|
||||
## Testing
|
||||
|
||||
- `npm run typecheck`, `npm test`, `cargo check --manifest-path src-tauri/Cargo.toml`.
|
||||
- UI: `npm run dev` and a browser at http://localhost:1420 (signs in from `.env`).
|
||||
- Native: `npm run tauri dev` with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`;
|
||||
`window.__kaleido` exposes the stores in development.
|
||||
- Mute before playback tests (`__kaleido.useSettings.getState().set('volume', 0)`).
|
||||
Playback changes real Plex progress and track selections; restore them.
|
||||
|
||||
See `docs/architecture.md` and `docs/development.md`.
|
||||
92
README.md
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
# Kaleido for Desktop
|
||||
|
||||
A cinematic Plex client for the desktop, built in the same artwork-led style as
|
||||
[Kaleido for Android TV](https://git.elijahkuntz.com/Elijah/Kaleido), and designed for
|
||||
mouse and keyboard.
|
||||
|
||||
Windows is supported today. The repository is structured for Windows, macOS and Linux:
|
||||
the interface and nearly all of the native core are shared, and each platform's
|
||||
differences live in one place (see [Architecture](docs/architecture.md)).
|
||||
|
||||
## What's in the app
|
||||
|
||||
### Browse
|
||||
- **Home** features recently released, highly rated and recommended titles in a rotating
|
||||
cinematic hero, with Continue Watching and your server's shelves beneath it.
|
||||
- **Movies** and **TV Shows** each have **Discover**, **Library** and **Collections**.
|
||||
Discover leads with Continue Watching (Next Episodes for TV), new seasons, recent
|
||||
releases and Plex's recommendations. Library is the full catalog: a fast, virtualized
|
||||
poster grid with search, server-provided filters (genre, year, decade, content rating,
|
||||
resolution, HDR, Dolby Vision, Atmos, unwatched and more), every Plex sort, an A–Z jump
|
||||
rail and three poster sizes. If you have several libraries of a kind, pick which one
|
||||
each destination shows.
|
||||
- **Search** finds movies, shows, episodes, people and collections, with recent searches.
|
||||
- **Title pages** show clear-logo art over the title's backdrop with its colour wash,
|
||||
Rotten Tomatoes and IMDb scores, 4K/HDR/Atmos badges, cast and crew (select a person
|
||||
for their filmography in your library), trailers and extras, related titles and an
|
||||
About panel with credits and media details. Shows list their seasons and episodes.
|
||||
- Rest the pointer on a poster for a quick preview; right-click any title for actions.
|
||||
|
||||
### Watch
|
||||
- Playback uses **mpv**, so original files play directly — HEVC, AV1, Dolby Vision,
|
||||
TrueHD/Atmos, DTS-HD, PGS subtitles — with hardware decoding and HDR passthrough. Plex
|
||||
conversion (4K/1080p/720p/480p) is available per network type or from the player.
|
||||
- Audio and subtitle tracks, subtitle timing and size, speed, chapters and versions.
|
||||
- Server preview thumbnails on the timeline, Skip Intro/Credits (button or automatic),
|
||||
and a next-episode countdown.
|
||||
- Progress, watched state and Now Playing sync with your Plex server.
|
||||
|
||||
### Manage
|
||||
- Mark watched/unwatched, remove from Continue Watching, rate, add to collections and
|
||||
playlists, play from the beginning or pick a version.
|
||||
- For server owners: edit metadata (with field locks), change posters, backgrounds and
|
||||
logos, refresh metadata, analyze, fix match, unmatch, split apart and delete.
|
||||
|
||||
### Downloads
|
||||
- Download movies, episodes or whole seasons in original quality. Downloads pause,
|
||||
resume (including after restarting) and play offline; artwork is kept for offline
|
||||
browsing.
|
||||
|
||||
### Settings and server administration
|
||||
- App settings for account and server, playback, audio and subtitles, interface,
|
||||
downloads, keyboard shortcuts and updates.
|
||||
- Plex server settings: a live **dashboard** (streams with stop-stream, bandwidth, CPU
|
||||
and memory), activity and watch history, general, remote access, library, network,
|
||||
transcoder, extras, scheduled tasks and DLNA settings, **library management** (scan,
|
||||
refresh, analyze, empty trash, add/edit/delete with a server folder browser), devices,
|
||||
troubleshooting (logs, database, clean bundles, optimize) and a live console.
|
||||
Live TV/DVR and Plex's online catalog are intentionally not included.
|
||||
|
||||
## Keyboard
|
||||
|
||||
| Browsing | | Player | |
|
||||
| --- | --- | --- | --- |
|
||||
| Ctrl+K | Search | Space / K | Play/pause |
|
||||
| Arrow keys | Move between titles | ← / → | Seek (Shift: 1 min) |
|
||||
| Enter / Space | Open / play | ↑ / ↓, wheel | Volume |
|
||||
| Menu or Shift+F10 | Title actions | F, double-click | Full screen |
|
||||
| Alt+← / mouse back | Back | C | Next subtitle |
|
||||
| / | Focus search | Shift+N | Next episode |
|
||||
| F11 | Full screen | Esc | Exit full screen, then player |
|
||||
|
||||
## Build from source
|
||||
|
||||
Requirements: Node 22+, Rust (stable), and on Windows the Visual Studio C++ build tools
|
||||
and 7-Zip.
|
||||
|
||||
```powershell
|
||||
npm ci
|
||||
.\scripts\fetch-libmpv.ps1 # libmpv for Windows into vendor/mpv/windows
|
||||
npm run tauri dev # development app
|
||||
.\scripts\build.ps1 # signed release installer (NSIS)
|
||||
```
|
||||
|
||||
During development the app signs in automatically from an ignored `.env` in the
|
||||
repository root (`PLEX_SERVER_URL`, `PLEX_TOKEN`). Release builds never read it.
|
||||
`npm run dev` serves the interface alone in a browser for UI work (no playback or
|
||||
downloads). `npm test` runs unit tests; `npm run typecheck` checks types.
|
||||
|
||||
Releases and the update feed are described in [docs/development.md](docs/development.md).
|
||||
|
||||
Kaleido is an independent project and is not affiliated with Plex. Video playback uses
|
||||
libmpv (LGPL).
|
||||
72
docs/architecture.md
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
# Architecture
|
||||
|
||||
Kaleido Desktop is a [Tauri 2](https://tauri.app) application: a Rust core hosts the
|
||||
system web view (WebView2 on Windows, WKWebView on macOS, WebKitGTK on Linux), which runs
|
||||
the React/TypeScript interface. Video is decoded and rendered by libmpv and composed
|
||||
**beneath** the transparent web view, so the player's controls are ordinary interface
|
||||
elements drawn over the video — the same arrangement Plex HTPC and Jellyfin Media
|
||||
Player use.
|
||||
|
||||
```
|
||||
src/ Shared interface (all platforms)
|
||||
app/ Session, router, settings, queries, actions, shell, updater
|
||||
plex/ Plex client: account (plex.tv), library API, admin, playback, parsing
|
||||
player/ Playback controller (store.ts), mpv bridge, player overlay
|
||||
downloads/ Download catalog and actions
|
||||
screens/ Home, Movies/TV (Discover/Library/Collections), title pages,
|
||||
search, people, downloads, settings, dialogs
|
||||
ui/ Design system: primitives, menus/dialogs/toasts, cards, hero
|
||||
styles/ Tokens and styles (base, ui, app, screens, player)
|
||||
platform/native.ts The only module that talks to the host (Tauri or browser)
|
||||
src-tauri/ Shared Rust core
|
||||
src/mpv.rs Dynamically loaded libmpv binding (node ↔ JSON)
|
||||
src/player.rs One long-lived mpv instance, event stream to the interface
|
||||
src/downloads.rs Resumable downloads with a JSON catalog
|
||||
src/system.rs Credentials (OS keychain), paths, disk space, file saving
|
||||
src/platform/ Everything OS-specific (see below)
|
||||
tauri.conf.json Shared configuration (+ tauri.<os>.conf.json overrides)
|
||||
vendor/mpv/<os>/ libmpv per platform (fetched by scripts, ignored by git)
|
||||
scripts/ build, libmpv fetch, update-feed generation
|
||||
updates/latest.json Signed update feed for every platform
|
||||
```
|
||||
|
||||
## Platform boundary
|
||||
|
||||
`src-tauri/src/platform/mod.rs` selects one of `windows.rs`, `macos.rs` or `linux.rs`.
|
||||
Each exposes the same items:
|
||||
|
||||
| Item | Windows implementation |
|
||||
| --- | --- |
|
||||
| `VideoSurface` | mpv renders with `d3d11-output-mode=composition`; its swapchain (`display-swapchain`) is set as the content of a DirectComposition visual targeted at the window with `topmost = false`, i.e. behind the web view's child windows. |
|
||||
| `MPV_LIBRARIES` | `libmpv-2.dll` |
|
||||
| `hold_awake` | `SetThreadExecutionState` while video plays |
|
||||
|
||||
macOS and Linux currently provide stubs for `VideoSurface` (browsing, downloads,
|
||||
settings and updates work; playback reports that it is unavailable). To add playback
|
||||
there, render through mpv's render API into a layer beneath the web view and implement
|
||||
the same five methods. Per-OS bundling (libmpv, targets, dependencies) lives in
|
||||
`tauri.macos.conf.json` and `tauri.linux.conf.json`. Credentials use the platform's
|
||||
keychain through the `keyring` crate with per-OS features in `Cargo.toml`.
|
||||
|
||||
On Windows the main window is created transparent and the page background turns
|
||||
transparent only while video is visible (`html.video-active`), so browsing is opaque.
|
||||
|
||||
## Interface
|
||||
|
||||
- **State**: zustand stores for the session (`app/session.ts`), navigation history
|
||||
(`app/router.ts`, with scroll and per-screen state restored on Back), preferences
|
||||
(`app/settings.ts`, persisted) and the player (`player/store.ts`). Server data goes
|
||||
through TanStack Query; every key starts with the server's machine identifier.
|
||||
- **Plex HTTP** goes through the host's native HTTP client (`@tauri-apps/plugin-http`),
|
||||
avoiding CORS and local-network restrictions. Artwork uses Plex's photo transcoder,
|
||||
sized for the display's pixel ratio (PNG for transparent clear logos).
|
||||
- **Library sync**: the section list is polled every 20 seconds; a change refreshes
|
||||
browsing caches.
|
||||
- **Playback** (`player/store.ts`): Original quality plays the part URL directly (multi
|
||||
part titles are joined with an mpv EDL); other qualities request Plex HLS with
|
||||
timestamps kept absolute. If direct play fails, playback retries through Plex once.
|
||||
Plex streams are matched to mpv tracks by stream index; external subtitles are added
|
||||
on demand. Timeline reports every 10 seconds make the session appear in Plex, and the
|
||||
title is marked watched at the configured percentage.
|
||||
- **Updates**: `app/updater.ts` checks the signed feed on start; installs need the
|
||||
user's confirmation and then relaunch.
|
||||
50
docs/development.md
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
# Development
|
||||
|
||||
## Setup (Windows)
|
||||
|
||||
1. Node 22+, Rust stable (MSVC), Visual Studio C++ build tools, 7-Zip.
|
||||
2. `npm ci`
|
||||
3. `.\scripts\fetch-libmpv.ps1` downloads the shinchiro `mpv-dev-x86_64` build (the
|
||||
Windows libmpv builds linked from mpv.io) into `vendor/mpv/windows`.
|
||||
4. Put a `.env` in the repository root for the development sign-in:
|
||||
`PLEX_SERVER_URL=...` and `PLEX_TOKEN=...`. It is ignored by git and only read by
|
||||
debug builds and the Vite dev server. Never commit or print it.
|
||||
5. `npm run tauri dev`
|
||||
|
||||
The interface alone runs in a browser with `npm run dev` (port 1420), which is handy for
|
||||
layout work; playback, downloads and native dialogs need the desktop app. In development
|
||||
builds the stores are available as `window.__kaleido` for debugging.
|
||||
|
||||
To drive the desktop app from scripts, start it with
|
||||
`WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333` and attach over the
|
||||
Chrome DevTools Protocol.
|
||||
|
||||
## Checks
|
||||
|
||||
```powershell
|
||||
npm run typecheck
|
||||
npm test
|
||||
cargo check --manifest-path src-tauri/Cargo.toml
|
||||
```
|
||||
|
||||
Playback tests change real Plex progress; resume an in-progress title near its saved
|
||||
position, or restore it afterwards. Selecting audio or subtitle tracks is saved to Plex
|
||||
for that file.
|
||||
|
||||
## Releases
|
||||
|
||||
1. Bump the version in `package.json`, `src-tauri/Cargo.toml` and
|
||||
`src-tauri/tauri.conf.json`.
|
||||
2. `.\scripts\build.ps1` builds the NSIS installer and its signed updater artifact. The
|
||||
updater key is read from `.tools/updater.key` (ignored; keep it safe — replacing it
|
||||
breaks in-app updates for existing installs) or from `TAURI_SIGNING_PRIVATE_KEY`.
|
||||
3. Create the release (tag `vX.Y.Z`) and upload the files from
|
||||
`src-tauri/target/release/bundle/nsis/`.
|
||||
4. `node scripts/update-manifest.mjs X.Y.Z https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/vX.Y.Z notes.md`
|
||||
and commit `updates/latest.json`. Installed copies offer the update on their next
|
||||
start.
|
||||
|
||||
For macOS and Linux, build on those systems (`scripts/fetch-libmpv.sh`, then
|
||||
`npx tauri build`) and merge their bundles into the same feed with `KALEIDO_BUNDLES`.
|
||||
CI (`.forgejo/workflows/release.yml`) validates every push and builds installers for
|
||||
tags on runners for each enabled platform.
|
||||
12
index.html
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Kaleido</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
1584
package-lock.json
generated
Normal file
37
package.json
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
{
|
||||
"name": "kaleido-desktop",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@tanstack/react-query": "^5.105.0",
|
||||
"@tanstack/react-virtual": "^3.14.24",
|
||||
"@tauri-apps/api": "^2.12.4",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.4",
|
||||
"@tauri-apps/plugin-http": "^2.8.3",
|
||||
"@tauri-apps/plugin-opener": "^2.7.2",
|
||||
"@tauri-apps/plugin-process": "^2.4.0",
|
||||
"@tauri-apps/plugin-updater": "^2.14.1",
|
||||
"@tauri-apps/plugin-window-state": "^2.5.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"zustand": "^5.0.16"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.12.4",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"typescript": "~5.9",
|
||||
"vite": "^8.3.5",
|
||||
"vitest": "^5.0.5"
|
||||
}
|
||||
}
|
||||
30
scripts/build.ps1
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Builds Kaleido for Windows: the NSIS installer plus signed updater artifacts.
|
||||
# .\scripts\build.ps1 # release installer
|
||||
# .\scripts\build.ps1 -Debug # faster unoptimized build
|
||||
param([switch]$Debug)
|
||||
$ErrorActionPreference = "Stop"
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
|
||||
& "$PSScriptRoot\fetch-libmpv.ps1"
|
||||
|
||||
# The updater signing key stays outside git (.tools/). CI provides it as a secret.
|
||||
if (-not $env:TAURI_SIGNING_PRIVATE_KEY) {
|
||||
$keyFile = Join-Path $root ".tools\updater.key"
|
||||
if (Test-Path $keyFile) {
|
||||
$env:TAURI_SIGNING_PRIVATE_KEY = Get-Content $keyFile -Raw
|
||||
if (-not $env:TAURI_SIGNING_PRIVATE_KEY_PASSWORD) { $env:TAURI_SIGNING_PRIVATE_KEY_PASSWORD = "" }
|
||||
} else {
|
||||
Write-Warning "No updater signing key; building without update artifacts."
|
||||
$env:TAURI_CONFIG = '{"bundle":{"createUpdaterArtifacts":false}}'
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Test-Path (Join-Path $root "node_modules"))) { npm ci }
|
||||
$buildArgs = @("tauri", "build")
|
||||
if ($Debug) { $buildArgs += "--debug" }
|
||||
npx @buildArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Build failed" }
|
||||
|
||||
$profile = if ($Debug) { "debug" } else { "release" }
|
||||
Get-ChildItem (Join-Path $root "src-tauri\target\$profile\bundle\nsis") | Select-Object Name, Length
|
||||
15
scripts/fetch-libmpv.ps1
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Downloads libmpv for Windows into vendor/mpv/windows.
|
||||
# Source: https://github.com/shinchiro/mpv-winbuild-cmake (the builds linked from mpv.io).
|
||||
param([string]$Tag = "20261021", [string]$Build = "mpv-dev-x86_64-20261021-git-e471496c56")
|
||||
$ErrorActionPreference = "Stop"
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
$dest = Join-Path $root "vendor\mpv\windows"
|
||||
if (Test-Path (Join-Path $dest "libmpv-2.dll")) { Write-Host "libmpv already present in $dest"; exit 0 }
|
||||
$tmp = Join-Path ([IO.Path]::GetTempPath()) ("kaleido-mpv-" + [guid]::NewGuid())
|
||||
New-Item -ItemType Directory -Force $tmp, $dest | Out-Null
|
||||
$archive = Join-Path $tmp "mpv-dev.7z"
|
||||
Invoke-WebRequest "https://github.com/shinchiro/mpv-winbuild-cmake/releases/download/$Tag/$Build.7z" -OutFile $archive
|
||||
& 7z x $archive "-o$tmp\x" -y | Out-Null
|
||||
Copy-Item "$tmp\x\libmpv-2.dll" $dest
|
||||
Remove-Item -Recurse -Force $tmp
|
||||
Write-Host "libmpv installed to $dest"
|
||||
15
scripts/fetch-libmpv.sh
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
#!/usr/bin/env sh
|
||||
# macOS: copies Homebrew's libmpv into vendor/mpv/macos for bundling.
|
||||
# Linux: libmpv comes from the system package (libmpv2); nothing to copy.
|
||||
set -eu
|
||||
root=$(cd "$(dirname "$0")/.." && pwd)
|
||||
case "$(uname -s)" in
|
||||
Darwin)
|
||||
brew list mpv >/dev/null 2>&1 || brew install mpv
|
||||
mkdir -p "$root/vendor/mpv/macos"
|
||||
cp "$(brew --prefix mpv)/lib/libmpv.2.dylib" "$root/vendor/mpv/macos/"
|
||||
echo "libmpv copied to vendor/mpv/macos" ;;
|
||||
Linux)
|
||||
echo "Install libmpv from your distribution (e.g. apt install libmpv2 libmpv-dev)." ;;
|
||||
*) echo "Use scripts/fetch-libmpv.ps1 on Windows." ;;
|
||||
esac
|
||||
47
scripts/update-manifest.mjs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// Writes updates/latest.json, the feed Kaleido's updater reads, from built bundles.
|
||||
// Usage: node scripts/update-manifest.mjs <version> <baseDownloadUrl> [notesFile]
|
||||
// Each platform's signed artifact (and its .sig) must be in src-tauri/target/release/bundle,
|
||||
// or pass several bundle folders via KALEIDO_BUNDLES (path;path) when collecting CI outputs.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const [version, baseUrl, notesFile] = process.argv.slice(2);
|
||||
if (!version || !baseUrl) {
|
||||
console.error('usage: node scripts/update-manifest.mjs <version> <baseDownloadUrl> [notesFile]');
|
||||
process.exit(1);
|
||||
}
|
||||
const root = path.resolve(import.meta.dirname, '..');
|
||||
const bundles = (process.env.KALEIDO_BUNDLES ?? path.join(root, 'src-tauri/target/release/bundle')).split(';');
|
||||
|
||||
/** Tauri updater platform keys and the artifact each one installs. */
|
||||
const PLATFORMS = [
|
||||
{ key: 'windows-x86_64', dir: 'nsis', match: /-setup\.exe$/ },
|
||||
{ key: 'darwin-aarch64', dir: 'macos', match: /aarch64.*\.app\.tar\.gz$/ },
|
||||
{ key: 'darwin-x86_64', dir: 'macos', match: /x64.*\.app\.tar\.gz$/ },
|
||||
{ key: 'linux-x86_64', dir: 'appimage', match: /\.AppImage$/ },
|
||||
];
|
||||
|
||||
const manifestPath = path.join(root, 'updates/latest.json');
|
||||
const manifest = fs.existsSync(manifestPath) ? JSON.parse(fs.readFileSync(manifestPath, 'utf8')) : { platforms: {} };
|
||||
manifest.version = version;
|
||||
manifest.notes = notesFile ? fs.readFileSync(notesFile, 'utf8').trim() : manifest.notes ?? '';
|
||||
manifest.pub_date = new Date().toISOString();
|
||||
manifest.platforms ??= {};
|
||||
|
||||
for (const bundle of bundles) {
|
||||
for (const p of PLATFORMS) {
|
||||
const dir = path.join(bundle, p.dir);
|
||||
if (!fs.existsSync(dir)) continue;
|
||||
const file = fs.readdirSync(dir).find((f) => p.match.test(f) && f.includes(version));
|
||||
if (!file || !fs.existsSync(path.join(dir, `${file}.sig`))) continue;
|
||||
manifest.platforms[p.key] = {
|
||||
signature: fs.readFileSync(path.join(dir, `${file}.sig`), 'utf8').trim(),
|
||||
url: `${baseUrl.replace(/\/$/, '')}/${encodeURIComponent(file)}`,
|
||||
};
|
||||
console.log(`${p.key}: ${file}`);
|
||||
}
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
|
||||
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
||||
console.log(`Wrote ${path.relative(root, manifestPath)}`);
|
||||
6368
src-tauri/Cargo.lock
generated
Normal file
63
src-tauri/Cargo.toml
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
[package]
|
||||
name = "kaleido"
|
||||
version = "0.1.0"
|
||||
description = "Kaleido — a Plex client for Windows"
|
||||
authors = ["Elijah"]
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "kaleido_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = ["protocol-asset"] }
|
||||
tauri-plugin-http = "2"
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-window-state = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
tauri-plugin-process = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
libloading = "0.8"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "io-util", "sync", "time"] }
|
||||
reqwest = { version = "0.12", default-features = false, features = ["stream", "rustls-tls", "json"] }
|
||||
futures-util = "0.3"
|
||||
fs2 = "0.4"
|
||||
parking_lot = "0.12"
|
||||
once_cell = "1"
|
||||
log = "0.4"
|
||||
|
||||
# Credentials use each OS's native store: Credential Manager, Keychain, Secret Service.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
keyring = { version = "3", features = ["apple-native"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
keyring = { version = "3", features = ["sync-secret-service", "crypto-rust"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
keyring = { version = "3", features = ["windows-native"] }
|
||||
windows = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_System_Power",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_Graphics_DirectComposition",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D11",
|
||||
"Foundation_Numerics",
|
||||
] }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
opt-level = 3
|
||||
strip = true
|
||||
3
src-tauri/build.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
47
src-tauri/capabilities/default.json
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Kaleido main window",
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-unmaximize",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-fullscreen",
|
||||
"core:window:allow-is-fullscreen",
|
||||
"core:window:allow-is-maximized",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"dialog:default",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"window-state:default",
|
||||
{
|
||||
"identifier": "http:default",
|
||||
"allow": [
|
||||
{
|
||||
"url": "https://*"
|
||||
},
|
||||
{
|
||||
"url": "http://*"
|
||||
},
|
||||
{
|
||||
"url": "https://*:*"
|
||||
},
|
||||
{
|
||||
"url": "http://*:*"
|
||||
}
|
||||
]
|
||||
},
|
||||
"updater:default",
|
||||
"process:allow-restart"
|
||||
]
|
||||
}
|
||||
BIN
src-tauri/icons/128x128.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
src-tauri/icons/128x128@2x.png
Normal file
|
After Width: | Height: | Size: 30 KiB |
BIN
src-tauri/icons/32x32.png
Normal file
|
After Width: | Height: | Size: 1.8 KiB |
BIN
src-tauri/icons/64x64.png
Normal file
|
After Width: | Height: | Size: 4.7 KiB |
BIN
src-tauri/icons/Square107x107Logo.png
Normal file
|
After Width: | Height: | Size: 9.9 KiB |
BIN
src-tauri/icons/Square142x142Logo.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
src-tauri/icons/Square150x150Logo.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
src-tauri/icons/Square284x284Logo.png
Normal file
|
After Width: | Height: | Size: 33 KiB |
BIN
src-tauri/icons/Square30x30Logo.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
src-tauri/icons/Square310x310Logo.png
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
src-tauri/icons/Square44x44Logo.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
src-tauri/icons/Square71x71Logo.png
Normal file
|
After Width: | Height: | Size: 5.5 KiB |
BIN
src-tauri/icons/Square89x89Logo.png
Normal file
|
After Width: | Height: | Size: 7.6 KiB |
BIN
src-tauri/icons/StoreLogo.png
Normal file
|
After Width: | Height: | Size: 3.3 KiB |
BIN
src-tauri/icons/app-icon.png
Normal file
|
After Width: | Height: | Size: 153 KiB |
BIN
src-tauri/icons/icon.icns
Normal file
BIN
src-tauri/icons/icon.ico
Normal file
|
After Width: | Height: | Size: 43 KiB |
BIN
src-tauri/icons/icon.png
Normal file
|
After Width: | Height: | Size: 67 KiB |
428
src-tauri/src/downloads.rs
Normal file
|
|
@ -0,0 +1,428 @@
|
|||
//! Offline downloads: resumable HTTP transfers of Plex media parts with a small
|
||||
//! JSON catalog, so downloaded titles stay browsable and playable offline.
|
||||
//!
|
||||
//! URLs carrying Plex tokens are only held in memory. The catalog stores the
|
||||
//! server-relative source path; resuming after a restart asks the interface for
|
||||
//! a freshly signed URL.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use tauri::{AppHandle, Emitter, Manager, Runtime};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::sync::{watch, Semaphore};
|
||||
|
||||
const MAX_ACTIVE: usize = 2;
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Status {
|
||||
Queued,
|
||||
Downloading,
|
||||
Paused,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Item {
|
||||
pub id: String,
|
||||
pub file_path: String,
|
||||
pub total: u64,
|
||||
pub received: u64,
|
||||
pub status: Status,
|
||||
#[serde(default)]
|
||||
pub error: Option<String>,
|
||||
#[serde(default)]
|
||||
pub meta: Value,
|
||||
pub created_at: u64,
|
||||
#[serde(default)]
|
||||
pub speed: u64,
|
||||
}
|
||||
|
||||
pub struct Downloads {
|
||||
items: Mutex<Vec<Item>>,
|
||||
dir: Mutex<Option<PathBuf>>,
|
||||
cancels: Mutex<HashMap<String, watch::Sender<bool>>>,
|
||||
permits: Arc<Semaphore>,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
impl Default for Downloads {
|
||||
fn default() -> Self {
|
||||
Downloads {
|
||||
items: Mutex::new(Vec::new()),
|
||||
dir: Mutex::new(None),
|
||||
cancels: Mutex::new(HashMap::new()),
|
||||
permits: Arc::new(Semaphore::new(MAX_ACTIVE)),
|
||||
client: reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_secs(20))
|
||||
.user_agent("Kaleido")
|
||||
.build()
|
||||
.expect("http client"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn catalog_path<R: Runtime>(app: &AppHandle<R>) -> PathBuf {
|
||||
crate::system::data_dir(app).join("downloads.json")
|
||||
}
|
||||
|
||||
fn save<R: Runtime>(app: &AppHandle<R>) {
|
||||
let state = app.state::<Downloads>();
|
||||
let items = state.items.lock().clone();
|
||||
let path = catalog_path(app);
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
if let Ok(text) = serde_json::to_string_pretty(&items) {
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
if std::fs::write(&tmp, text).is_ok() {
|
||||
let _ = std::fs::rename(tmp, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the catalog at startup. Interrupted transfers become paused: their
|
||||
/// signed URLs were never persisted.
|
||||
pub fn restore<R: Runtime>(app: &AppHandle<R>) {
|
||||
let Ok(text) = std::fs::read_to_string(catalog_path(app)) else { return };
|
||||
let Ok(mut items) = serde_json::from_str::<Vec<Item>>(&text) else { return };
|
||||
for item in items.iter_mut() {
|
||||
if matches!(item.status, Status::Downloading | Status::Queued) {
|
||||
// Marked so the interface resumes it once it has a signed URL again.
|
||||
item.status = Status::Paused;
|
||||
item.error = Some("interrupted".into());
|
||||
}
|
||||
if item.status == Status::Completed && !Path::new(&item.file_path).exists() {
|
||||
item.status = Status::Failed;
|
||||
item.error = Some("The downloaded file is missing.".into());
|
||||
}
|
||||
item.speed = 0;
|
||||
}
|
||||
*app.state::<Downloads>().items.lock() = items;
|
||||
}
|
||||
|
||||
fn update<R: Runtime>(app: &AppHandle<R>, id: &str, f: impl FnOnce(&mut Item)) -> Option<Item> {
|
||||
let state = app.state::<Downloads>();
|
||||
let mut items = state.items.lock();
|
||||
let item = items.iter_mut().find(|i| i.id == id)?;
|
||||
f(item);
|
||||
let snapshot = item.clone();
|
||||
drop(items);
|
||||
let _ = app.emit("download", &snapshot);
|
||||
Some(snapshot)
|
||||
}
|
||||
|
||||
fn sanitize(name: &str) -> String {
|
||||
let cleaned: String = name
|
||||
.chars()
|
||||
.map(|c| if "<>:\"/\\|?*".contains(c) || c.is_control() { '_' } else { c })
|
||||
.collect();
|
||||
let trimmed = cleaned.trim().trim_end_matches('.').to_string();
|
||||
if trimmed.is_empty() {
|
||||
"Untitled".into()
|
||||
} else {
|
||||
trimmed.chars().take(120).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StartRequest {
|
||||
id: String,
|
||||
url: String,
|
||||
folder: String,
|
||||
file_name: String,
|
||||
#[serde(default)]
|
||||
meta: Value,
|
||||
/// Artwork to keep with the download: name → signed URL.
|
||||
#[serde(default)]
|
||||
assets: HashMap<String, String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn download_start<R: Runtime>(app: AppHandle<R>, request: StartRequest) -> Result<Item, String> {
|
||||
let state = app.state::<Downloads>();
|
||||
let dir = state.dir.lock().clone().ok_or("Choose a download folder first.")?;
|
||||
// The folder may be nested ("Show/Season 1"); sanitize each component.
|
||||
let folder = request
|
||||
.folder
|
||||
.split(['/', '\\'])
|
||||
.filter(|c| !c.trim().is_empty() && *c != "." && *c != "..")
|
||||
.fold(dir.clone(), |p, c| p.join(sanitize(c)));
|
||||
tokio::fs::create_dir_all(&folder).await.map_err(|e| format!("Cannot create the download folder: {e}"))?;
|
||||
let file_path = folder.join(sanitize(&request.file_name));
|
||||
|
||||
let mut meta = request.meta.clone();
|
||||
if let Value::Object(map) = &mut meta {
|
||||
let mut local = serde_json::Map::new();
|
||||
for (name, url) in &request.assets {
|
||||
let target = folder.join(format!(".{}.jpg", sanitize(name)));
|
||||
if fetch_to(&state.client, url, &target).await.is_ok() {
|
||||
local.insert(name.clone(), Value::String(target.display().to_string()));
|
||||
}
|
||||
}
|
||||
map.insert("localAssets".into(), Value::Object(local));
|
||||
}
|
||||
|
||||
let item = Item {
|
||||
id: request.id.clone(),
|
||||
file_path: file_path.display().to_string(),
|
||||
total: 0,
|
||||
received: 0,
|
||||
status: Status::Queued,
|
||||
error: None,
|
||||
meta,
|
||||
created_at: now(),
|
||||
speed: 0,
|
||||
};
|
||||
{
|
||||
let mut items = state.items.lock();
|
||||
items.retain(|i| i.id != item.id);
|
||||
items.insert(0, item.clone());
|
||||
}
|
||||
save(&app);
|
||||
let _ = app.emit("download", &item);
|
||||
spawn(app.clone(), request.id, request.url);
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result<(), String> {
|
||||
let bytes = client.get(url).send().await.map_err(|e| e.to_string())?.error_for_status().map_err(|e| e.to_string())?.bytes().await.map_err(|e| e.to_string())?;
|
||||
tokio::fs::write(target, bytes).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
||||
let (tx, rx) = watch::channel(false);
|
||||
app.state::<Downloads>().cancels.lock().insert(id.clone(), tx);
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let permits = app.state::<Downloads>().permits.clone();
|
||||
let _permit = tokio::select! {
|
||||
p = permits.acquire_owned() => p,
|
||||
_ = cancelled(rx.clone()) => return,
|
||||
};
|
||||
let result = transfer(&app, &id, &url, rx).await;
|
||||
app.state::<Downloads>().cancels.lock().remove(&id);
|
||||
match result {
|
||||
Ok(true) => {
|
||||
update(&app, &id, |i| {
|
||||
i.status = Status::Completed;
|
||||
i.speed = 0;
|
||||
i.received = i.total.max(i.received);
|
||||
});
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
update(&app, &id, |i| {
|
||||
i.status = Status::Failed;
|
||||
i.error = Some(e);
|
||||
i.speed = 0;
|
||||
});
|
||||
}
|
||||
}
|
||||
save(&app);
|
||||
});
|
||||
}
|
||||
|
||||
async fn cancelled(mut rx: watch::Receiver<bool>) {
|
||||
while !*rx.borrow() {
|
||||
if rx.changed().await.is_err() {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns Ok(true) when complete, Ok(false) when paused/removed.
|
||||
async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch::Receiver<bool>) -> Result<bool, String> {
|
||||
let Some(item) = app.state::<Downloads>().items.lock().iter().find(|i| i.id == id).cloned() else { return Ok(false) };
|
||||
let final_path = PathBuf::from(&item.file_path);
|
||||
let part_path = final_path.with_extension(format!(
|
||||
"{}.part",
|
||||
final_path.extension().and_then(|e| e.to_str()).unwrap_or("bin")
|
||||
));
|
||||
let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0);
|
||||
|
||||
let client = app.state::<Downloads>().client.clone();
|
||||
let mut request = client.get(url);
|
||||
if existing > 0 {
|
||||
request = request.header("Range", format!("bytes={existing}-"));
|
||||
}
|
||||
let response = request.send().await.map_err(|e| format!("Could not reach the server: {e}"))?;
|
||||
let status = response.status();
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||
return Err("The server does not allow downloads for this account.".into());
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(format!("The server could not provide this file ({status})."));
|
||||
}
|
||||
let resumed = status.as_u16() == 206;
|
||||
let start = if resumed { existing } else { 0 };
|
||||
let total = response.content_length().map(|l| l + start).unwrap_or(0);
|
||||
let mut file = tokio::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.append(resumed)
|
||||
.truncate(!resumed)
|
||||
.open(&part_path)
|
||||
.await
|
||||
.map_err(|e| format!("Cannot write the download: {e}"))?;
|
||||
|
||||
update(app, id, |i| {
|
||||
i.status = Status::Downloading;
|
||||
i.total = total;
|
||||
i.received = start;
|
||||
i.error = None;
|
||||
});
|
||||
save(app);
|
||||
|
||||
let mut stream = response.bytes_stream();
|
||||
let mut received = start;
|
||||
let mut last_emit = Instant::now();
|
||||
let mut last_save = Instant::now();
|
||||
let mut window_bytes = 0u64;
|
||||
let mut window_start = Instant::now();
|
||||
let mut speed = 0u64;
|
||||
loop {
|
||||
if *rx.borrow() {
|
||||
file.flush().await.ok();
|
||||
return Ok(false);
|
||||
}
|
||||
let chunk = tokio::select! {
|
||||
c = stream.next() => c,
|
||||
_ = cancelled(rx.clone()) => { file.flush().await.ok(); return Ok(false); }
|
||||
};
|
||||
let Some(chunk) = chunk else { break };
|
||||
let chunk = chunk.map_err(|e| format!("The transfer was interrupted: {e}"))?;
|
||||
file.write_all(&chunk).await.map_err(|e| format!("Cannot write the download: {e}"))?;
|
||||
received += chunk.len() as u64;
|
||||
window_bytes += chunk.len() as u64;
|
||||
let elapsed = window_start.elapsed();
|
||||
if elapsed >= Duration::from_secs(1) {
|
||||
speed = (window_bytes as f64 / elapsed.as_secs_f64()) as u64;
|
||||
window_bytes = 0;
|
||||
window_start = Instant::now();
|
||||
}
|
||||
if last_emit.elapsed() >= Duration::from_millis(250) {
|
||||
last_emit = Instant::now();
|
||||
update(app, id, |i| {
|
||||
i.received = received;
|
||||
i.speed = speed;
|
||||
});
|
||||
}
|
||||
if last_save.elapsed() >= Duration::from_secs(5) {
|
||||
last_save = Instant::now();
|
||||
save(app);
|
||||
}
|
||||
}
|
||||
file.flush().await.map_err(|e| e.to_string())?;
|
||||
drop(file);
|
||||
if total > 0 && received < total {
|
||||
return Err("The transfer ended early. Resume to continue.".into());
|
||||
}
|
||||
tokio::fs::rename(&part_path, &final_path).await.map_err(|e| format!("Cannot finish the download: {e}"))?;
|
||||
update(app, id, |i| i.received = received);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn cancel<R: Runtime>(app: &AppHandle<R>, id: &str) {
|
||||
if let Some(tx) = app.state::<Downloads>().cancels.lock().remove(id) {
|
||||
let _ = tx.send(true);
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn download_pause<R: Runtime>(app: AppHandle<R>, id: String) {
|
||||
cancel(&app, &id);
|
||||
update(&app, &id, |i| {
|
||||
if i.status != Status::Completed {
|
||||
i.status = Status::Paused;
|
||||
i.speed = 0;
|
||||
}
|
||||
});
|
||||
save(&app);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
||||
cancel(&app, &id);
|
||||
update(&app, &id, |i| {
|
||||
i.status = Status::Queued;
|
||||
i.error = None;
|
||||
});
|
||||
spawn(app, id, url);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_files: bool) -> Result<(), String> {
|
||||
cancel(&app, &id);
|
||||
let removed = {
|
||||
let state = app.state::<Downloads>();
|
||||
let mut items = state.items.lock();
|
||||
let pos = items.iter().position(|i| i.id == id);
|
||||
pos.map(|p| items.remove(p))
|
||||
};
|
||||
if let (Some(item), true) = (removed, delete_files) {
|
||||
let path = PathBuf::from(&item.file_path);
|
||||
// Give the cancelled transfer a moment to release its file handle.
|
||||
tokio::time::sleep(Duration::from_millis(150)).await;
|
||||
let _ = tokio::fs::remove_file(&path).await;
|
||||
let part = path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin")));
|
||||
let _ = tokio::fs::remove_file(&part).await;
|
||||
if let Value::Object(assets) = &item.meta["localAssets"] {
|
||||
for v in assets.values() {
|
||||
if let Some(p) = v.as_str() {
|
||||
let _ = tokio::fs::remove_file(p).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Remove now-empty folders (season, then show), never the download root.
|
||||
let root = app.state::<Downloads>().dir.lock().clone();
|
||||
let mut folder = path.parent().map(|p| p.to_path_buf());
|
||||
while let Some(f) = folder {
|
||||
if Some(&f) == root.as_ref() || tokio::fs::remove_dir(&f).await.is_err() {
|
||||
break;
|
||||
}
|
||||
folder = f.parent().map(|p| p.to_path_buf());
|
||||
}
|
||||
}
|
||||
save(&app);
|
||||
let _ = app.emit("download-removed", &id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn download_list<R: Runtime>(app: AppHandle<R>) -> Vec<Item> {
|
||||
app.state::<Downloads>().items.lock().clone()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn download_set_dir<R: Runtime>(app: AppHandle<R>, dir: String) -> Result<(), String> {
|
||||
let path = PathBuf::from(dir);
|
||||
std::fs::create_dir_all(&path).map_err(|e| format!("Cannot use this folder: {e}"))?;
|
||||
*app.state::<Downloads>().dir.lock() = Some(path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn download_write_meta<R: Runtime>(app: AppHandle<R>, id: String, meta: Value) {
|
||||
update(&app, &id, |i| {
|
||||
let assets = i.meta.get("localAssets").cloned();
|
||||
i.meta = meta;
|
||||
if let (Some(a), Value::Object(m)) = (assets, &mut i.meta) {
|
||||
m.insert("localAssets".into(), a);
|
||||
}
|
||||
});
|
||||
save(&app);
|
||||
}
|
||||
64
src-tauri/src/lib.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
mod downloads;
|
||||
mod mpv;
|
||||
mod platform;
|
||||
mod player;
|
||||
mod system;
|
||||
|
||||
use tauri::{Manager, WindowEvent};
|
||||
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_http::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(
|
||||
tauri_plugin_window_state::Builder::default()
|
||||
.with_state_flags(
|
||||
tauri_plugin_window_state::StateFlags::SIZE
|
||||
| tauri_plugin_window_state::StateFlags::POSITION
|
||||
| tauri_plugin_window_state::StateFlags::MAXIMIZED,
|
||||
)
|
||||
.build(),
|
||||
)
|
||||
.manage(player::PlayerState::default())
|
||||
.manage(downloads::Downloads::default())
|
||||
.setup(|app| {
|
||||
let handle = app.handle().clone();
|
||||
downloads::restore(&handle);
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let w = window.clone();
|
||||
window.on_window_event(move |event| {
|
||||
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
|
||||
player::on_resize(&w);
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
player::player_init,
|
||||
player::player_show,
|
||||
player::player_command,
|
||||
player::player_set,
|
||||
player::player_get,
|
||||
system::secret_get,
|
||||
system::secret_set,
|
||||
system::secret_delete,
|
||||
system::app_info,
|
||||
system::dev_session,
|
||||
system::keep_awake,
|
||||
system::disk_space,
|
||||
system::save_url,
|
||||
downloads::download_start,
|
||||
downloads::download_pause,
|
||||
downloads::download_resume,
|
||||
downloads::download_remove,
|
||||
downloads::download_list,
|
||||
downloads::download_set_dir,
|
||||
downloads::download_write_meta,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running Kaleido");
|
||||
}
|
||||
6
src-tauri/src/main.rs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
// Prevents an additional console window on Windows in release.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
kaleido_lib::run()
|
||||
}
|
||||
370
src-tauri/src/mpv.rs
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
//! A small, dynamically loaded binding to libmpv's client API.
|
||||
//!
|
||||
//! libmpv is loaded at runtime (`libmpv-2.dll` beside the executable, or the
|
||||
//! repository's `vendor/mpv` folder during development) so the application can
|
||||
//! still start, browse and report a useful error if the library is missing.
|
||||
|
||||
use std::ffi::{c_char, c_int, c_void, CStr, CString};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use libloading::Library;
|
||||
use serde_json::{Map, Number, Value};
|
||||
|
||||
const FORMAT_NONE: c_int = 0;
|
||||
const FORMAT_STRING: c_int = 1;
|
||||
const FORMAT_FLAG: c_int = 3;
|
||||
const FORMAT_INT64: c_int = 4;
|
||||
const FORMAT_DOUBLE: c_int = 5;
|
||||
const FORMAT_NODE: c_int = 6;
|
||||
const FORMAT_NODE_ARRAY: c_int = 7;
|
||||
const FORMAT_NODE_MAP: c_int = 8;
|
||||
|
||||
pub const EVENT_NONE: c_int = 0;
|
||||
pub const EVENT_SHUTDOWN: c_int = 1;
|
||||
pub const EVENT_LOG_MESSAGE: c_int = 2;
|
||||
pub const EVENT_START_FILE: c_int = 6;
|
||||
pub const EVENT_END_FILE: c_int = 7;
|
||||
pub const EVENT_FILE_LOADED: c_int = 8;
|
||||
pub const EVENT_PLAYBACK_RESTART: c_int = 21;
|
||||
pub const EVENT_PROPERTY_CHANGE: c_int = 22;
|
||||
pub const EVENT_SEEK: c_int = 20;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
union NodeValue {
|
||||
string: *mut c_char,
|
||||
flag: c_int,
|
||||
int64: i64,
|
||||
double: f64,
|
||||
list: *mut NodeList,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Node {
|
||||
u: NodeValue,
|
||||
format: c_int,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct NodeList {
|
||||
num: c_int,
|
||||
values: *mut Node,
|
||||
keys: *mut *mut c_char,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct RawEvent {
|
||||
pub event_id: c_int,
|
||||
pub error: c_int,
|
||||
pub reply_userdata: u64,
|
||||
pub data: *mut c_void,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct EventProperty {
|
||||
name: *const c_char,
|
||||
format: c_int,
|
||||
data: *mut c_void,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct EventEndFile {
|
||||
reason: c_int,
|
||||
error: c_int,
|
||||
playlist_entry_id: i64,
|
||||
playlist_insert_id: i64,
|
||||
playlist_insert_num_entries: c_int,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct EventLogMessage {
|
||||
prefix: *const c_char,
|
||||
level: *const c_char,
|
||||
text: *const c_char,
|
||||
log_level: c_int,
|
||||
}
|
||||
|
||||
type Handle = *mut c_void;
|
||||
|
||||
struct Api {
|
||||
_lib: Library,
|
||||
create: unsafe extern "C" fn() -> Handle,
|
||||
initialize: unsafe extern "C" fn(Handle) -> c_int,
|
||||
terminate_destroy: unsafe extern "C" fn(Handle),
|
||||
set_option_string: unsafe extern "C" fn(Handle, *const c_char, *const c_char) -> c_int,
|
||||
command: unsafe extern "C" fn(Handle, *mut *const c_char) -> c_int,
|
||||
set_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int,
|
||||
get_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int,
|
||||
observe_property: unsafe extern "C" fn(Handle, u64, *const c_char, c_int) -> c_int,
|
||||
wait_event: unsafe extern "C" fn(Handle, f64) -> *mut RawEvent,
|
||||
free_node_contents: unsafe extern "C" fn(*mut Node),
|
||||
error_string: unsafe extern "C" fn(c_int) -> *const c_char,
|
||||
request_log_messages: unsafe extern "C" fn(Handle, *const c_char) -> c_int,
|
||||
}
|
||||
|
||||
/// Candidate locations for libmpv, in priority order: bundled resources, the
|
||||
/// executable's folder, the repository's `vendor/mpv/<os>` (development), and
|
||||
/// finally bare names for the system library search path.
|
||||
pub fn library_candidates(resource_dir: Option<PathBuf>) -> Vec<PathBuf> {
|
||||
let os = if cfg!(target_os = "windows") {
|
||||
"windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"macos"
|
||||
} else {
|
||||
"linux"
|
||||
};
|
||||
let mut dirs: Vec<PathBuf> = Vec::new();
|
||||
if let Some(dir) = resource_dir {
|
||||
dirs.push(dir.join("lib"));
|
||||
dirs.push(dir);
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
dirs.push(dir.to_path_buf());
|
||||
dirs.push(dir.join("../Frameworks"));
|
||||
}
|
||||
}
|
||||
dirs.push(Path::new(env!("CARGO_MANIFEST_DIR")).join("../vendor/mpv").join(os));
|
||||
let mut out: Vec<PathBuf> = dirs
|
||||
.iter()
|
||||
.flat_map(|d| crate::platform::MPV_LIBRARIES.iter().map(move |n| d.join(n)))
|
||||
.filter(|p| p.exists())
|
||||
.collect();
|
||||
out.extend(crate::platform::MPV_LIBRARIES.iter().map(PathBuf::from));
|
||||
out
|
||||
}
|
||||
|
||||
pub struct Mpv {
|
||||
api: Api,
|
||||
handle: Handle,
|
||||
}
|
||||
|
||||
// libmpv's client API is thread safe: every function may be called from any thread.
|
||||
unsafe impl Send for Mpv {}
|
||||
unsafe impl Sync for Mpv {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Event {
|
||||
Shutdown,
|
||||
StartFile,
|
||||
FileLoaded,
|
||||
PlaybackRestart,
|
||||
Seek,
|
||||
EndFile { reason: &'static str, error: Option<String> },
|
||||
Property { name: String, value: Value },
|
||||
Log { level: String, prefix: String, text: String },
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Mpv {
|
||||
pub fn load(candidates: &[PathBuf]) -> Result<Arc<Mpv>, String> {
|
||||
unsafe {
|
||||
let lib = candidates
|
||||
.iter()
|
||||
.find_map(|p| Library::new(p).ok())
|
||||
.ok_or_else(|| "libmpv was not found. Reinstall Kaleido to restore video playback.".to_string())?;
|
||||
macro_rules! sym {
|
||||
($name:literal) => {
|
||||
*lib.get(concat!($name, "\0").as_bytes()).map_err(|e| format!("libmpv is missing {}: {e}", $name))?
|
||||
};
|
||||
}
|
||||
let api = Api {
|
||||
create: sym!("mpv_create"),
|
||||
initialize: sym!("mpv_initialize"),
|
||||
terminate_destroy: sym!("mpv_terminate_destroy"),
|
||||
set_option_string: sym!("mpv_set_option_string"),
|
||||
command: sym!("mpv_command"),
|
||||
set_property: sym!("mpv_set_property"),
|
||||
get_property: sym!("mpv_get_property"),
|
||||
observe_property: sym!("mpv_observe_property"),
|
||||
wait_event: sym!("mpv_wait_event"),
|
||||
free_node_contents: sym!("mpv_free_node_contents"),
|
||||
error_string: sym!("mpv_error_string"),
|
||||
request_log_messages: sym!("mpv_request_log_messages"),
|
||||
_lib: lib,
|
||||
};
|
||||
let handle = (api.create)();
|
||||
if handle.is_null() {
|
||||
return Err("libmpv could not create a player.".into());
|
||||
}
|
||||
Ok(Arc::new(Mpv { api, handle }))
|
||||
}
|
||||
}
|
||||
|
||||
fn error(&self, code: c_int) -> String {
|
||||
unsafe { CStr::from_ptr((self.api.error_string)(code)).to_string_lossy().into_owned() }
|
||||
}
|
||||
|
||||
fn check(&self, code: c_int, what: &str) -> Result<(), String> {
|
||||
if code < 0 {
|
||||
Err(format!("{what}: {}", self.error(code)))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_option(&self, name: &str, value: &str) -> Result<(), String> {
|
||||
let n = CString::new(name).unwrap();
|
||||
let v = CString::new(value).unwrap();
|
||||
self.check(unsafe { (self.api.set_option_string)(self.handle, n.as_ptr(), v.as_ptr()) }, name)
|
||||
}
|
||||
|
||||
pub fn initialize(&self) -> Result<(), String> {
|
||||
self.check(unsafe { (self.api.initialize)(self.handle) }, "initialize")
|
||||
}
|
||||
|
||||
pub fn request_log_messages(&self, level: &str) {
|
||||
let l = CString::new(level).unwrap();
|
||||
unsafe { (self.api.request_log_messages)(self.handle, l.as_ptr()) };
|
||||
}
|
||||
|
||||
pub fn command(&self, args: &[String]) -> Result<(), String> {
|
||||
let owned: Vec<CString> = args.iter().map(|a| CString::new(a.as_str()).unwrap_or_default()).collect();
|
||||
let mut ptrs: Vec<*const c_char> = owned.iter().map(|c| c.as_ptr()).collect();
|
||||
ptrs.push(std::ptr::null());
|
||||
let what = args.first().cloned().unwrap_or_default();
|
||||
self.check(unsafe { (self.api.command)(self.handle, ptrs.as_mut_ptr()) }, &what)
|
||||
}
|
||||
|
||||
pub fn set_property(&self, name: &str, value: &Value) -> Result<(), String> {
|
||||
let n = CString::new(name).unwrap();
|
||||
// Scalars use their native formats; anything else goes through a string.
|
||||
unsafe {
|
||||
let code = match value {
|
||||
Value::Bool(b) => {
|
||||
let mut v: c_int = *b as c_int;
|
||||
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_FLAG, &mut v as *mut _ as *mut c_void)
|
||||
}
|
||||
Value::Number(num) if num.is_i64() => {
|
||||
let mut v: i64 = num.as_i64().unwrap();
|
||||
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_INT64, &mut v as *mut _ as *mut c_void)
|
||||
}
|
||||
Value::Number(num) => {
|
||||
let mut v: f64 = num.as_f64().unwrap_or(0.0);
|
||||
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_DOUBLE, &mut v as *mut _ as *mut c_void)
|
||||
}
|
||||
Value::String(s) => {
|
||||
let c = CString::new(s.as_str()).unwrap_or_default();
|
||||
let mut p = c.as_ptr();
|
||||
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_STRING, &mut p as *mut _ as *mut c_void)
|
||||
}
|
||||
Value::Null => {
|
||||
let c = CString::new("no").unwrap();
|
||||
let mut p = c.as_ptr();
|
||||
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_STRING, &mut p as *mut _ as *mut c_void)
|
||||
}
|
||||
other => {
|
||||
let c = CString::new(other.to_string()).unwrap_or_default();
|
||||
let mut p = c.as_ptr();
|
||||
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_STRING, &mut p as *mut _ as *mut c_void)
|
||||
}
|
||||
};
|
||||
self.check(code, name)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_property(&self, name: &str) -> Result<Value, String> {
|
||||
let n = CString::new(name).unwrap();
|
||||
unsafe {
|
||||
let mut node: Node = std::mem::zeroed();
|
||||
let code = (self.api.get_property)(self.handle, n.as_ptr(), FORMAT_NODE, &mut node as *mut _ as *mut c_void);
|
||||
self.check(code, name)?;
|
||||
let value = node_to_json(&node);
|
||||
(self.api.free_node_contents)(&mut node);
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn observe(&self, id: u64, name: &str) {
|
||||
let n = CString::new(name).unwrap();
|
||||
unsafe { (self.api.observe_property)(self.handle, id, n.as_ptr(), FORMAT_NODE) };
|
||||
}
|
||||
|
||||
/// Blocks for up to `timeout` seconds. Only one thread may wait for events.
|
||||
pub fn wait_event(&self, timeout: f64) -> Option<Event> {
|
||||
unsafe {
|
||||
let ev = &*(self.api.wait_event)(self.handle, timeout);
|
||||
Some(match ev.event_id {
|
||||
EVENT_NONE => return None,
|
||||
EVENT_SHUTDOWN => Event::Shutdown,
|
||||
EVENT_START_FILE => Event::StartFile,
|
||||
EVENT_FILE_LOADED => Event::FileLoaded,
|
||||
EVENT_PLAYBACK_RESTART => Event::PlaybackRestart,
|
||||
EVENT_SEEK => Event::Seek,
|
||||
EVENT_END_FILE => {
|
||||
let data = &*(ev.data as *const EventEndFile);
|
||||
let reason = match data.reason {
|
||||
0 => "eof",
|
||||
2 => "stop",
|
||||
3 => "quit",
|
||||
4 => "error",
|
||||
5 => "redirect",
|
||||
_ => "unknown",
|
||||
};
|
||||
let error = if data.reason == 4 { Some(self.error(data.error)) } else { None };
|
||||
Event::EndFile { reason, error }
|
||||
}
|
||||
EVENT_PROPERTY_CHANGE => {
|
||||
let data = &*(ev.data as *const EventProperty);
|
||||
let name = CStr::from_ptr(data.name).to_string_lossy().into_owned();
|
||||
let value = if data.format == FORMAT_NODE && !data.data.is_null() {
|
||||
node_to_json(&*(data.data as *const Node))
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
Event::Property { name, value }
|
||||
}
|
||||
EVENT_LOG_MESSAGE => {
|
||||
let data = &*(ev.data as *const EventLogMessage);
|
||||
Event::Log {
|
||||
level: CStr::from_ptr(data.level).to_string_lossy().into_owned(),
|
||||
prefix: CStr::from_ptr(data.prefix).to_string_lossy().into_owned(),
|
||||
text: CStr::from_ptr(data.text).to_string_lossy().trim_end().to_string(),
|
||||
}
|
||||
}
|
||||
_ => Event::Other,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Mpv {
|
||||
fn drop(&mut self) {
|
||||
unsafe { (self.api.terminate_destroy)(self.handle) }
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn node_to_json(node: &Node) -> Value {
|
||||
match node.format {
|
||||
FORMAT_STRING => {
|
||||
if node.u.string.is_null() {
|
||||
Value::Null
|
||||
} else {
|
||||
Value::String(CStr::from_ptr(node.u.string).to_string_lossy().into_owned())
|
||||
}
|
||||
}
|
||||
FORMAT_FLAG => Value::Bool(node.u.flag != 0),
|
||||
FORMAT_INT64 => Value::Number(node.u.int64.into()),
|
||||
FORMAT_DOUBLE => Number::from_f64(node.u.double).map(Value::Number).unwrap_or(Value::Null),
|
||||
FORMAT_NODE_ARRAY => {
|
||||
let list = &*node.u.list;
|
||||
let mut out = Vec::with_capacity(list.num.max(0) as usize);
|
||||
for i in 0..list.num as isize {
|
||||
out.push(node_to_json(&*list.values.offset(i)));
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
FORMAT_NODE_MAP => {
|
||||
let list = &*node.u.list;
|
||||
let mut out = Map::new();
|
||||
for i in 0..list.num as isize {
|
||||
let key = CStr::from_ptr(*list.keys.offset(i)).to_string_lossy().into_owned();
|
||||
out.insert(key, node_to_json(&*list.values.offset(i)));
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
FORMAT_NONE => Value::Null,
|
||||
_ => Value::Null,
|
||||
}
|
||||
}
|
||||
31
src-tauri/src/platform/linux.rs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
//! Linux: render mpv through its render API (OpenGL) beneath the WebKitGTK
|
||||
//! view, then implement `VideoSurface` here.
|
||||
//!
|
||||
//! Browsing, downloads, settings and updates already work here; only native
|
||||
//! video composition remains to be written.
|
||||
|
||||
use tauri::{Runtime, WebviewWindow};
|
||||
|
||||
use crate::mpv::Mpv;
|
||||
|
||||
pub const SURFACE_PROPERTIES: &[&str] = &[];
|
||||
pub const MPV_LIBRARIES: &[&str] = &["libmpv.so.2", "libmpv.so"];
|
||||
|
||||
pub struct VideoSurface;
|
||||
|
||||
impl VideoSurface {
|
||||
pub fn create<R: Runtime>(_: &WebviewWindow<R>) -> Result<VideoSurface, String> {
|
||||
Err("Video playback is not available on this platform yet.".into())
|
||||
}
|
||||
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
|
||||
Vec::new()
|
||||
}
|
||||
pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {}
|
||||
pub fn show(&mut self, _: bool) {}
|
||||
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>) {}
|
||||
}
|
||||
|
||||
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
||||
// TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus.
|
||||
let _ = rx.recv();
|
||||
}
|
||||
31
src-tauri/src/platform/macos.rs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
//! macOS: render mpv through its render API (libplacebo) into a CAMetalLayer
|
||||
//! placed beneath the WKWebView, then implement `VideoSurface` here.
|
||||
//!
|
||||
//! Browsing, downloads, settings and updates already work here; only native
|
||||
//! video composition remains to be written.
|
||||
|
||||
use tauri::{Runtime, WebviewWindow};
|
||||
|
||||
use crate::mpv::Mpv;
|
||||
|
||||
pub const SURFACE_PROPERTIES: &[&str] = &[];
|
||||
pub const MPV_LIBRARIES: &[&str] = &["libmpv.2.dylib", "libmpv.dylib"];
|
||||
|
||||
pub struct VideoSurface;
|
||||
|
||||
impl VideoSurface {
|
||||
pub fn create<R: Runtime>(_: &WebviewWindow<R>) -> Result<VideoSurface, String> {
|
||||
Err("Video playback is not available on this platform yet.".into())
|
||||
}
|
||||
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
|
||||
Vec::new()
|
||||
}
|
||||
pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {}
|
||||
pub fn show(&mut self, _: bool) {}
|
||||
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>) {}
|
||||
}
|
||||
|
||||
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
||||
// TODO(macOS): IOPMAssertionCreateWithName(PreventUserIdleDisplaySleep).
|
||||
let _ = rx.recv();
|
||||
}
|
||||
23
src-tauri/src/platform/mod.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
//! Everything that differs between operating systems lives in this module.
|
||||
//! Each platform file exposes the same items:
|
||||
//!
|
||||
//! - `VideoSurface`: composes mpv's output beneath the web view
|
||||
//! (`create`, `mpv_options`, `on_property`, `show`, `fit`).
|
||||
//! - `SURFACE_PROPERTIES`: mpv properties the surface observes.
|
||||
//! - `MPV_LIBRARIES`: libmpv file names to look for.
|
||||
//! - `hold_awake`: prevents display sleep until the receiver closes.
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use self::windows::*;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use self::macos::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use self::linux::*;
|
||||
133
src-tauri/src/platform/windows.rs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
//! Windows: DirectComposition video surface, libmpv names and power requests.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use tauri::{Runtime, WebviewWindow};
|
||||
use ::windows::core::{IUnknown, Interface};
|
||||
use ::windows::Win32::Foundation::{HWND, RECT};
|
||||
use ::windows::Win32::Graphics::DirectComposition::*;
|
||||
use ::windows::Win32::UI::WindowsAndMessaging::GetClientRect;
|
||||
|
||||
use crate::mpv::Mpv;
|
||||
|
||||
pub struct VideoSurface {
|
||||
attached: usize,
|
||||
device: IDCompositionDevice,
|
||||
_target: IDCompositionTarget,
|
||||
root: IDCompositionVisual,
|
||||
visible: bool,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
}
|
||||
|
||||
// DirectComposition objects may be used from any thread when access is
|
||||
// serialized; the surface always sits behind PlayerState's mutex.
|
||||
unsafe impl Send for VideoSurface {}
|
||||
|
||||
fn client_size(hwnd: HWND) -> (i32, i32) {
|
||||
let mut rect = RECT::default();
|
||||
unsafe {
|
||||
let _ = GetClientRect(hwnd, &mut rect);
|
||||
}
|
||||
((rect.right - rect.left).max(16), (rect.bottom - rect.top).max(16))
|
||||
}
|
||||
|
||||
impl VideoSurface {
|
||||
pub fn create<R: Runtime>(window: &WebviewWindow<R>) -> Result<VideoSurface, String> {
|
||||
let hwnd = HWND(window.hwnd().map_err(|e| e.to_string())?.0 as _);
|
||||
unsafe {
|
||||
let device: IDCompositionDevice =
|
||||
DCompositionCreateDevice2(None).map_err(|e| format!("DirectComposition is unavailable: {e}"))?;
|
||||
// topmost = false: the visual tree is composed behind the window's children.
|
||||
let target = device.CreateTargetForHwnd(hwnd, false).map_err(|e| e.to_string())?;
|
||||
let root = device.CreateVisual().map_err(|e| e.to_string())?;
|
||||
let (width, height) = client_size(hwnd);
|
||||
device.Commit().map_err(|e| e.to_string())?;
|
||||
let _ = ⌖
|
||||
Ok(VideoSurface {
|
||||
attached: 0,
|
||||
device,
|
||||
_target: target,
|
||||
root,
|
||||
visible: false,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// mpv renders into a composition swapchain (`display-swapchain`), shown
|
||||
/// in a DirectComposition visual behind the web view's child windows.
|
||||
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
|
||||
vec![
|
||||
("vo", "gpu-next".into()),
|
||||
("gpu-api", "d3d11".into()),
|
||||
("d3d11-output-mode", "composition".into()),
|
||||
("d3d11-composition-size", format!("{}x{}", self.width, self.height)),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn on_property(&mut self, name: &str, value: &serde_json::Value) {
|
||||
if name == "display-swapchain" {
|
||||
self.attach(value.as_i64().unwrap_or(0) as usize);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows mpv's current swapchain; mpv recreates it with its video output.
|
||||
fn attach(&mut self, swapchain: usize) {
|
||||
if swapchain == self.attached {
|
||||
return;
|
||||
}
|
||||
self.attached = swapchain;
|
||||
unsafe {
|
||||
let raw = swapchain as *mut c_void;
|
||||
let result = match IUnknown::from_raw_borrowed(&raw) {
|
||||
Some(unknown) if swapchain != 0 => self.root.SetContent(unknown),
|
||||
_ => self.root.SetContent(None::<&IUnknown>),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
eprintln!("[video] could not attach swapchain: {e}");
|
||||
}
|
||||
let _ = self.device.Commit();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(&mut self, visible: bool) {
|
||||
if self.visible == visible {
|
||||
return;
|
||||
}
|
||||
self.visible = visible;
|
||||
unsafe {
|
||||
let _ = if visible { self._target.SetRoot(&self.root) } else { self._target.SetRoot(None::<&IDCompositionVisual>) };
|
||||
let _ = self.device.Commit();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fit<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>) {
|
||||
let Ok(h) = window.hwnd() else { return };
|
||||
let (w, h) = client_size(HWND(h.0 as _));
|
||||
if (w, h) == (self.width, self.height) {
|
||||
return;
|
||||
}
|
||||
self.width = w;
|
||||
self.height = h;
|
||||
if let Some(mpv) = mpv {
|
||||
let _ = mpv.set_property("d3d11-composition-size", &serde_json::Value::String(format!("{w}x{h}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// mpv properties the surface needs to observe.
|
||||
pub const SURFACE_PROPERTIES: &[&str] = &["display-swapchain"];
|
||||
|
||||
/// File names libmpv may have on this platform.
|
||||
pub const MPV_LIBRARIES: &[&str] = &["libmpv-2.dll", "mpv-2.dll"];
|
||||
|
||||
/// Keeps the display awake until `rx` closes or receives.
|
||||
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
||||
use ::windows::Win32::System::Power::*;
|
||||
unsafe {
|
||||
SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED);
|
||||
let _ = rx.recv();
|
||||
SetThreadExecutionState(ES_CONTINUOUS);
|
||||
}
|
||||
}
|
||||
207
src-tauri/src/player.rs
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
//! Video playback: one long-lived libmpv instance whose output is composed
|
||||
//! beneath the (transparent) web view, so the interface draws its controls
|
||||
//! directly over the video. How the video reaches the screen is platform
|
||||
//! specific; see `platform::VideoSurface`.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow};
|
||||
|
||||
use crate::mpv::{self, Event, Mpv};
|
||||
use crate::platform::VideoSurface;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct PlayerState {
|
||||
mpv: Mutex<Option<Arc<Mpv>>>,
|
||||
surface: Mutex<Option<VideoSurface>>,
|
||||
}
|
||||
|
||||
/// Properties streamed to the interface as they change.
|
||||
const OBSERVED: &[&str] = &[
|
||||
"time-pos",
|
||||
"duration",
|
||||
"pause",
|
||||
"paused-for-cache",
|
||||
"cache-buffering-state",
|
||||
"demuxer-cache-time",
|
||||
"eof-reached",
|
||||
"idle-active",
|
||||
"track-list",
|
||||
"volume",
|
||||
"mute",
|
||||
"speed",
|
||||
"sub-delay",
|
||||
"audio-delay",
|
||||
"video-params",
|
||||
"hwdec-current",
|
||||
"chapter-list",
|
||||
"seeking",
|
||||
];
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InitOptions {
|
||||
#[serde(default)]
|
||||
pub hwdec: Option<String>,
|
||||
#[serde(default)]
|
||||
pub hdr: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub extra: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
fn emit<R: Runtime>(app: &AppHandle<R>, payload: Value) {
|
||||
let _ = app.emit("mpv", payload);
|
||||
}
|
||||
|
||||
fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts: &InitOptions) -> Result<Arc<Mpv>, String> {
|
||||
let resource_dir = app.path().resource_dir().ok();
|
||||
let mpv = Mpv::load(&mpv::library_candidates(resource_dir))?;
|
||||
let surface = VideoSurface::create(window)?;
|
||||
let render_options = surface.mpv_options();
|
||||
*app.state::<PlayerState>().surface.lock() = Some(surface);
|
||||
|
||||
let set = |k: &str, v: &str| mpv.set_option(k, v);
|
||||
for (k, v) in &render_options {
|
||||
set(k, v)?;
|
||||
}
|
||||
set("hwdec", opts.hwdec.as_deref().unwrap_or("auto-safe"))?;
|
||||
set("keep-open", "yes")?;
|
||||
set("idle", "yes")?;
|
||||
set("force-window", "yes")?;
|
||||
set("osc", "no")?;
|
||||
set("osd-level", "0")?;
|
||||
set("input-default-bindings", "no")?;
|
||||
set("input-vo-keyboard", "no")?;
|
||||
set("input-cursor", "no")?;
|
||||
set("cursor-autohide", "no")?;
|
||||
set("terminal", "no")?;
|
||||
set("ytdl", "no")?;
|
||||
set("sub-auto", "no")?;
|
||||
set("audio-client-name", "Kaleido")?;
|
||||
set("title", "Kaleido")?;
|
||||
set("cache", "yes")?;
|
||||
set("demuxer-max-bytes", "300MiB")?;
|
||||
set("demuxer-max-back-bytes", "100MiB")?;
|
||||
set("demuxer-readahead-secs", "30")?;
|
||||
set("network-timeout", "30")?;
|
||||
set("hr-seek", "yes")?;
|
||||
set("background-color", "#000000")?;
|
||||
set("user-agent", "Kaleido")?;
|
||||
if opts.hdr.unwrap_or(true) {
|
||||
let _ = set("target-colorspace-hint", "yes");
|
||||
}
|
||||
for (k, v) in &opts.extra {
|
||||
let _ = set(k, v);
|
||||
}
|
||||
mpv.request_log_messages("warn");
|
||||
mpv.initialize()?;
|
||||
for (i, name) in OBSERVED.iter().chain(crate::platform::SURFACE_PROPERTIES).enumerate() {
|
||||
mpv.observe(i as u64 + 1, name);
|
||||
}
|
||||
|
||||
let events = mpv.clone();
|
||||
let app = app.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("mpv-events".into())
|
||||
.spawn(move || event_loop(app, events))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(mpv)
|
||||
}
|
||||
|
||||
fn event_loop<R: Runtime>(app: AppHandle<R>, mpv: Arc<Mpv>) {
|
||||
let mut last_time = Instant::now() - Duration::from_secs(1);
|
||||
let mut last_pos = -1.0f64;
|
||||
loop {
|
||||
let Some(event) = mpv.wait_event(1.0) else { continue };
|
||||
match event {
|
||||
Event::Shutdown => break,
|
||||
Event::StartFile => emit(&app, json!({"type": "start-file"})),
|
||||
Event::FileLoaded => emit(&app, json!({"type": "file-loaded"})),
|
||||
Event::PlaybackRestart => emit(&app, json!({"type": "playback-restart"})),
|
||||
Event::Seek => emit(&app, json!({"type": "seek"})),
|
||||
Event::EndFile { reason, error } => emit(&app, json!({"type": "end-file", "reason": reason, "error": error})),
|
||||
Event::Property { name, value } => {
|
||||
if crate::platform::SURFACE_PROPERTIES.contains(&name.as_str()) {
|
||||
let state = app.state::<PlayerState>();
|
||||
let mut surface = state.surface.lock();
|
||||
if let Some(surface) = surface.as_mut() {
|
||||
surface.on_property(&name, &value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if name == "time-pos" {
|
||||
// Positions change every frame; a few updates a second suffice.
|
||||
let pos = value.as_f64().unwrap_or(-1.0);
|
||||
let now = Instant::now();
|
||||
if now.duration_since(last_time) < Duration::from_millis(200) && (pos - last_pos).abs() < 1.5 {
|
||||
continue;
|
||||
}
|
||||
last_time = now;
|
||||
last_pos = pos;
|
||||
}
|
||||
emit(&app, json!({"type": "property", "name": name, "value": value}));
|
||||
}
|
||||
Event::Log { level, prefix, text } => {
|
||||
eprintln!("[mpv {level}] {prefix}: {text}");
|
||||
emit(&app, json!({"type": "log", "level": level, "prefix": prefix, "text": text}));
|
||||
}
|
||||
Event::Other => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn player<R: Runtime>(app: &AppHandle<R>) -> Result<Arc<Mpv>, String> {
|
||||
app.state::<PlayerState>().mpv.lock().clone().ok_or_else(|| "The player has not started.".to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn player_init<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, options: Option<InitOptions>) -> Result<(), String> {
|
||||
let state = app.state::<PlayerState>();
|
||||
let mut guard = state.mpv.lock();
|
||||
if guard.is_none() {
|
||||
*guard = Some(create_player(&app, &window, &options.unwrap_or_default())?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, visible: bool) -> Result<(), String> {
|
||||
let state = app.state::<PlayerState>();
|
||||
let mpv = state.mpv.lock().clone();
|
||||
let mut surface = state.surface.lock();
|
||||
if let Some(surface) = surface.as_mut() {
|
||||
surface.fit(&window, mpv.as_deref());
|
||||
surface.show(visible);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn player_command<R: Runtime>(app: AppHandle<R>, args: Vec<String>) -> Result<(), String> {
|
||||
player(&app)?.command(&args)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn player_set<R: Runtime>(app: AppHandle<R>, name: String, value: Value) -> Result<(), String> {
|
||||
player(&app)?.set_property(&name, &value)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn player_get<R: Runtime>(app: AppHandle<R>, name: String) -> Result<Value, String> {
|
||||
player(&app)?.get_property(&name)
|
||||
}
|
||||
|
||||
/// Keeps the video surface matched to the window's client area.
|
||||
pub fn on_resize<R: Runtime>(window: &WebviewWindow<R>) {
|
||||
let app = window.app_handle();
|
||||
let state = app.state::<PlayerState>();
|
||||
let mpv = state.mpv.lock().clone();
|
||||
let mut surface = state.surface.lock();
|
||||
if let Some(surface) = surface.as_mut() {
|
||||
surface.fit(window, mpv.as_deref());
|
||||
}
|
||||
}
|
||||
161
src-tauri/src/system.rs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
//! Small platform services: credential storage, app paths, power and disk.
|
||||
|
||||
use std::sync::mpsc::{channel, Sender};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use tauri::{AppHandle, Manager, Runtime};
|
||||
|
||||
const SERVICE: &str = "tv.kaleido.desktop";
|
||||
|
||||
fn entry(key: &str) -> Result<keyring::Entry, String> {
|
||||
keyring::Entry::new(SERVICE, key).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Secrets (Plex tokens) live in Windows Credential Manager, never in plain files.
|
||||
#[tauri::command]
|
||||
pub fn secret_get(key: String) -> Result<Option<String>, String> {
|
||||
match entry(&key)?.get_password() {
|
||||
Ok(v) => Ok(Some(v)),
|
||||
Err(keyring::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn secret_set(key: String, value: String) -> Result<(), String> {
|
||||
entry(&key)?.set_password(&value).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn secret_delete(key: String) -> Result<(), String> {
|
||||
match entry(&key)?.delete_credential() {
|
||||
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppInfo {
|
||||
version: String,
|
||||
data_dir: String,
|
||||
default_download_dir: String,
|
||||
platform: String,
|
||||
device_name: String,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn app_info<R: Runtime>(app: AppHandle<R>) -> AppInfo {
|
||||
let paths = app.path();
|
||||
let data = paths.app_data_dir().map(|p| p.display().to_string()).unwrap_or_default();
|
||||
let downloads = paths
|
||||
.video_dir()
|
||||
.map(|p| p.join("Kaleido"))
|
||||
.or_else(|_| paths.app_data_dir().map(|p| p.join("Downloads")))
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_default();
|
||||
AppInfo {
|
||||
version: app.package_info().version.to_string(),
|
||||
data_dir: data,
|
||||
default_download_dir: downloads,
|
||||
platform: std::env::consts::OS.to_string(),
|
||||
device_name: std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Development builds can start signed in from the repository's ignored `.env`
|
||||
/// (`PLEX_SERVER_URL`, `PLEX_TOKEN`). Release builds never read it.
|
||||
#[tauri::command]
|
||||
pub fn dev_session() -> Option<Value> {
|
||||
if !cfg!(debug_assertions) {
|
||||
return None;
|
||||
}
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
let path = std::env::var("KALEIDO_DEV_ENV")
|
||||
.ok()
|
||||
.map(std::path::PathBuf::from)
|
||||
.into_iter()
|
||||
.chain([root.join(".env"), root.join("../Custom plex client/.env")])
|
||||
.find(|p| p.exists())?;
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let mut server = None;
|
||||
let mut token = None;
|
||||
for line in text.lines() {
|
||||
if let Some((k, v)) = line.split_once('=') {
|
||||
let v = v.trim().trim_matches('"').to_string();
|
||||
match k.trim() {
|
||||
"PLEX_SERVER_URL" => server = Some(v),
|
||||
"PLEX_TOKEN" => token = Some(v),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(json!({ "server": server?, "token": token? }))
|
||||
}
|
||||
|
||||
static AWAKE: Mutex<Option<Sender<()>>> = Mutex::new(None);
|
||||
|
||||
/// Prevents display sleep during playback.
|
||||
#[tauri::command]
|
||||
pub fn keep_awake(enabled: bool) {
|
||||
let mut guard = AWAKE.lock();
|
||||
if let Some(stop) = guard.take() {
|
||||
let _ = stop.send(());
|
||||
}
|
||||
if !enabled {
|
||||
return;
|
||||
}
|
||||
let (tx, rx) = channel::<()>();
|
||||
*guard = Some(tx);
|
||||
std::thread::spawn(move || crate::platform::hold_awake(rx));
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiskSpace {
|
||||
free: u64,
|
||||
total: u64,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn disk_space(path: String) -> Result<DiskSpace, String> {
|
||||
// Walk up to an existing folder; the download folder may not exist yet.
|
||||
let mut p = std::path::PathBuf::from(&path);
|
||||
while !p.exists() {
|
||||
if !p.pop() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(DiskSpace {
|
||||
free: fs2::available_space(&p).map_err(|e| e.to_string())?,
|
||||
total: fs2::total_space(&p).map_err(|e| e.to_string())?,
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn data_dir<R: Runtime>(app: &AppHandle<R>) -> std::path::PathBuf {
|
||||
app.path().app_data_dir().unwrap_or_else(|_| std::env::temp_dir().join("Kaleido"))
|
||||
}
|
||||
|
||||
/// Saves a URL (e.g. server logs) to a file the user chose.
|
||||
#[tauri::command]
|
||||
pub async fn save_url(url: String, path: String) -> Result<u64, String> {
|
||||
use futures_util::StreamExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let response = reqwest::Client::new().get(&url).send().await.map_err(|e| e.to_string())?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("The server returned {}", response.status()));
|
||||
}
|
||||
let mut file = tokio::fs::File::create(&path).await.map_err(|e| e.to_string())?;
|
||||
let mut stream = response.bytes_stream();
|
||||
let mut total = 0u64;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk.map_err(|e| e.to_string())?;
|
||||
total += chunk.len() as u64;
|
||||
file.write_all(&chunk).await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
file.flush().await.map_err(|e| e.to_string())?;
|
||||
Ok(total)
|
||||
}
|
||||
64
src-tauri/tauri.conf.json
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Kaleido",
|
||||
"version": "0.1.0",
|
||||
"identifier": "tv.kaleido.desktop",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
"devUrl": "http://localhost:1420",
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"withGlobalTauri": false,
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Kaleido",
|
||||
"width": 1480,
|
||||
"height": 900,
|
||||
"minWidth": 900,
|
||||
"minHeight": 580,
|
||||
"center": true,
|
||||
"decorations": false,
|
||||
"transparent": false,
|
||||
"shadow": true,
|
||||
"visible": false,
|
||||
"dragDropEnabled": false
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null,
|
||||
"assetProtocol": {
|
||||
"enable": true,
|
||||
"scope": [
|
||||
"**"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"createUpdaterArtifacts": true,
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"shortDescription": "Kaleido for Plex",
|
||||
"longDescription": "Kaleido is a cinematic Plex client for the desktop.",
|
||||
"category": "Video",
|
||||
"copyright": "\u00a9 Elijah Kuntz",
|
||||
"publisher": "Kaleido"
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEU0MTA2RjI0OUFFQzU1QzUKUldURlZleWFKRzhRNUlqTTR3U095STFYS3BsUXd2UnZMYlRrQmt3aUk5YU5WSjdqcUxVcHllU1EK",
|
||||
"endpoints": [
|
||||
"https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
16
src-tauri/tauri.linux.conf.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"bundle": {
|
||||
"targets": [
|
||||
"appimage",
|
||||
"deb"
|
||||
],
|
||||
"linux": {
|
||||
"deb": {
|
||||
"depends": [
|
||||
"libmpv2"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
15
src-tauri/tauri.macos.conf.json
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"bundle": {
|
||||
"targets": [
|
||||
"app",
|
||||
"dmg"
|
||||
],
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "12.0",
|
||||
"frameworks": [
|
||||
"../vendor/mpv/macos/libmpv.2.dylib"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
45
src-tauri/tauri.windows.conf.json
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Kaleido",
|
||||
"width": 1480,
|
||||
"height": 900,
|
||||
"minWidth": 900,
|
||||
"minHeight": 580,
|
||||
"center": true,
|
||||
"decorations": false,
|
||||
"transparent": true,
|
||||
"shadow": true,
|
||||
"visible": false,
|
||||
"dragDropEnabled": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"bundle": {
|
||||
"targets": [
|
||||
"nsis"
|
||||
],
|
||||
"resources": {
|
||||
"../vendor/mpv/windows/libmpv-2.dll": "libmpv-2.dll"
|
||||
},
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"installMode": "currentUser",
|
||||
"installerIcon": "icons/icon.ico"
|
||||
},
|
||||
"webviewInstallMode": {
|
||||
"type": "downloadBootstrapper"
|
||||
}
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"windows": {
|
||||
"installMode": "passive"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
258
src/app/App.tsx
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { queryClient, invalidateLibrary } from './queries';
|
||||
import { useSession } from './session';
|
||||
import { useRouter, navigate, type Route } from './router';
|
||||
import { useSettings } from './settings';
|
||||
import { TopBar } from './TopBar';
|
||||
import { MenuHost, ToastHost, ConfirmHost } from '../ui/overlays';
|
||||
import { HoverPreviewHost } from '../ui/HoverPreview';
|
||||
import { PageLoader } from '../ui/primitives';
|
||||
import { Splash } from '../screens/Splash';
|
||||
import { SignIn } from '../screens/SignIn';
|
||||
import { ServerPicker } from '../screens/ServerPicker';
|
||||
import { win } from '../platform/native';
|
||||
import { usePlayer } from '../player/store';
|
||||
import { PlayerOverlay } from '../player/PlayerOverlay';
|
||||
import { DialogHost } from '../screens/dialogs/DialogHost';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { libraryRevision } from '../plex/api';
|
||||
import { checkForUpdate } from './updater';
|
||||
import { Home } from '../screens/Home';
|
||||
import { SectionScreen } from '../screens/Section';
|
||||
import { ItemScreen } from '../screens/Item';
|
||||
|
||||
const Search = lazy(() => import('../screens/Search'));
|
||||
const Downloads = lazy(() => import('../screens/Downloads'));
|
||||
const Settings = lazy(() => import('../screens/settings/Settings'));
|
||||
const Person = lazy(() => import('../screens/Person'));
|
||||
const HubScreen = lazy(() => import('../screens/HubScreen'));
|
||||
|
||||
function Screen({ route }: { route: Route }) {
|
||||
switch (route.name) {
|
||||
case 'home':
|
||||
return <Home />;
|
||||
case 'section':
|
||||
return <SectionScreen kind={route.kind} tab={route.tab} />;
|
||||
case 'item':
|
||||
return <ItemScreen id={route.id} />;
|
||||
case 'person':
|
||||
return <Person id={route.id} title={route.title} thumb={route.thumb} />;
|
||||
case 'hub':
|
||||
return <HubScreen hubKey={route.key} title={route.title} />;
|
||||
case 'search':
|
||||
return <Search initial={route.query} />;
|
||||
case 'downloads':
|
||||
return <Downloads />;
|
||||
case 'settings':
|
||||
return <Settings mode={route.mode} tab={route.tab} />;
|
||||
}
|
||||
}
|
||||
|
||||
/** One scroll container per history entry; its position is restored on Back. */
|
||||
function Page({ onScrolled }: { onScrolled: (top: number) => void }) {
|
||||
const entry = useRouter((s) => s.current);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const target = entry.scroll;
|
||||
el.scrollTop = target;
|
||||
onScrolled(target);
|
||||
if (!target) return;
|
||||
// Content may still be loading; keep trying briefly until it is tall enough.
|
||||
let tries = 0;
|
||||
const t = setInterval(() => {
|
||||
if (!ref.current || tries++ > 30) return clearInterval(t);
|
||||
ref.current.scrollTop = target;
|
||||
if (Math.abs(ref.current.scrollTop - target) < 2) clearInterval(t);
|
||||
}, 50);
|
||||
return () => clearInterval(t);
|
||||
}, [entry]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="main-scroll"
|
||||
data-route={entry.route.name}
|
||||
onScroll={(e) => {
|
||||
const top = (e.target as HTMLDivElement).scrollTop;
|
||||
entry.scroll = top;
|
||||
onScrolled(top);
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<main className="page-enter" key={entry.id}>
|
||||
<Screen route={entry.route} />
|
||||
</main>
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useGlobalShortcuts() {
|
||||
useEffect(() => {
|
||||
const isTyping = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName));
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (usePlayer.getState().open) return;
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'f')) {
|
||||
e.preventDefault();
|
||||
navigate({ name: 'search' });
|
||||
} else if (e.altKey && e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
useRouter.getState().back();
|
||||
} else if (e.altKey && e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
useRouter.getState().forward();
|
||||
} else if (e.key === 'F11') {
|
||||
e.preventDefault();
|
||||
win.isFullscreen().then((fs) => win.setFullscreen(!fs));
|
||||
} else if ((e.key === 'Escape' || e.key === 'Backspace') && !isTyping(e.target) && !document.querySelector('.menu-layer, .dialog-layer')) {
|
||||
if (e.key === 'Escape' && document.fullscreenElement) return;
|
||||
useRouter.getState().back();
|
||||
} else if ((e.ctrlKey || e.metaKey) && e.key === ',') {
|
||||
e.preventDefault();
|
||||
navigate({ name: 'settings', mode: 'app', tab: 'general' });
|
||||
}
|
||||
};
|
||||
// Mouse back/forward buttons.
|
||||
const onMouse = (e: MouseEvent) => {
|
||||
if (usePlayer.getState().open) return;
|
||||
if (e.button === 3) {
|
||||
e.preventDefault();
|
||||
useRouter.getState().back();
|
||||
} else if (e.button === 4) {
|
||||
e.preventDefault();
|
||||
useRouter.getState().forward();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
window.addEventListener('mouseup', onMouse);
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('mouseup', onMouse);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
/** Refreshes browsing when the server's libraries change. */
|
||||
function useLibrarySync() {
|
||||
const server = useSession((s) => s.server);
|
||||
useEffect(() => {
|
||||
if (!server) return;
|
||||
let last = '';
|
||||
let stopped = false;
|
||||
const tick = async () => {
|
||||
if (stopped || document.hidden || usePlayer.getState().open) return;
|
||||
try {
|
||||
const rev = await libraryRevision(server);
|
||||
if (last && rev !== last) invalidateLibrary();
|
||||
last = rev;
|
||||
} catch {
|
||||
/* transient */
|
||||
}
|
||||
};
|
||||
tick();
|
||||
const t = setInterval(tick, 20000);
|
||||
const onVisible = () => !document.hidden && tick();
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearInterval(t);
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, [server]);
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const [scrolled, setScrolled] = useState(false);
|
||||
const playerOpen = usePlayer((s) => s.open);
|
||||
const startPage = useSettings.getState().startPage;
|
||||
useGlobalShortcuts();
|
||||
useLibrarySync();
|
||||
useEffect(() => {
|
||||
if (startPage !== 'home') useRouter.getState().reset(startPage === 'movies' ? { name: 'section', kind: 'movie', tab: 'discover' } : { name: 'section', kind: 'show', tab: 'discover' });
|
||||
useDownloads.getState().init().then(() => useDownloads.getState().resumeInterrupted());
|
||||
const t = setTimeout(() => checkForUpdate(false), 8000);
|
||||
return () => clearTimeout(t);
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<div className="app-shell" aria-hidden={playerOpen}>
|
||||
<TopBar solid={scrolled} />
|
||||
<Page onScrolled={(top) => setScrolled(top > 24)} />
|
||||
</div>
|
||||
<PlayerOverlay />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function OfflineShell() {
|
||||
const error = useSession((s) => s.error);
|
||||
const init = useSession((s) => s.init);
|
||||
useEffect(() => {
|
||||
useDownloads.getState().init();
|
||||
useRouter.getState().reset({ name: 'downloads' });
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<div className="app-shell offline">
|
||||
<div className="offline-banner" data-tauri-drag-region>
|
||||
<span>{error || 'You’re offline.'}</span>
|
||||
<button className="btn text" onClick={() => init()}>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
<div className="main-scroll">
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<Downloads offline />
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
<PlayerOverlay />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const status = useSession((s) => s.status);
|
||||
const hasServer = useSession((s) => !!s.server);
|
||||
const reducedMotion = useSettings((s) => s.reducedMotion);
|
||||
const [splashDone, setSplashDone] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
useSession.getState().init();
|
||||
// The window appears once the first frame is painted (no white flash).
|
||||
requestAnimationFrame(() => win.show());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle('reduced-motion', reducedMotion);
|
||||
}, [reducedMotion]);
|
||||
|
||||
// Switching servers or users starts browsing fresh.
|
||||
const serverId = useSession((s) => s.server?.machineId);
|
||||
useEffect(() => {
|
||||
if (serverId) useRouter.getState().reset({ name: 'home' });
|
||||
}, [serverId]);
|
||||
|
||||
let body;
|
||||
if (status === 'loading') body = null;
|
||||
else if (status === 'signed-out') body = <SignIn />;
|
||||
else if (status === 'choose-server' || (status === 'connecting' && !hasServer)) body = <ServerPicker />;
|
||||
else if (status === 'offline') body = <OfflineShell />;
|
||||
else body = <Shell />;
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{body}
|
||||
{(!splashDone || status === 'loading') && <Splash ready={status !== 'loading'} onDone={() => setSplashDone(true)} />}
|
||||
<HoverPreviewHost />
|
||||
<DialogHost />
|
||||
<MenuHost />
|
||||
<ConfirmHost />
|
||||
<ToastHost />
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
126
src/app/TopBar.tsx
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { navigate, topLevel, useRouter } from './router';
|
||||
import { useSession } from './session';
|
||||
import { useSettings } from './settings';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { KaleidoMark } from '../ui/primitives';
|
||||
import { openMenu, type MenuItem } from '../ui/overlays';
|
||||
import { isNative, win } from '../platform/native';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { useHomeUsers } from './useHomeUsers';
|
||||
|
||||
const NAV = [
|
||||
{ id: 'home', label: 'Home', route: { name: 'home' } as const },
|
||||
{ id: 'movies', label: 'Movies', route: { name: 'section', kind: 'movie', tab: 'discover' } as const },
|
||||
{ id: 'shows', label: 'TV Shows', route: { name: 'section', kind: 'show', tab: 'discover' } as const },
|
||||
{ id: 'downloads', label: 'Downloads', route: { name: 'downloads' } as const },
|
||||
];
|
||||
|
||||
function WindowControls() {
|
||||
const [maximized, setMaximized] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!isNative) return;
|
||||
let off: (() => void) | undefined;
|
||||
const sync = () => win.isMaximized().then(setMaximized);
|
||||
sync();
|
||||
win.onResized(sync).then((u) => (off = u));
|
||||
return () => off?.();
|
||||
}, []);
|
||||
if (!isNative) return null;
|
||||
return (
|
||||
<div className="window-controls">
|
||||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label={maximized ? 'Restore' : 'Maximize'} onClick={() => win.toggleMaximize()}>
|
||||
<Icon name={maximized ? 'restore' : 'maximize'} size={13} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
||||
<Icon name="x" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Avatar() {
|
||||
const user = useSession((s) => s.user);
|
||||
const server = useSession((s) => s.server);
|
||||
const connection = useSession((s) => s.connection);
|
||||
const showServerPicker = useSession((s) => s.showServerPicker);
|
||||
const signOut = useSession((s) => s.signOut);
|
||||
const home = useHomeUsers();
|
||||
const initial = (user?.title || server?.name || 'K').slice(0, 1).toUpperCase();
|
||||
const menu = (el: HTMLElement) => {
|
||||
const items: MenuItem[] = [
|
||||
{ heading: user ? user.title : 'Kaleido' },
|
||||
{
|
||||
label: server ? `${server.name}` : 'No server',
|
||||
hint: connection ? (connection.relay ? 'Relay' : connection.local ? 'Local' : 'Remote') : '',
|
||||
icon: 'server',
|
||||
onSelect: showServerPicker,
|
||||
},
|
||||
];
|
||||
if (home.users.length > 1) {
|
||||
items.push({
|
||||
label: 'Switch profile',
|
||||
icon: 'users',
|
||||
submenu: home.users.map((u) => ({ label: u.title, checked: u.uuid === user?.uuid, onSelect: () => home.switchTo(u) })),
|
||||
});
|
||||
}
|
||||
items.push(
|
||||
{ divider: true },
|
||||
{ label: 'Settings', icon: 'settings', onSelect: () => navigate({ name: 'settings', mode: 'app', tab: 'general' }) },
|
||||
);
|
||||
if (server?.owned) items.push({ label: 'Server dashboard', icon: 'activity', onSelect: () => navigate({ name: 'settings', mode: 'server', tab: 'dashboard' }) });
|
||||
items.push({ divider: true }, { label: 'Sign out', icon: 'logout', onSelect: signOut });
|
||||
openMenu(items, el, { align: 'end', minWidth: 250 });
|
||||
};
|
||||
return (
|
||||
<button className="avatar-btn" aria-label="Account" onClick={(e) => menu(e.currentTarget)}>
|
||||
{user?.thumb ? <img src={user.thumb} alt="" draggable={false} /> : <span>{initial}</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function TopBar({ solid }: { solid: boolean }) {
|
||||
const current = useRouter((s) => s.current.route);
|
||||
const canBack = useRouter((s) => s.index > 0);
|
||||
const back = useRouter((s) => s.back);
|
||||
const active = topLevel(current);
|
||||
const activeDownloads = useDownloads((s) => s.items.filter((d) => d.status === 'downloading' || d.status === 'queued').length);
|
||||
const startPage = useSettings((s) => s.startPage);
|
||||
void startPage;
|
||||
const showBack = canBack && !active;
|
||||
|
||||
return (
|
||||
<header className={`topbar${solid ? ' solid' : ''}`} data-tauri-drag-region>
|
||||
<div className="topbar-left" data-tauri-drag-region>
|
||||
<button className={`nav-back${showBack ? ' show' : ''}`} aria-label="Back" onClick={back} tabIndex={showBack ? 0 : -1}>
|
||||
<Icon name="arrowLeft" size={19} />
|
||||
</button>
|
||||
<button className="brand" onClick={() => navigate({ name: 'home' })} aria-label="Kaleido home">
|
||||
<KaleidoMark size={24} />
|
||||
<span>KALEIDO</span>
|
||||
</button>
|
||||
<nav className="primary-nav" aria-label="Main navigation" data-tauri-drag-region>
|
||||
{NAV.map((n) => (
|
||||
<button key={n.id} className={`nav-item${active === n.id ? ' active' : ''}`} onClick={() => navigate(n.route)}>
|
||||
{n.label}
|
||||
{n.id === 'downloads' && activeDownloads > 0 && <span className="nav-count">{activeDownloads}</span>}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
<div className="topbar-right" data-tauri-drag-region>
|
||||
<button className={`icon-btn${active === 'search' ? ' on' : ''}`} aria-label="Search" title="Search (Ctrl+K)" onClick={() => navigate({ name: 'search' })}>
|
||||
<Icon name="search" size={19} />
|
||||
</button>
|
||||
<button className={`icon-btn${active === 'settings' ? ' on' : ''}`} aria-label="Settings" title="Settings" onClick={() => navigate({ name: 'settings', mode: 'app', tab: 'general' })}>
|
||||
<Icon name="settings" size={19} />
|
||||
</button>
|
||||
<Avatar />
|
||||
<WindowControls />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
230
src/app/actions.ts
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import { create } from 'zustand';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item } from '../plex/types';
|
||||
import { navigate } from './router';
|
||||
import { useSession } from './session';
|
||||
import { invalidateItem, invalidateLibrary } from './queries';
|
||||
import { isWatched } from './format';
|
||||
import { useSettings } from './settings';
|
||||
import { usePlayer, type PlayOptions } from '../player/store';
|
||||
import { confirmDialog, toast, toastError, type MenuItem } from '../ui/overlays';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
|
||||
const server = () => {
|
||||
const s = useSession.getState().server;
|
||||
if (!s) throw new Error('Not connected to a server.');
|
||||
return s;
|
||||
};
|
||||
|
||||
export const canManage = () => !!useSession.getState().server?.owned;
|
||||
|
||||
export function openItem(item: Item) {
|
||||
if (item.type === 'clip') {
|
||||
playItem(item, { resume: false });
|
||||
return;
|
||||
}
|
||||
if (item.type === 'person') {
|
||||
navigate({ name: 'person', id: item.id, title: item.title, thumb: item.thumb });
|
||||
return;
|
||||
}
|
||||
navigate({ name: 'item', id: item.id, title: item.title });
|
||||
}
|
||||
|
||||
/** Plays a title. Shows and seasons play their next episode. */
|
||||
export async function playItem(item: Item, opts: PlayOptions = {}) {
|
||||
try {
|
||||
if (item.type === 'show' || item.type === 'season') {
|
||||
const s = server();
|
||||
const full = await api.metadata(s, item.id);
|
||||
let next = await api.onDeckFor(s, full);
|
||||
if (!next) {
|
||||
const leaves = await api.allLeaves(s, item.id);
|
||||
next = leaves.find((e) => !isWatched(e)) ?? leaves[0] ?? null;
|
||||
}
|
||||
if (!next) throw new Error('There are no episodes to play.');
|
||||
await usePlayer.getState().play(next, { resume: true, ...opts });
|
||||
return;
|
||||
}
|
||||
if (item.type === 'collection') {
|
||||
const items = await api.collectionItems(server(), item.id);
|
||||
if (items[0]) await playItem(items[0], opts);
|
||||
return;
|
||||
}
|
||||
const local = useDownloads.getState().localFileFor(item.id);
|
||||
if (local && !opts.localFile && !useSession.getState().server) opts = { ...opts, localFile: local };
|
||||
await usePlayer.getState().play(item, { resume: true, ...opts });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function shuffleItem(item: Item) {
|
||||
try {
|
||||
const leaves = await api.allLeaves(server(), item.id);
|
||||
if (!leaves.length) return;
|
||||
const pick = leaves[Math.floor(Math.random() * leaves.length)];
|
||||
await usePlayer.getState().play(pick, { resume: false });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function setWatched(item: Item, watched: boolean) {
|
||||
try {
|
||||
await api.setWatched(server(), item.id, watched);
|
||||
toast(watched ? `Marked “${item.title}” watched` : `Marked “${item.title}” unwatched`, 'success');
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeFromContinueWatching(item: Item) {
|
||||
try {
|
||||
await api.removeFromContinueWatching(server(), item.id);
|
||||
toast('Removed from Continue Watching', 'success');
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function run(label: string, fn: () => Promise<unknown>, done?: string) {
|
||||
try {
|
||||
await fn();
|
||||
if (done) toast(done, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
void label;
|
||||
}
|
||||
|
||||
export const admin = {
|
||||
refresh: (item: Item) =>
|
||||
run('refresh', async () => {
|
||||
await api.refreshMetadata(server(), item.id);
|
||||
setTimeout(() => invalidateItem(item.id), 4000);
|
||||
}, `Refreshing metadata for “${item.title}”`),
|
||||
analyze: (item: Item) => run('analyze', () => api.analyze(server(), item.id), `Analyzing “${item.title}”`),
|
||||
unmatch: async (item: Item) => {
|
||||
if (!(await confirmDialog({ title: 'Unmatch this title?', message: `Plex will remove the metadata for “${item.title}” and show it by its file name until it is matched again.`, confirm: 'Unmatch', danger: true }))) return;
|
||||
await run('unmatch', async () => {
|
||||
await api.unmatch(server(), item.id);
|
||||
invalidateLibrary();
|
||||
}, 'Title unmatched');
|
||||
},
|
||||
split: async (item: Item) => {
|
||||
if (!(await confirmDialog({ title: 'Split apart?', message: `Each version of “${item.title}” will become a separate title.`, confirm: 'Split apart' }))) return;
|
||||
await run('split', async () => {
|
||||
await api.splitApart(server(), item.id);
|
||||
invalidateLibrary();
|
||||
}, 'Versions split apart');
|
||||
},
|
||||
remove: async (item: Item, onDone?: () => void) => {
|
||||
const ok = await confirmDialog({
|
||||
title: `Delete “${item.title}”?`,
|
||||
message: 'This permanently deletes the media files from the server’s disk and removes the title from the library. This cannot be undone.',
|
||||
confirm: 'Delete files',
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.deleteItem(server(), item.id);
|
||||
toast(`Deleted “${item.title}”`, 'success');
|
||||
invalidateLibrary();
|
||||
onDone?.();
|
||||
} catch (e: any) {
|
||||
toast(e?.status === 403 || e?.status === 401 ? 'The server does not allow media deletion. Enable it in Settings › Plex server › Library.' : e.message, 'error');
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// —— Dialog routing ——————————————————————————————————————————————
|
||||
|
||||
export type DialogRequest =
|
||||
| { kind: 'edit'; item: Item }
|
||||
| { kind: 'match'; item: Item }
|
||||
| { kind: 'info'; item: Item }
|
||||
| { kind: 'artwork'; item: Item; type: 'poster' | 'art' | 'clearLogo' }
|
||||
| { kind: 'collection'; item: Item }
|
||||
| { kind: 'playlist'; item: Item }
|
||||
| { kind: 'trailer'; item: Item }
|
||||
| { kind: 'synopsis'; item: Item }
|
||||
| { kind: 'versions'; item: Item; onPick: (index: number) => void };
|
||||
|
||||
export const useDialogs = create<{ dialog: DialogRequest | null; open(d: DialogRequest): void; close(): void }>((set) => ({
|
||||
dialog: null,
|
||||
open: (dialog) => set({ dialog }),
|
||||
close: () => set({ dialog: null }),
|
||||
}));
|
||||
export const openDialog = (d: DialogRequest) => useDialogs.getState().open(d);
|
||||
|
||||
/** Plays with a version choice when a title has several. */
|
||||
export function playWithVersion(item: Item, opts: PlayOptions = {}) {
|
||||
if (item.media.length > 1 && opts.mediaIndex === undefined) {
|
||||
openDialog({ kind: 'versions', item, onPick: (mediaIndex) => playItem(item, { ...opts, mediaIndex }) });
|
||||
return;
|
||||
}
|
||||
playItem(item, opts);
|
||||
}
|
||||
|
||||
/** The full context menu for a title, as on cards and the detail page "More" button. */
|
||||
export function itemMenu(item: Item, ctx: { continueWatching?: boolean; onDeleted?: () => void; detail?: boolean } = {}): MenuItem[] {
|
||||
const owned = canManage();
|
||||
const playable = ['movie', 'episode', 'show', 'season', 'clip'].includes(item.type);
|
||||
const watched = isWatched(item, useSettings.getState().watchedPercent);
|
||||
const downloads = useDownloads.getState();
|
||||
const items: MenuItem[] = [];
|
||||
if (playable) {
|
||||
items.push({ label: item.viewOffset ? 'Resume' : 'Play', icon: 'play', onSelect: () => playWithVersion(item) });
|
||||
if (item.viewOffset) items.push({ label: 'Play from beginning', icon: 'replay10', onSelect: () => playWithVersion(item, { offsetMs: 0, resume: false }) });
|
||||
if (item.type === 'show' || item.type === 'season') items.push({ label: 'Shuffle episodes', icon: 'shuffle', onSelect: () => shuffleItem(item) });
|
||||
}
|
||||
if (!ctx.detail) items.push({ label: 'Details', icon: 'info', onSelect: () => openItem(item) });
|
||||
if (item.type === 'episode') {
|
||||
items.push({ label: 'Go to season', icon: 'layers', onSelect: () => navigate({ name: 'item', id: item.parentId }) });
|
||||
items.push({ label: 'Go to show', icon: 'tv', onSelect: () => navigate({ name: 'item', id: item.grandparentId }) });
|
||||
}
|
||||
if (item.type === 'season') items.push({ label: 'Go to show', icon: 'tv', onSelect: () => navigate({ name: 'item', id: item.parentId }) });
|
||||
if (playable && item.type !== 'clip') {
|
||||
items.push({ divider: true });
|
||||
items.push({ label: watched ? 'Mark unwatched' : 'Mark watched', icon: watched ? 'minus' : 'check', onSelect: () => setWatched(item, !watched) });
|
||||
if (ctx.continueWatching || (item.viewOffset > 0 && !watched)) items.push({ label: 'Remove from Continue Watching', icon: 'x', onSelect: () => removeFromContinueWatching(item) });
|
||||
}
|
||||
if (item.type === 'movie' || item.type === 'episode') {
|
||||
const dl = downloads.items.find((d) => d.id === downloads.idFor(item.id));
|
||||
items.push(
|
||||
dl
|
||||
? { label: dl.status === 'completed' ? 'Downloaded' : 'Downloading…', icon: 'downloaded', onSelect: () => navigate({ name: 'downloads' }) }
|
||||
: { label: 'Download', icon: 'download', onSelect: () => downloads.start(item) },
|
||||
);
|
||||
} else if (item.type === 'season' || item.type === 'show') {
|
||||
items.push({ label: item.type === 'show' ? 'Download all episodes' : 'Download season', icon: 'download', onSelect: () => downloads.startAll(item) });
|
||||
}
|
||||
if (['movie', 'show', 'season', 'episode'].includes(item.type)) {
|
||||
items.push({ label: 'Add to playlist…', icon: 'queue', onSelect: () => openDialog({ kind: 'playlist', item }) });
|
||||
}
|
||||
if (owned && ['movie', 'show'].includes(item.type)) items.push({ label: 'Add to collection…', icon: 'collection', onSelect: () => openDialog({ kind: 'collection', item }) });
|
||||
if (['movie', 'episode'].includes(item.type)) items.push({ label: 'Media info', icon: 'info', onSelect: () => openDialog({ kind: 'info', item }) });
|
||||
if (owned && ['movie', 'show', 'season', 'episode', 'collection'].includes(item.type)) {
|
||||
const manage: MenuItem[] = [
|
||||
{ label: 'Edit metadata…', icon: 'edit', onSelect: () => openDialog({ kind: 'edit', item }) },
|
||||
{ label: 'Change poster…', icon: 'image', onSelect: () => openDialog({ kind: 'artwork', item, type: 'poster' }) },
|
||||
{ label: 'Change background…', icon: 'image', onSelect: () => openDialog({ kind: 'artwork', item, type: 'art' }) },
|
||||
{ label: 'Refresh metadata', icon: 'refresh', onSelect: () => admin.refresh(item) },
|
||||
];
|
||||
if (item.type !== 'collection') manage.push({ label: 'Analyze', icon: 'activity', onSelect: () => admin.analyze(item) });
|
||||
if (item.type === 'movie' || item.type === 'show') {
|
||||
manage.push({ label: 'Fix match…', icon: 'wand', onSelect: () => openDialog({ kind: 'match', item }) });
|
||||
manage.push({ label: 'Unmatch', icon: 'unlink', onSelect: () => admin.unmatch(item) });
|
||||
}
|
||||
if (item.type === 'movie' && item.media.length > 1) manage.push({ label: 'Split apart', icon: 'split', onSelect: () => admin.split(item) });
|
||||
if (item.type !== 'collection') {
|
||||
manage.push({ divider: true });
|
||||
manage.push({ label: 'Delete from server…', icon: 'trash', danger: true, onSelect: () => admin.remove(item, ctx.onDeleted) });
|
||||
}
|
||||
items.push({ divider: true });
|
||||
items.push({ label: 'Manage', icon: 'tool', submenu: manage });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
190
src/app/format.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import type { Item, Media } from '../plex/types';
|
||||
|
||||
export function duration(ms: number): string {
|
||||
if (!ms || ms < 0) return '';
|
||||
const m = Math.round(ms / 60000);
|
||||
if (m < 60) return `${m}m`;
|
||||
const h = Math.floor(m / 60);
|
||||
return m % 60 ? `${h}h ${m % 60}m` : `${h}h`;
|
||||
}
|
||||
|
||||
export function clock(seconds: number, forceHours = false): string {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) seconds = 0;
|
||||
const s = Math.floor(seconds % 60);
|
||||
const m = Math.floor((seconds / 60) % 60);
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return h || forceHours ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
|
||||
}
|
||||
|
||||
export function remaining(item: Item): string {
|
||||
if (!item.duration || !item.viewOffset) return '';
|
||||
const left = Math.max(0, item.duration - item.viewOffset);
|
||||
const m = Math.round(left / 60000);
|
||||
if (m < 1) return 'Almost done';
|
||||
return m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m left` : `${m}m left`;
|
||||
}
|
||||
|
||||
export function episodeLabel(item: Item, long = false): string {
|
||||
if (item.type !== 'episode') return '';
|
||||
if (long) return `Season ${item.parentIndex} · Episode ${item.index}`;
|
||||
return `S${item.parentIndex} · E${item.index}`;
|
||||
}
|
||||
|
||||
export function progress(item: Item): number {
|
||||
if (!item.duration || !item.viewOffset) return 0;
|
||||
return Math.min(1, Math.max(0, item.viewOffset / item.duration));
|
||||
}
|
||||
|
||||
export function isWatched(item: Item, percent = 90): boolean {
|
||||
if (item.type === 'show' || item.type === 'season') return item.leafCount > 0 && item.viewedLeafCount >= item.leafCount;
|
||||
if (item.viewOffset > 0 && item.duration > 0) return item.viewCount > 0 && item.viewOffset / item.duration >= percent / 100;
|
||||
return item.viewCount > 0;
|
||||
}
|
||||
|
||||
export function remainingEpisodes(item: Item): number {
|
||||
return Math.max(0, item.leafCount - item.viewedLeafCount);
|
||||
}
|
||||
|
||||
export function displayTitle(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentTitle || item.title;
|
||||
if (item.type === 'season') return item.parentTitle ? `${item.parentTitle}` : item.title;
|
||||
return item.title;
|
||||
}
|
||||
|
||||
export function subtitleFor(item: Item): string {
|
||||
switch (item.type) {
|
||||
case 'episode':
|
||||
return `${episodeLabel(item)} ${item.title}`;
|
||||
case 'season':
|
||||
return item.title + (item.leafCount ? ` · ${item.leafCount} episodes` : '');
|
||||
case 'show':
|
||||
return [item.year || '', item.childCount ? `${item.childCount} season${item.childCount === 1 ? '' : 's'}` : ''].filter(Boolean).join(' · ');
|
||||
case 'collection':
|
||||
return item.childCount ? `${item.childCount} titles` : 'Collection';
|
||||
case 'clip':
|
||||
return [extraLabel(item), duration(item.duration)].filter(Boolean).join(' · ');
|
||||
default:
|
||||
return [item.year || '', duration(item.duration)].filter(Boolean).join(' · ');
|
||||
}
|
||||
}
|
||||
|
||||
export function extraLabel(item: Item): string {
|
||||
const map: Record<string, string> = {
|
||||
trailer: 'Trailer',
|
||||
behindTheScenes: 'Behind the scenes',
|
||||
deletedScene: 'Deleted scene',
|
||||
featurette: 'Featurette',
|
||||
interview: 'Interview',
|
||||
sceneOrSample: 'Scene',
|
||||
short: 'Short',
|
||||
};
|
||||
return map[item.subtype] ?? (item.type === 'clip' ? 'Extra' : '');
|
||||
}
|
||||
|
||||
/** Image path choices per presentation. */
|
||||
export const art = {
|
||||
poster(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentThumb || item.parentThumb || item.thumb;
|
||||
if (item.type === 'season') return item.thumb || item.parentThumb;
|
||||
return item.thumb;
|
||||
},
|
||||
landscape(item: Item): string {
|
||||
if (item.type === 'episode' || item.type === 'clip') return item.thumb || item.art;
|
||||
return item.art || item.grandparentArt || item.thumb;
|
||||
},
|
||||
backdrop(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentArt || item.art || item.thumb;
|
||||
return item.art || item.grandparentArt || item.thumb;
|
||||
},
|
||||
};
|
||||
|
||||
export function resolutionLabel(m?: Media): string {
|
||||
if (!m) return '';
|
||||
const r = m.videoResolution.toLowerCase();
|
||||
if (r === '4k') return '4K';
|
||||
if (r === 'sd') return 'SD';
|
||||
if (/^\d+$/.test(r)) return `${r}p`;
|
||||
if (m.height >= 2000) return '4K';
|
||||
if (m.height >= 1000) return '1080p';
|
||||
if (m.height >= 700) return '720p';
|
||||
return r.toUpperCase();
|
||||
}
|
||||
|
||||
export function channelLabel(n: number): string {
|
||||
return n === 1 ? 'Mono' : n === 2 ? 'Stereo' : n === 6 ? '5.1' : n === 8 ? '7.1' : n ? `${n} ch` : '';
|
||||
}
|
||||
|
||||
/** Format badges: 4K, HDR flavor, Atmos/5.1 — the facts that matter at a glance. */
|
||||
export function formatBadges(item: Item): string[] {
|
||||
const m = item.media[0];
|
||||
if (!m) return [];
|
||||
const out: string[] = [];
|
||||
const res = resolutionLabel(m);
|
||||
if (res === '4K' || res === '1080p' || res === '720p') out.push(res.toUpperCase());
|
||||
if (m.dynamicRange === 'Dolby Vision') out.push('DOLBY VISION');
|
||||
else if (m.dynamicRange) out.push(m.dynamicRange === 'HDR10' ? 'HDR' : m.dynamicRange);
|
||||
if (m.atmos) out.push('ATMOS');
|
||||
else if (m.audioChannels >= 6) out.push(channelLabel(m.audioChannels));
|
||||
return out;
|
||||
}
|
||||
|
||||
export function technicalLine(m?: Media): string {
|
||||
if (!m) return '';
|
||||
return [
|
||||
m.videoCodec.toUpperCase(),
|
||||
[m.audioCodec.toUpperCase(), channelLabel(m.audioChannels)].filter(Boolean).join(' '),
|
||||
m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
}
|
||||
|
||||
export function fileSize(bytes: number): string {
|
||||
if (!bytes) return '';
|
||||
if (bytes >= 1e12) return `${(bytes / 1e12).toFixed(2)} TB`;
|
||||
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
|
||||
if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`;
|
||||
return `${Math.round(bytes / 1e3)} KB`;
|
||||
}
|
||||
|
||||
export function bitrate(kbps: number): string {
|
||||
if (!kbps) return '';
|
||||
return kbps >= 1000 ? `${(kbps / 1000).toFixed(kbps >= 10000 ? 0 : 1)} Mbps` : `${kbps} kbps`;
|
||||
}
|
||||
|
||||
export function date(value: string | number): string {
|
||||
if (!value) return '';
|
||||
const d = typeof value === 'number' ? new Date(value * 1000) : new Date(value);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
export function relativeTime(seconds: number): string {
|
||||
if (!seconds) return '';
|
||||
const diff = Date.now() / 1000 - seconds;
|
||||
if (diff < 60) return 'just now';
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)} min ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)} hr ago`;
|
||||
if (diff < 86400 * 30) return `${Math.floor(diff / 86400)} days ago`;
|
||||
return date(seconds);
|
||||
}
|
||||
|
||||
export function plural(n: number, word: string, pluralWord = `${word}s`) {
|
||||
return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`;
|
||||
}
|
||||
|
||||
/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */
|
||||
export function washGradient(u: Item['ultraBlur'], strength = 1): string {
|
||||
if (!u) return '';
|
||||
const c = (hex: string, a: number) => {
|
||||
const n = parseInt(hex, 16);
|
||||
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${(a * strength).toFixed(3)})`;
|
||||
};
|
||||
return [
|
||||
`radial-gradient(ellipse at 100% 0%, ${c(u.topRight, 0.95)} 0%, transparent 62%)`,
|
||||
`radial-gradient(ellipse at 0% 0%, ${c(u.topLeft, 0.7)} 0%, transparent 55%)`,
|
||||
`radial-gradient(ellipse at 100% 100%, ${c(u.bottomRight, 0.55)} 0%, transparent 60%)`,
|
||||
`radial-gradient(ellipse at 0% 100%, ${c(u.bottomLeft, 0.45)} 0%, transparent 60%)`,
|
||||
].join(', ');
|
||||
}
|
||||
91
src/app/keyboardNav.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
/**
|
||||
* Arrow-key movement between titles, for keyboard users. Focus moves to the
|
||||
* nearest card in the pressed direction (by on-screen geometry), so it works
|
||||
* the same across shelves, grids, episode lists and people rows.
|
||||
*/
|
||||
const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link';
|
||||
|
||||
function center(r: DOMRect) {
|
||||
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
||||
}
|
||||
|
||||
function nearest(from: HTMLElement, dir: 'left' | 'right' | 'up' | 'down'): HTMLElement | null {
|
||||
const a = from.getBoundingClientRect();
|
||||
const ac = center(a);
|
||||
const scope = from.closest('.main-scroll') ?? document;
|
||||
let best: HTMLElement | null = null;
|
||||
let bestScore = Infinity;
|
||||
for (const el of scope.querySelectorAll<HTMLElement>(TARGETS)) {
|
||||
if (el === from || el.offsetParent === null) continue;
|
||||
const b = el.getBoundingClientRect();
|
||||
const bc = center(b);
|
||||
const dx = bc.x - ac.x;
|
||||
const dy = bc.y - ac.y;
|
||||
let primary: number;
|
||||
let secondary: number;
|
||||
switch (dir) {
|
||||
case 'right':
|
||||
if (b.left < a.right - 4 || Math.abs(dy) > a.height * 0.6) continue;
|
||||
primary = dx;
|
||||
secondary = Math.abs(dy);
|
||||
break;
|
||||
case 'left':
|
||||
if (b.right > a.left + 4 || Math.abs(dy) > a.height * 0.6) continue;
|
||||
primary = -dx;
|
||||
secondary = Math.abs(dy);
|
||||
break;
|
||||
case 'down':
|
||||
if (b.top < a.bottom - 4) continue;
|
||||
primary = dy;
|
||||
secondary = Math.abs(dx);
|
||||
break;
|
||||
case 'up':
|
||||
if (b.bottom > a.top + 4) continue;
|
||||
primary = -dy;
|
||||
secondary = Math.abs(dx);
|
||||
break;
|
||||
}
|
||||
// Prefer the next row/column first, then the closest within it.
|
||||
const score = primary + secondary * (dir === 'up' || dir === 'down' ? 0.35 : 2);
|
||||
if (score < bestScore) {
|
||||
bestScore = score;
|
||||
best = el;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function installKeyboardNav() {
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
|
||||
const target = e.target as HTMLElement;
|
||||
if (document.documentElement.classList.contains('player-open')) return;
|
||||
if (document.querySelector('.menu-layer, .dialog-layer')) return;
|
||||
|
||||
// "/" focuses the nearest search field.
|
||||
if (e.key === '/' && !target.closest('input, textarea')) {
|
||||
const field = document.querySelector<HTMLInputElement>('.lib-search input, .search-field input');
|
||||
if (field) {
|
||||
e.preventDefault();
|
||||
field.focus();
|
||||
field.select();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!target.matches?.(TARGETS)) return;
|
||||
if ((e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) && !target.matches('.shelf-title-link')) {
|
||||
e.preventDefault();
|
||||
const r = target.getBoundingClientRect();
|
||||
target.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: r.left + 24, clientY: r.top + 24 }));
|
||||
return;
|
||||
}
|
||||
const dir = ({ ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down' } as const)[e.key as 'ArrowLeft'];
|
||||
if (!dir) return;
|
||||
const next = nearest(target, dir);
|
||||
if (!next) return;
|
||||
e.preventDefault();
|
||||
next.focus({ preventScroll: true });
|
||||
next.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
|
||||
});
|
||||
}
|
||||
53
src/app/queries.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { QueryClient, useQuery, type UseQueryOptions } from '@tanstack/react-query';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item, Section } from '../plex/types';
|
||||
import { useServer } from './session';
|
||||
import { useSettings } from './settings';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 60_000,
|
||||
gcTime: 30 * 60_000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/** Every key starts with the server so switching servers never mixes caches. */
|
||||
export function useKey(...parts: unknown[]) {
|
||||
const server = useServer();
|
||||
return [server.machineId, ...parts];
|
||||
}
|
||||
|
||||
export function useServerQuery<T>(parts: unknown[], fn: (s: ReturnType<typeof useServer>) => Promise<T>, opts: Partial<UseQueryOptions<T>> = {}) {
|
||||
const server = useServer();
|
||||
return useQuery<T>({ queryKey: [server.machineId, ...parts], queryFn: () => fn(server), ...opts } as UseQueryOptions<T>);
|
||||
}
|
||||
|
||||
export const useSections = () => useServerQuery(['sections'], (s) => api.sections(s), { staleTime: 5 * 60_000 });
|
||||
|
||||
/** The library a Movies or TV destination shows: the user's choice, else the first. */
|
||||
export function useSectionFor(kind: 'movie' | 'show'): { section: Section | null; all: Section[]; loading: boolean } {
|
||||
const { data, isLoading } = useSections();
|
||||
const chosen = useSettings((s) => (kind === 'movie' ? s.movieSection : s.showSection));
|
||||
const all = (data ?? []).filter((s) => s.type === kind && !s.hidden);
|
||||
return { section: all.find((s) => s.id === chosen) ?? all[0] ?? null, all, loading: isLoading };
|
||||
}
|
||||
|
||||
export const useItem = (id: string | undefined, opts: Partial<UseQueryOptions<Item>> = {}) =>
|
||||
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...opts });
|
||||
|
||||
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000 });
|
||||
|
||||
export const useRelated = (id: string | undefined) => useServerQuery(['related', id], (s) => api.related(s, id!), { enabled: !!id, staleTime: 10 * 60_000 });
|
||||
|
||||
/** After a watched-state or metadata change, refresh everything that may show it. */
|
||||
export function invalidateLibrary() {
|
||||
queryClient.invalidateQueries({ predicate: (q) => !['sections', 'libraryMeta', 'filterOptions', 'serverPrefs'].includes(String(q.queryKey[1])) });
|
||||
}
|
||||
|
||||
export function invalidateItem(id: string) {
|
||||
queryClient.invalidateQueries({ predicate: (q) => q.queryKey.includes(id) });
|
||||
}
|
||||
101
src/app/router.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { create } from 'zustand';
|
||||
|
||||
export type SectionKind = 'movie' | 'show';
|
||||
export type SectionTab = 'discover' | 'library' | 'collections';
|
||||
|
||||
export type Route =
|
||||
| { name: 'home' }
|
||||
| { name: 'section'; kind: SectionKind; tab: SectionTab }
|
||||
| { name: 'item'; id: string; title?: string }
|
||||
| { name: 'person'; id: string; title: string; thumb?: string }
|
||||
| { name: 'hub'; key: string; title: string }
|
||||
| { name: 'search'; query?: string }
|
||||
| { name: 'downloads' }
|
||||
| { name: 'settings'; mode: 'app' | 'server'; tab: string };
|
||||
|
||||
export interface Entry {
|
||||
id: number;
|
||||
route: Route;
|
||||
scroll: number;
|
||||
/** Per-screen state to restore on Back (e.g. selected season, library offset). */
|
||||
state: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface RouterState {
|
||||
entries: Entry[];
|
||||
index: number;
|
||||
current: Entry;
|
||||
navigate(route: Route, opts?: { replace?: boolean }): void;
|
||||
back(): void;
|
||||
forward(): void;
|
||||
canBack(): boolean;
|
||||
saveScroll(scroll: number): void;
|
||||
setState(patch: Record<string, unknown>): void;
|
||||
reset(route: Route): void;
|
||||
}
|
||||
|
||||
let nextId = 1;
|
||||
const entry = (route: Route): Entry => ({ id: nextId++, route, scroll: 0, state: {} });
|
||||
const MAX = 60;
|
||||
|
||||
const sameDestination = (a: Route, b: Route) => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
export const useRouter = create<RouterState>((set, get) => {
|
||||
const first = entry({ name: 'home' });
|
||||
return {
|
||||
entries: [first],
|
||||
index: 0,
|
||||
current: first,
|
||||
navigate(route, opts) {
|
||||
const { entries, index } = get();
|
||||
if (sameDestination(entries[index].route, route)) return;
|
||||
const e = entry(route);
|
||||
let next = entries.slice(0, index + 1);
|
||||
if (opts?.replace) next[next.length - 1] = e;
|
||||
else next.push(e);
|
||||
if (next.length > MAX) next = next.slice(next.length - MAX);
|
||||
set({ entries: next, index: next.length - 1, current: e });
|
||||
},
|
||||
back() {
|
||||
const { entries, index } = get();
|
||||
if (index > 0) set({ index: index - 1, current: entries[index - 1] });
|
||||
},
|
||||
forward() {
|
||||
const { entries, index } = get();
|
||||
if (index < entries.length - 1) set({ index: index + 1, current: entries[index + 1] });
|
||||
},
|
||||
canBack: () => get().index > 0,
|
||||
saveScroll(scroll) {
|
||||
get().current.scroll = scroll;
|
||||
},
|
||||
setState(patch) {
|
||||
const cur = get().current;
|
||||
cur.state = { ...cur.state, ...patch };
|
||||
},
|
||||
reset(route) {
|
||||
const e = entry(route);
|
||||
set({ entries: [e], index: 0, current: e });
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const navigate = (route: Route, opts?: { replace?: boolean }) => useRouter.getState().navigate(route, opts);
|
||||
export const goBack = () => useRouter.getState().back();
|
||||
|
||||
/** The top-level destination a route belongs to, for the navigation highlight. */
|
||||
export function topLevel(route: Route): string {
|
||||
switch (route.name) {
|
||||
case 'home':
|
||||
return 'home';
|
||||
case 'section':
|
||||
return route.kind === 'movie' ? 'movies' : 'shows';
|
||||
case 'search':
|
||||
return 'search';
|
||||
case 'downloads':
|
||||
return 'downloads';
|
||||
case 'settings':
|
||||
return 'settings';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
213
src/app/session.ts
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
import { create } from 'zustand';
|
||||
import { appInfo, devSession, isNative, secrets } from '../platform/native';
|
||||
import { configureClient, PlexError, PlexServer } from '../plex/client';
|
||||
import * as account from '../plex/account';
|
||||
import type { PlexUser, ServerResource } from '../plex/types';
|
||||
|
||||
export type Status = 'loading' | 'signed-out' | 'choose-server' | 'connecting' | 'ready' | 'offline';
|
||||
|
||||
interface StoredServer {
|
||||
id: string;
|
||||
name: string;
|
||||
uri: string;
|
||||
owned: boolean;
|
||||
manual?: boolean;
|
||||
}
|
||||
|
||||
interface SessionState {
|
||||
status: Status;
|
||||
error: string;
|
||||
accountToken: string | null;
|
||||
user: PlexUser | null;
|
||||
resources: ServerResource[];
|
||||
server: PlexServer | null;
|
||||
connection: { local: boolean; relay: boolean } | null;
|
||||
init(): Promise<void>;
|
||||
completeSignIn(token: string): Promise<void>;
|
||||
refreshResources(): Promise<ServerResource[]>;
|
||||
chooseServer(resource: ServerResource): Promise<void>;
|
||||
connectManual(uri: string, token: string): Promise<void>;
|
||||
reconnect(): Promise<void>;
|
||||
switchUser(token: string): Promise<void>;
|
||||
showServerPicker(): void;
|
||||
signOut(): Promise<void>;
|
||||
}
|
||||
|
||||
const SERVER_KEY = 'kaleido.server';
|
||||
const loadStoredServer = (): StoredServer | null => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(SERVER_KEY) ?? 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const storeServer = (s: StoredServer | null) => (s ? localStorage.setItem(SERVER_KEY, JSON.stringify(s)) : localStorage.removeItem(SERVER_KEY));
|
||||
|
||||
export const useSession = create<SessionState>((set, get) => ({
|
||||
status: 'loading',
|
||||
error: '',
|
||||
accountToken: null,
|
||||
user: null,
|
||||
resources: [],
|
||||
server: null,
|
||||
connection: null,
|
||||
|
||||
async init() {
|
||||
const info = await appInfo();
|
||||
configureClient({ version: info.version, deviceName: info.deviceName });
|
||||
let token = await secrets.get('account-token');
|
||||
const stored = loadStoredServer();
|
||||
|
||||
if (!token) {
|
||||
const dev = await devSession();
|
||||
if (dev) {
|
||||
// The development token is the owner's account token.
|
||||
try {
|
||||
await account.getUser(dev.token);
|
||||
token = dev.token;
|
||||
await secrets.set('account-token', token);
|
||||
} catch {
|
||||
try {
|
||||
await get().connectManual(dev.server, dev.token);
|
||||
return;
|
||||
} catch {
|
||||
/* fall through to sign-in */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (stored?.manual) {
|
||||
const serverToken = await secrets.get('server-token');
|
||||
if (serverToken) {
|
||||
try {
|
||||
await get().connectManual(stored.uri, serverToken);
|
||||
return;
|
||||
} catch (e: any) {
|
||||
set({ status: 'offline', error: e.message });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
set({ status: 'signed-out' });
|
||||
return;
|
||||
}
|
||||
set({ accountToken: token });
|
||||
try {
|
||||
const user = await account.getUser(token);
|
||||
set({ user });
|
||||
} catch (e: any) {
|
||||
if (e instanceof PlexError && (e.status === 401 || e.status === 403)) {
|
||||
await secrets.delete('account-token');
|
||||
set({ status: 'signed-out', accountToken: null, error: 'Your Plex session has expired. Sign in again.' });
|
||||
return;
|
||||
}
|
||||
// plex.tv unreachable: try the last server directly.
|
||||
if (stored) {
|
||||
const serverToken = (await secrets.get('server-token')) ?? token;
|
||||
try {
|
||||
await get().connectManual(stored.uri, serverToken);
|
||||
return;
|
||||
} catch {
|
||||
/* offline */
|
||||
}
|
||||
}
|
||||
set({ status: 'offline', error: 'Kaleido cannot reach Plex right now. Downloaded titles are still available.' });
|
||||
return;
|
||||
}
|
||||
const resources = await get().refreshResources().catch(() => [] as ServerResource[]);
|
||||
const preferred = resources.find((r) => r.id === stored?.id);
|
||||
if (preferred) {
|
||||
await get().chooseServer(preferred);
|
||||
return;
|
||||
}
|
||||
if (resources.length === 1) {
|
||||
await get().chooseServer(resources[0]);
|
||||
return;
|
||||
}
|
||||
set({ status: resources.length ? 'choose-server' : 'choose-server', error: resources.length ? '' : 'No Plex Media Servers are available to this account.' });
|
||||
},
|
||||
|
||||
async completeSignIn(token) {
|
||||
await secrets.set('account-token', token);
|
||||
set({ accountToken: token, error: '', status: 'connecting' });
|
||||
const user = await account.getUser(token);
|
||||
set({ user });
|
||||
const resources = await get().refreshResources();
|
||||
if (resources.length === 1) await get().chooseServer(resources[0]);
|
||||
else set({ status: 'choose-server' });
|
||||
},
|
||||
|
||||
async refreshResources() {
|
||||
const token = get().accountToken;
|
||||
if (!token) return [];
|
||||
const resources = await account.getResources(token);
|
||||
resources.sort((a, b) => Number(b.owned) - Number(a.owned) || Number(b.presence) - Number(a.presence) || a.name.localeCompare(b.name));
|
||||
set({ resources });
|
||||
return resources;
|
||||
},
|
||||
|
||||
async chooseServer(resource) {
|
||||
set({ status: 'connecting', error: '' });
|
||||
const stored = loadStoredServer();
|
||||
try {
|
||||
const r = await account.connect(resource, stored?.id === resource.id ? stored.uri : undefined);
|
||||
const server = new PlexServer(r.uri, resource.accessToken, r.machineId, resource.name, resource.owned, r.local);
|
||||
storeServer({ id: resource.id, name: resource.name, uri: r.uri, owned: resource.owned });
|
||||
await secrets.set('server-token', resource.accessToken);
|
||||
set({ server, status: 'ready', connection: { local: r.local, relay: r.relay } });
|
||||
} catch (e: any) {
|
||||
set({ status: 'choose-server', error: e.message ?? String(e) });
|
||||
}
|
||||
},
|
||||
|
||||
async connectManual(uri, token) {
|
||||
set({ status: 'connecting', error: '' });
|
||||
const r = await account.connectManual(uri, token);
|
||||
const owned = await account
|
||||
.getUser(token)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
const server = new PlexServer(r.uri, token, r.machineId, r.name, owned, r.local);
|
||||
storeServer({ id: r.machineId, name: r.name, uri: r.uri, owned, manual: !get().accountToken });
|
||||
await secrets.set('server-token', token);
|
||||
set({ server, status: 'ready', connection: { local: r.local, relay: false } });
|
||||
},
|
||||
|
||||
async reconnect() {
|
||||
const { resources, server } = get();
|
||||
const resource = resources.find((r) => r.id === server?.machineId);
|
||||
if (resource) await get().chooseServer(resource);
|
||||
else await get().init();
|
||||
},
|
||||
|
||||
async switchUser(token) {
|
||||
await secrets.set('account-token', token);
|
||||
storeServer(null);
|
||||
set({ accountToken: token, server: null, status: 'connecting' });
|
||||
await get().init();
|
||||
},
|
||||
|
||||
showServerPicker() {
|
||||
set({ status: 'choose-server', error: '' });
|
||||
get().refreshResources().catch(() => {});
|
||||
},
|
||||
|
||||
async signOut() {
|
||||
const token = get().accountToken;
|
||||
if (token && isNative) await account.signOut(token);
|
||||
await secrets.delete('account-token');
|
||||
await secrets.delete('server-token');
|
||||
storeServer(null);
|
||||
set({ status: 'signed-out', accountToken: null, user: null, server: null, resources: [], connection: null, error: '' });
|
||||
},
|
||||
}));
|
||||
|
||||
/** The connected server. Only call beneath screens rendered when status is ready. */
|
||||
export function useServer(): PlexServer {
|
||||
const s = useSession((st) => st.server);
|
||||
if (!s) throw new Error('No server connection');
|
||||
return s;
|
||||
}
|
||||
102
src/app/settings.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
|
||||
export type Quality = 'original' | '2160' | '1080' | '720' | '480';
|
||||
export type SkipMode = 'off' | 'button' | 'auto';
|
||||
export type SubtitleMode = 'auto' | 'always' | 'forced' | 'off';
|
||||
|
||||
export interface Preferences {
|
||||
// Playback
|
||||
quality: Quality;
|
||||
remoteQuality: Quality;
|
||||
hwdec: boolean;
|
||||
hdrPassthrough: boolean;
|
||||
autoplayNext: boolean;
|
||||
countdownSeconds: number;
|
||||
skipIntro: SkipMode;
|
||||
skipCredits: SkipMode;
|
||||
watchedPercent: number;
|
||||
audioLanguage: string;
|
||||
subtitleMode: SubtitleMode;
|
||||
subtitleLanguage: string;
|
||||
subtitleScale: number;
|
||||
subtitleBackground: boolean;
|
||||
volume: number;
|
||||
seekStep: number;
|
||||
// Interface
|
||||
startPage: 'home' | 'movies' | 'shows';
|
||||
colorWash: boolean;
|
||||
reducedMotion: boolean;
|
||||
posterSize: 'compact' | 'comfortable' | 'large';
|
||||
heroRotation: boolean;
|
||||
themeMusic: boolean;
|
||||
themeVolume: number;
|
||||
// Libraries shown for Movies and TV Shows
|
||||
movieSection: string;
|
||||
showSection: string;
|
||||
// Downloads
|
||||
downloadDir: string;
|
||||
// Remembered library views per section
|
||||
libraryViews: Record<string, { sort: string; filters: Record<string, string> }>;
|
||||
}
|
||||
|
||||
export const defaults: Preferences = {
|
||||
quality: 'original',
|
||||
remoteQuality: '1080',
|
||||
hwdec: true,
|
||||
hdrPassthrough: true,
|
||||
autoplayNext: true,
|
||||
countdownSeconds: 8,
|
||||
skipIntro: 'button',
|
||||
skipCredits: 'button',
|
||||
watchedPercent: 90,
|
||||
audioLanguage: '',
|
||||
subtitleMode: 'auto',
|
||||
subtitleLanguage: '',
|
||||
subtitleScale: 1,
|
||||
subtitleBackground: false,
|
||||
volume: 100,
|
||||
seekStep: 10,
|
||||
startPage: 'home',
|
||||
colorWash: true,
|
||||
reducedMotion: false,
|
||||
posterSize: 'comfortable',
|
||||
heroRotation: true,
|
||||
themeMusic: false,
|
||||
themeVolume: 30,
|
||||
movieSection: '',
|
||||
showSection: '',
|
||||
downloadDir: '',
|
||||
libraryViews: {},
|
||||
};
|
||||
|
||||
interface SettingsState extends Preferences {
|
||||
set<K extends keyof Preferences>(key: K, value: Preferences[K]): void;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
export const useSettings = create<SettingsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
...defaults,
|
||||
set: (key, value) => set({ [key]: value } as Partial<SettingsState>),
|
||||
reset: () => set({ ...defaults }),
|
||||
}),
|
||||
{ name: 'kaleido.settings', version: 1 },
|
||||
),
|
||||
);
|
||||
|
||||
export const QUALITY_LABEL: Record<Quality, string> = {
|
||||
original: 'Original quality',
|
||||
'2160': '4K (40 Mbps)',
|
||||
'1080': '1080p (20 Mbps)',
|
||||
'720': '720p (4 Mbps)',
|
||||
'480': '480p (1.5 Mbps)',
|
||||
};
|
||||
|
||||
export const QUALITY_PROFILE: Record<Exclude<Quality, 'original'>, { kbps: number; width: number; height: number }> = {
|
||||
'2160': { kbps: 40000, width: 3840, height: 2160 },
|
||||
'1080': { kbps: 20000, width: 1920, height: 1080 },
|
||||
'720': { kbps: 4000, width: 1280, height: 720 },
|
||||
'480': { kbps: 1500, width: 854, height: 480 },
|
||||
};
|
||||
64
src/app/updater.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
/**
|
||||
* Application updates through Tauri's signed updater. The feed
|
||||
* (`updates/latest.json`) lists a build per platform, so the same flow serves
|
||||
* Windows, macOS and Linux.
|
||||
*/
|
||||
import { create } from 'zustand';
|
||||
import { isNative } from '../platform/native';
|
||||
import { toast } from '../ui/overlays';
|
||||
|
||||
interface UpdaterState {
|
||||
checking: boolean;
|
||||
installing: boolean;
|
||||
progress: number;
|
||||
checkedAt: number;
|
||||
error: string;
|
||||
available: { version: string; notes: string } | null;
|
||||
}
|
||||
|
||||
export const useUpdater = create<UpdaterState>(() => ({
|
||||
checking: false,
|
||||
installing: false,
|
||||
progress: 0,
|
||||
checkedAt: 0,
|
||||
error: '',
|
||||
available: null,
|
||||
}));
|
||||
|
||||
let pending: import('@tauri-apps/plugin-updater').Update | null = null;
|
||||
|
||||
export async function checkForUpdate(manual = false) {
|
||||
if (!isNative || useUpdater.getState().checking) return;
|
||||
useUpdater.setState({ checking: true, error: '' });
|
||||
try {
|
||||
const { check } = await import('@tauri-apps/plugin-updater');
|
||||
const update = await check({ timeout: 15000 });
|
||||
pending = update;
|
||||
useUpdater.setState({ available: update ? { version: update.version, notes: update.body ?? '' } : null, checkedAt: Date.now() });
|
||||
if (update && !manual) toast(`Kaleido ${update.version} is available`, 'info', { label: 'Install', onClick: installUpdate });
|
||||
} catch (e: any) {
|
||||
if (manual) useUpdater.setState({ error: `Couldn’t check for updates: ${e?.message ?? e}` });
|
||||
} finally {
|
||||
useUpdater.setState({ checking: false });
|
||||
}
|
||||
}
|
||||
|
||||
export async function installUpdate() {
|
||||
if (!pending) return;
|
||||
useUpdater.setState({ installing: true, progress: 0 });
|
||||
try {
|
||||
let total = 0;
|
||||
let received = 0;
|
||||
await pending.downloadAndInstall((event) => {
|
||||
if (event.event === 'Started') total = event.data.contentLength ?? 0;
|
||||
else if (event.event === 'Progress') {
|
||||
received += event.data.chunkLength;
|
||||
if (total) useUpdater.setState({ progress: received / total });
|
||||
}
|
||||
});
|
||||
const { relaunch } = await import('@tauri-apps/plugin-process');
|
||||
await relaunch();
|
||||
} catch (e: any) {
|
||||
useUpdater.setState({ installing: false, error: `The update couldn’t be installed: ${e?.message ?? e}` });
|
||||
}
|
||||
}
|
||||
41
src/app/useHomeUsers.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { getHomeUsers, switchHomeUser } from '../plex/account';
|
||||
import type { HomeUser } from '../plex/types';
|
||||
import { promptDialog, toastError } from '../ui/overlays';
|
||||
import { useSession } from './session';
|
||||
import { queryClient } from './queries';
|
||||
|
||||
/** Plex Home profiles available to the signed-in account. */
|
||||
export function useHomeUsers() {
|
||||
const token = useSession((s) => s.accountToken);
|
||||
const home = useSession((s) => s.user?.home);
|
||||
const { data } = useQuery({
|
||||
queryKey: ['homeUsers', token],
|
||||
queryFn: () => getHomeUsers(token!),
|
||||
enabled: !!token && !!home,
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
return {
|
||||
users: data ?? [],
|
||||
async switchTo(u: HomeUser) {
|
||||
try {
|
||||
let pin: string | undefined;
|
||||
if (u.protected) {
|
||||
const v = await promptDialog({
|
||||
title: `Switch to ${u.title}`,
|
||||
message: 'This profile is protected by a PIN.',
|
||||
confirm: 'Switch',
|
||||
input: { label: 'PIN', type: 'password', placeholder: '4-digit PIN' },
|
||||
});
|
||||
if (v === null) return;
|
||||
pin = v;
|
||||
}
|
||||
const next = await switchHomeUser(token!, u.uuid, pin);
|
||||
queryClient.clear();
|
||||
await useSession.getState().switchUser(next);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
1
src/assets/brand-mark.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#C3E8D3" d="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path fill="#71B9B0" d="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path fill="#3D7C7B" d="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path fill="#D0A977" d="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path fill="#E9D8AE" d="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path fill="#EEF2DD" d="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></svg>
|
||||
|
After Width: | Height: | Size: 444 B |
1
src/assets/imdb.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 500"><path fill="#F5C518" d="M197,122.7v255.4h-66.2V122.7h66.2ZM338.4,122.7l-15.3,119.4-9.4-64.9c-2.8-20.8-5.4-39-8-54.5h-85.9v255.4h58.1l.3-168.6,24.4,168.6h41.4l23.3-172.3v172.3h58.1V122.7h-86.7ZM447.7,378.1V122.7h49.4c32.1,0,50.6,1.5,61.9,4.5,11.3,3,19.9,7.8,25.7,14.5,6,6.7,9.7,14.2,11.1,22.4,1.4,8.3,2.4,24.5,2.4,48.7v89.6c0,22.9-1.2,38.3-3.5,45.9-2.1,7.7-5.9,13.7-11.3,18.1-5.3,4.5-12,7.4-19.8,9.2-7.9,1.7-19.8,2.6-35.7,2.6h-80.4ZM513.9,166.4v167.6c9.5,0,15.4-1.9,17.6-5.7,2.2-3.8,3.4-14.2,3.4-31.3v-98.9c0-11.5-.4-18.9-1.1-22.2-.7-3.3-2.5-5.7-5.1-7.2-2.6-1.6-7.6-2.3-14.7-2.3ZM684.7,122.7v83.1c5.3-6.1,11.3-10.6,17.7-13.6,6.6-3.1,16.3-4.6,23.9-4.6s16.4,1.4,22.9,4.1c6.4,2.7,11.3,6.6,14.7,11.5,3.3,5,5.4,9.8,6.1,14.5.7,4.7,1,14.7,1,30.2v71.7c0,15.2-1,26.6-3.1,34.2-2,7.4-6.8,14-14.5,19.4-7.6,5.6-16.7,8.3-27.1,8.3s-17.2-1.6-23.8-4.8c-6.6-3.4-12.5-8.2-17.8-14.7l-4.2,16.2h-59.7V122.7h63.9ZM707.1,250.7c0-10.8-.7-17.8-2.1-21.2-1.4-3.2-6.8-5-10.9-5s-6.4,1.5-7.7,4.3c-1.1,3-1.7,10.2-1.7,21.8v67.5c0,11.3.7,18.4,2,21.5,1.4,3.2,4,4.7,7.9,4.7s9.4-1.6,10.7-4.8c1.2-3.2,1.9-11.1,1.9-23.4v-65.5Z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
1
src/assets/rt-hot.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80"><g transform="translate(10.1 0)"><g transform="translate(0 0)"><path fill="#F9D320" d="M2.53115242,19.0988848 C2.76163569,23.9952416 14.8892193,27.8762825 29.8007435,27.7912268 C42.8237918,27.7168773 53.6874349,24.6411896 56.3485502,20.6004461 C55.7421561,19.9265428 54.904684,19.4643866 53.9613383,19.3391822 C53.9714498,19.220223 53.9779926,19.1003717 53.9773978,18.9787361 C53.9663941,17.0423792 52.5460223,15.4477323 50.695316,15.1503346 C50.7440892,14.8999257 50.7696654,14.6408922 50.7681784,14.3759108 C50.7559851,12.2194796 48.9977695,10.481487 46.8413383,10.4936803 C46.7925651,10.4939777 46.7449814,10.4999257 46.6965056,10.5020074 C46.8344981,10.0987361 46.9118216,9.66780669 46.9094424,9.21784387 C46.8969517,7.06141264 45.1390335,5.32342007 42.9826022,5.33561338 C42.4877323,5.33858736 42.0169517,5.43702602 41.5821561,5.60743494 C40.9653532,4.44639405 39.7811152,3.63717472 38.4002974,3.54379182 C38.1597026,1.60743494 36.5055762,0.113605948 34.506171,0.124843367 C33.247881,0.13204461 32.1350186,0.736356877 31.4263197,1.66453532 C30.7075093,0.882379182 29.6773234,0.391672862 28.5314498,0.398215613 C26.3750186,0.410408922 24.637026,2.16862454 24.6492193,4.32475836 C24.6515985,4.73665428 24.718513,5.13249071 24.8386617,5.50453532 C23.9586617,5.66780669 23.1848327,6.12520446 22.6191822,6.77144981 C22.1701115,5.09888476 20.642974,3.86973978 18.8297398,3.8798513 C17.1357621,3.88966543 15.7040892,4.97873606 15.172342,6.48981413 C13.7332342,7.07182156 12.7202974,8.48356877 12.7298141,10.1302602 C12.7318959,10.4960595 12.7878067,10.8481784 12.8838662,11.1836431 C12.398513,10.9713011 11.8634944,10.852342 11.2996283,10.8556134 C9.5994052,10.8654275 8.16327138,11.9622305 7.63598513,13.4822305 C7.13040892,13.2472862 6.56832714,13.1137546 5.973829,13.1173234 C3.81739777,13.1295167 2.07910781,14.8874349 2.09153162,17.0438662 C2.09546468,17.7549442 2.29263941,18.4187361 2.62810409,18.9909294 C2.59390335,19.0254275 2.56386617,19.063197 2.53115242,19.0988848"/><path fill="#DB382A" d="M50.9736803,68.1576208 C49.8275093,69.89829 47.6002974,71.7008178 45.2692937,72.9026022 L49.2541264,32.4853532 C51.7894424,31.6707807 54.2634944,30.5915242 56.085948,29.0438662 L50.9736803,68.1576208 Z M41.3037918,74.5885502 C37.4450558,75.8655762 35.201487,76.2614126 31.9895911,76.5766543 L32.4901115,35.0432714 C36.0383643,34.9415613 40.6301859,34.4606691 44.5427509,33.6255762 L41.3037918,74.5885502 Z M18.29829,74.5885502 L15.0596283,33.6255762 C18.9718959,34.4606691 23.5637175,34.9415613 27.1119703,35.0432714 L27.6124907,76.5766543 C24.4005948,76.2614126 22.1573234,75.8655762 18.29829,74.5885502 Z M8.62869888,68.1576208 L3.51613383,29.0438662 C5.33858736,30.5915242 7.81263941,31.6707807 10.3479554,32.4853532 L14.3327881,72.9026022 C12.0017844,71.7008178 9.77457249,69.89829 8.62869888,68.1576208 Z M50.687881,13.6110037 C50.7384387,13.8578439 50.7666914,14.1130112 50.7681784,14.3750186 C50.7696654,14.64 50.7440892,14.8990335 50.6950186,15.1494424 C52.5460223,15.4465428 53.9663941,17.0411896 53.9773978,18.9778439 C53.9779926,19.0991822 53.9714498,19.2193309 53.9613383,19.3379926 C54.904684,19.463197 55.7421561,19.9253532 56.3485502,20.5992565 C53.6877323,24.6402974 42.8237918,27.7159851 29.8010409,27.790632 C14.8895167,27.8759851 2.76193309,23.9952416 2.53115242,19.0985874 C2.56386617,19.063197 2.59390335,19.0251301 2.62810409,18.9909294 C2.39791822,18.5983643 2.23910781,18.1608922 2.15702602,17.6966543 C0.729219331,19.0518959 -0.13472119,20.1445353 0.0172490706,21.7356134 C0.0318215613,21.9482528 6.3339777,67.0709294 6.3339777,67.0709294 C7.06111524,74.2173978 17.4388104,79.9292193 29.8010409,80 C42.1632714,79.9292193 52.5412639,74.2173978 53.2681041,67.0709294 C53.2681041,67.0709294 59.5702602,21.9482528 59.5848327,21.7356134 C59.8866914,18.5531599 56.162974,15.6642379 50.687881,13.6110037 L50.687881,13.6110037 Z"/></g><path fill="#FFFFFE" d="M15.0596283,33.6255762 L18.29829,74.5885502 C22.1573234,75.8655762 24.4005948,76.2614126 27.6124907,76.5766543 L27.1119703,35.0432714 C23.5637175,34.9415613 18.9718959,34.4606691 15.0596283,33.6255762"/><path fill="#FFFFFE" d="M31.9895911,76.5766543 C35.201487,76.2614126 37.4447584,75.8655762 41.3037918,74.5885502 L44.5424535,33.6255762 C40.6301859,34.4606691 36.0383643,34.9415613 32.4901115,35.0432714 L31.9895911,76.5766543"/><path fill="#FFFFFE" d="M45.2692937,72.9026022 C47.6002974,71.7008178 49.8275093,69.89829 50.9733829,68.1576208 L56.085948,29.0438662 C54.2634944,30.5915242 51.7894424,31.6707807 49.2541264,32.4853532 L45.2692937,72.9026022"/><path fill="#FFFFFE" d="M3.51613383,29.0438662 L8.62840149,68.1576208 C9.77457249,69.89829 12.0017844,71.7008178 14.3327881,72.9026022 L10.3479554,32.4853532 C7.81263941,31.6707807 5.33858736,30.5915242 3.51613383,29.0438662"/></g></svg>
|
||||
|
After Width: | Height: | Size: 4.7 KiB |
1
src/assets/rt-stale.svg
Normal file
|
After Width: | Height: | Size: 6.2 KiB |
191
src/downloads/store.ts
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
import { create } from 'zustand';
|
||||
import * as api from '../plex/api';
|
||||
import { parseItem } from '../plex/parse';
|
||||
import type { Item } from '../plex/types';
|
||||
import { appInfo, invoke, isNative, listen } from '../platform/native';
|
||||
import { useSession } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { isWatched } from '../app/format';
|
||||
import { toast, toastError } from '../ui/overlays';
|
||||
|
||||
export type DownloadStatus = 'queued' | 'downloading' | 'paused' | 'completed' | 'failed';
|
||||
|
||||
export interface DownloadMeta {
|
||||
serverId: string;
|
||||
serverName: string;
|
||||
ratingKey: string;
|
||||
partKey: string;
|
||||
raw: any;
|
||||
localAssets?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface Download {
|
||||
id: string;
|
||||
filePath: string;
|
||||
total: number;
|
||||
received: number;
|
||||
status: DownloadStatus;
|
||||
error?: string | null;
|
||||
meta: DownloadMeta;
|
||||
createdAt: number;
|
||||
speed: number;
|
||||
}
|
||||
|
||||
interface DownloadsState {
|
||||
items: Download[];
|
||||
ready: boolean;
|
||||
dir: string;
|
||||
init(): Promise<void>;
|
||||
idFor(ratingKey: string, serverId?: string): string;
|
||||
localFileFor(ratingKey: string): string | null;
|
||||
start(item: Item): Promise<void>;
|
||||
startAll(item: Item): Promise<void>;
|
||||
pause(id: string): void;
|
||||
resume(id: string): Promise<void>;
|
||||
remove(id: string): Promise<void>;
|
||||
resumeInterrupted(): void;
|
||||
setDir(dir: string): Promise<void>;
|
||||
itemOf(d: Download): Item;
|
||||
}
|
||||
|
||||
function sanitize(s: string) {
|
||||
return s.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim() || 'Untitled';
|
||||
}
|
||||
|
||||
/** Trims metadata kept for offline display: no extras, related hubs or raw blobs. */
|
||||
function slim(raw: any) {
|
||||
const { Extras, Related, OnDeck, ...rest } = raw ?? {};
|
||||
void Extras;
|
||||
void Related;
|
||||
void OnDeck;
|
||||
return rest;
|
||||
}
|
||||
|
||||
export const useDownloads = create<DownloadsState>((set, get) => ({
|
||||
items: [],
|
||||
ready: false,
|
||||
dir: '',
|
||||
|
||||
async init() {
|
||||
if (!isNative || get().ready) return;
|
||||
const info = await appInfo();
|
||||
const dir = useSettings.getState().downloadDir || info.defaultDownloadDir;
|
||||
await invoke('download_set_dir', { dir }).catch(() => {});
|
||||
const items = await invoke<Download[]>('download_list');
|
||||
set({ items, ready: true, dir });
|
||||
listen<Download>('download', (d) => {
|
||||
const prev = get().items.find((x) => x.id === d.id);
|
||||
set({ items: prev ? get().items.map((x) => (x.id === d.id ? d : x)) : [d, ...get().items] });
|
||||
if (d.status === 'completed' && prev && prev.status !== 'completed') toast(`Downloaded “${d.meta.raw?.title ?? 'title'}”`, 'success');
|
||||
if (d.status === 'failed' && prev?.status !== 'failed' && d.error) toast(d.error, 'error');
|
||||
});
|
||||
listen<string>('download-removed', (id) => set({ items: get().items.filter((x) => x.id !== id) }));
|
||||
},
|
||||
|
||||
idFor(ratingKey, serverId) {
|
||||
const sid = serverId ?? useSession.getState().server?.machineId ?? 'offline';
|
||||
return `${sid}-${ratingKey}`;
|
||||
},
|
||||
|
||||
localFileFor(ratingKey) {
|
||||
const d = get().items.find((x) => x.meta.ratingKey === ratingKey && x.status === 'completed');
|
||||
return d?.filePath ?? null;
|
||||
},
|
||||
|
||||
async start(input) {
|
||||
const server = useSession.getState().server;
|
||||
if (!isNative) {
|
||||
toast('Downloads are available in the Kaleido desktop app.', 'error');
|
||||
return;
|
||||
}
|
||||
if (!server) return;
|
||||
try {
|
||||
await get().init();
|
||||
const item = await api.metadata(server, input.id);
|
||||
const media = item.media[0];
|
||||
const part = media?.parts[0];
|
||||
if (!part) throw new Error('This title has no downloadable file.');
|
||||
const id = get().idFor(item.id);
|
||||
if (get().items.some((d) => d.id === id && d.status !== 'failed')) {
|
||||
toast('This title is already in Downloads.');
|
||||
return;
|
||||
}
|
||||
const ext = part.file.split('.').pop() || part.container || media.container || 'mkv';
|
||||
const baseName = part.file.split(/[\\/]/).pop() || `${item.title}.${ext}`;
|
||||
const folder =
|
||||
item.type === 'episode'
|
||||
? `${sanitize(item.grandparentTitle)}/Season ${item.parentIndex}`
|
||||
: sanitize(item.year ? `${item.title} (${item.year})` : item.title);
|
||||
const assets: Record<string, string> = {};
|
||||
const poster = item.type === 'episode' ? item.grandparentThumb : item.thumb;
|
||||
if (poster) assets.poster = server.image(poster, 360, 540);
|
||||
if (item.type === 'episode' && item.thumb) assets.still = server.image(item.thumb, 640, 360);
|
||||
const backdrop = item.type === 'episode' ? item.grandparentArt : item.art;
|
||||
if (backdrop) assets.art = server.image(backdrop, 1280, 720);
|
||||
if (item.logo) assets.logo = server.image(item.logo, 600, 200, { format: 'png' });
|
||||
await invoke('download_start', {
|
||||
request: {
|
||||
id,
|
||||
url: server.signed(part.key, { download: 1 }),
|
||||
folder,
|
||||
fileName: sanitize(baseName),
|
||||
meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw) } satisfies DownloadMeta,
|
||||
assets,
|
||||
},
|
||||
});
|
||||
toast(`Downloading “${item.type === 'episode' ? `${item.grandparentTitle} · ${item.title}` : item.title}”`, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
},
|
||||
|
||||
async startAll(item) {
|
||||
const server = useSession.getState().server;
|
||||
if (!server) return;
|
||||
try {
|
||||
const leaves = await api.allLeaves(server, item.id);
|
||||
const percent = useSettings.getState().watchedPercent;
|
||||
const todo = leaves.filter((e) => !isWatched(e, percent));
|
||||
const list = todo.length ? todo : leaves;
|
||||
toast(`Queued ${list.length} episode${list.length === 1 ? '' : 's'} for download`, 'success');
|
||||
for (const e of list) await get().start(e);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
},
|
||||
|
||||
pause(id) {
|
||||
invoke('download_pause', { id }).catch(toastError);
|
||||
},
|
||||
|
||||
async resume(id) {
|
||||
const d = get().items.find((x) => x.id === id);
|
||||
const server = useSession.getState().server;
|
||||
if (!d || !server) return;
|
||||
if (server.machineId !== d.meta.serverId) {
|
||||
toast(`Connect to ${d.meta.serverName} to resume this download.`, 'error');
|
||||
return;
|
||||
}
|
||||
await invoke('download_resume', { id, url: server.signed(d.meta.partKey, { download: 1 }) }).catch(toastError);
|
||||
},
|
||||
|
||||
async remove(id) {
|
||||
await invoke('download_remove', { id, deleteFiles: true }).catch(toastError);
|
||||
},
|
||||
|
||||
resumeInterrupted() {
|
||||
const server = useSession.getState().server;
|
||||
if (!server) return;
|
||||
for (const d of get().items) if (d.status === 'paused' && d.error === 'interrupted' && d.meta.serverId === server.machineId) get().resume(d.id);
|
||||
},
|
||||
|
||||
async setDir(dir) {
|
||||
await invoke('download_set_dir', { dir });
|
||||
useSettings.getState().set('downloadDir', dir);
|
||||
set({ dir });
|
||||
},
|
||||
|
||||
itemOf(d) {
|
||||
return parseItem(d.meta.raw ?? {});
|
||||
},
|
||||
}));
|
||||
30
src/main.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import '@fontsource-variable/inter';
|
||||
import './styles/base.css';
|
||||
import './styles/ui.css';
|
||||
import './styles/app.css';
|
||||
import './styles/screens.css';
|
||||
import './styles/player.css';
|
||||
import { App } from './app/App';
|
||||
import { installKeyboardNav } from './app/keyboardNav';
|
||||
import { useSession } from './app/session';
|
||||
import { useRouter } from './app/router';
|
||||
import { usePlayer } from './player/store';
|
||||
import { useSettings } from './app/settings';
|
||||
|
||||
if (import.meta.env.DEV) (window as any).__kaleido = { useSession, useRouter, usePlayer, useSettings };
|
||||
|
||||
// No browser context menu or text-selection chrome outside inputs: this is an app.
|
||||
window.addEventListener('contextmenu', (e) => {
|
||||
const t = e.target as HTMLElement;
|
||||
if (!t.closest('input, textarea, .selectable')) e.preventDefault();
|
||||
});
|
||||
|
||||
installKeyboardNav();
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
161
src/platform/native.ts
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
/**
|
||||
* The boundary between Kaleido and its host. In the desktop app this talks to
|
||||
* the Rust side through Tauri; in a plain browser (used for UI development) it
|
||||
* degrades gracefully: no video, no downloads, tokens in localStorage.
|
||||
*/
|
||||
import type { UnlistenFn } from '@tauri-apps/api/event';
|
||||
|
||||
export const isNative = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
|
||||
|
||||
export async function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
|
||||
if (!isNative) throw new Error(`${cmd} is only available in the desktop app.`);
|
||||
const { invoke } = await import('@tauri-apps/api/core');
|
||||
return invoke<T>(cmd, args);
|
||||
}
|
||||
|
||||
export async function listen<T>(event: string, handler: (payload: T) => void): Promise<UnlistenFn> {
|
||||
if (!isNative) return () => {};
|
||||
const { listen } = await import('@tauri-apps/api/event');
|
||||
return listen<T>(event, (e) => handler(e.payload));
|
||||
}
|
||||
|
||||
/** HTTP for Plex APIs: native requests avoid CORS and local-network limits. */
|
||||
let nativeFetch: typeof fetch | null = null;
|
||||
export async function httpFetch(input: string, init?: RequestInit): Promise<Response> {
|
||||
if (!isNative) return fetch(input, init);
|
||||
if (!nativeFetch) nativeFetch = (await import('@tauri-apps/plugin-http')).fetch as typeof fetch;
|
||||
return nativeFetch(input, init);
|
||||
}
|
||||
|
||||
export const secrets = {
|
||||
async get(key: string): Promise<string | null> {
|
||||
if (!isNative) return localStorage.getItem(`kaleido.dev.secret.${key}`);
|
||||
return invoke<string | null>('secret_get', { key });
|
||||
},
|
||||
async set(key: string, value: string): Promise<void> {
|
||||
if (!isNative) return localStorage.setItem(`kaleido.dev.secret.${key}`, value);
|
||||
await invoke('secret_set', { key, value });
|
||||
},
|
||||
async delete(key: string): Promise<void> {
|
||||
if (!isNative) return localStorage.removeItem(`kaleido.dev.secret.${key}`);
|
||||
await invoke('secret_delete', { key });
|
||||
},
|
||||
};
|
||||
|
||||
export interface AppInfo {
|
||||
version: string;
|
||||
dataDir: string;
|
||||
defaultDownloadDir: string;
|
||||
platform: string;
|
||||
deviceName: string;
|
||||
}
|
||||
|
||||
let info: AppInfo | null = null;
|
||||
export async function appInfo(): Promise<AppInfo> {
|
||||
if (info) return info;
|
||||
info = isNative
|
||||
? await invoke<AppInfo>('app_info')
|
||||
: { version: '0.1.0-dev', dataDir: '', defaultDownloadDir: '', platform: 'browser', deviceName: 'Browser preview' };
|
||||
return info;
|
||||
}
|
||||
|
||||
/** Local development only: start signed in from the Android project's `.env`. */
|
||||
export async function devSession(): Promise<{ server: string; token: string } | null> {
|
||||
if (!import.meta.env.DEV) return null;
|
||||
try {
|
||||
if (isNative) return await invoke<{ server: string; token: string } | null>('dev_session');
|
||||
const r = await fetch('/__dev/session');
|
||||
if (!r.ok) return null;
|
||||
const j = await r.json();
|
||||
return j.server && j.token ? j : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const win = {
|
||||
async current() {
|
||||
const { getCurrentWindow } = await import('@tauri-apps/api/window');
|
||||
return getCurrentWindow();
|
||||
},
|
||||
async minimize() {
|
||||
if (isNative) (await this.current()).minimize();
|
||||
},
|
||||
async toggleMaximize() {
|
||||
if (isNative) (await this.current()).toggleMaximize();
|
||||
},
|
||||
async close() {
|
||||
if (isNative) (await this.current()).close();
|
||||
},
|
||||
async isMaximized() {
|
||||
return isNative ? (await this.current()).isMaximized() : false;
|
||||
},
|
||||
async setFullscreen(on: boolean) {
|
||||
if (isNative) return (await this.current()).setFullscreen(on);
|
||||
if (on) await document.documentElement.requestFullscreen?.().catch(() => {});
|
||||
else if (document.fullscreenElement) await document.exitFullscreen().catch(() => {});
|
||||
},
|
||||
async isFullscreen() {
|
||||
return isNative ? (await this.current()).isFullscreen() : !!document.fullscreenElement;
|
||||
},
|
||||
async show() {
|
||||
if (isNative) {
|
||||
const w = await this.current();
|
||||
await w.show();
|
||||
await w.setFocus();
|
||||
}
|
||||
},
|
||||
async onResized(cb: () => void): Promise<UnlistenFn> {
|
||||
if (!isNative) {
|
||||
window.addEventListener('resize', cb);
|
||||
return () => window.removeEventListener('resize', cb);
|
||||
}
|
||||
return (await this.current()).onResized(cb);
|
||||
},
|
||||
};
|
||||
|
||||
export async function openExternal(url: string) {
|
||||
if (!isNative) {
|
||||
window.open(url, '_blank', 'noopener');
|
||||
return;
|
||||
}
|
||||
const { openUrl } = await import('@tauri-apps/plugin-opener');
|
||||
await openUrl(url);
|
||||
}
|
||||
|
||||
export async function revealPath(path: string) {
|
||||
if (!isNative) return;
|
||||
const { revealItemInDir } = await import('@tauri-apps/plugin-opener');
|
||||
await revealItemInDir(path);
|
||||
}
|
||||
|
||||
export async function pickFolder(defaultPath?: string): Promise<string | null> {
|
||||
if (!isNative) return null;
|
||||
const { open } = await import('@tauri-apps/plugin-dialog');
|
||||
const r = await open({ directory: true, defaultPath, multiple: false });
|
||||
return typeof r === 'string' ? r : null;
|
||||
}
|
||||
|
||||
export async function pickFile(filters?: { name: string; extensions: string[] }[]): Promise<string | null> {
|
||||
if (!isNative) return null;
|
||||
const { open } = await import('@tauri-apps/plugin-dialog');
|
||||
const r = await open({ directory: false, multiple: false, filters });
|
||||
return typeof r === 'string' ? r : null;
|
||||
}
|
||||
|
||||
export async function saveFile(defaultPath: string): Promise<string | null> {
|
||||
if (!isNative) return null;
|
||||
const { save } = await import('@tauri-apps/plugin-dialog');
|
||||
return (await save({ defaultPath })) ?? null;
|
||||
}
|
||||
|
||||
/** Converts a local file path to a URL the web view may load (offline artwork). */
|
||||
export async function localFileUrl(path: string): Promise<string> {
|
||||
if (!isNative || !path) return '';
|
||||
const { convertFileSrc } = await import('@tauri-apps/api/core');
|
||||
return convertFileSrc(path);
|
||||
}
|
||||
|
||||
export function keepAwake(enabled: boolean) {
|
||||
if (isNative) invoke('keep_awake', { enabled }).catch(() => {});
|
||||
}
|
||||
566
src/player/PlayerOverlay.tsx
Normal file
|
|
@ -0,0 +1,566 @@
|
|||
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { usePlayer } from './store';
|
||||
import { useSession } from '../app/session';
|
||||
import { useSettings, QUALITY_LABEL, type Quality } from '../app/settings';
|
||||
import { clock, episodeLabel } from '../app/format';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { Facts, TitleArt } from '../ui/media';
|
||||
import { Button, Spinner } from '../ui/primitives';
|
||||
import { win, isNative } from '../platform/native';
|
||||
import type { Item } from '../plex/types';
|
||||
|
||||
const HIDE_AFTER = 3000;
|
||||
|
||||
function useAutoHide(paused: boolean, pinned: boolean) {
|
||||
const [visible, setVisible] = useState(true);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const poke = useCallback(() => {
|
||||
setVisible(true);
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => setVisible(false), HIDE_AFTER);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (paused || pinned) {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
setVisible(true);
|
||||
} else poke();
|
||||
}, [paused, pinned, poke]);
|
||||
return { visible, poke };
|
||||
}
|
||||
|
||||
function Timeline({ onScrub }: { onScrub: (active: boolean) => void }) {
|
||||
const position = usePlayer((s) => s.position);
|
||||
const duration = usePlayer((s) => s.duration);
|
||||
const cacheTime = usePlayer((s) => s.cacheTime);
|
||||
const chapters = usePlayer((s) => s.chapters);
|
||||
const markers = usePlayer((s) => s.item?.markers ?? []);
|
||||
const seek = usePlayer((s) => s.seek);
|
||||
const previewAt = usePlayer((s) => s.previewAt);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [hover, setHover] = useState<{ x: number; t: number } | null>(null);
|
||||
const [drag, setDrag] = useState<number | null>(null);
|
||||
|
||||
const timeAt = (clientX: number) => {
|
||||
const r = ref.current!.getBoundingClientRect();
|
||||
const f = Math.min(1, Math.max(0, (clientX - r.left) / r.width));
|
||||
return { f, t: f * duration, x: clientX - r.left };
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (drag === null) return;
|
||||
const move = (e: PointerEvent) => {
|
||||
const { t, x } = timeAt(e.clientX);
|
||||
setDrag(t);
|
||||
setHover({ x, t });
|
||||
};
|
||||
const up = (e: PointerEvent) => {
|
||||
const { t } = timeAt(e.clientX);
|
||||
seek(t);
|
||||
setDrag(null);
|
||||
setHover(null);
|
||||
onScrub(false);
|
||||
};
|
||||
window.addEventListener('pointermove', move);
|
||||
window.addEventListener('pointerup', up, { once: true });
|
||||
return () => {
|
||||
window.removeEventListener('pointermove', move);
|
||||
window.removeEventListener('pointerup', up);
|
||||
};
|
||||
}, [drag !== null]);
|
||||
|
||||
const shown = drag ?? position;
|
||||
const pct = duration ? (shown / duration) * 100 : 0;
|
||||
const buffered = duration ? Math.min(100, (Math.max(cacheTime, position) / duration) * 100) : 0;
|
||||
const preview = hover ? previewAt(hover.t) : '';
|
||||
const chapter = hover ? [...chapters].reverse().find((c) => c.time <= hover.t) : null;
|
||||
const width = ref.current?.clientWidth ?? 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`timeline${drag !== null ? ' dragging' : ''}`}
|
||||
ref={ref}
|
||||
onPointerMove={(e) => {
|
||||
if (drag === null && duration) {
|
||||
const { t, x } = timeAt(e.clientX);
|
||||
setHover({ x, t });
|
||||
}
|
||||
}}
|
||||
onPointerLeave={() => drag === null && setHover(null)}
|
||||
onPointerDown={(e) => {
|
||||
if (!duration) return;
|
||||
e.preventDefault();
|
||||
const { t, x } = timeAt(e.clientX);
|
||||
setDrag(t);
|
||||
setHover({ x, t });
|
||||
onScrub(true);
|
||||
}}
|
||||
role="slider"
|
||||
aria-label="Seek"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={Math.round(duration)}
|
||||
aria-valuenow={Math.round(position)}
|
||||
>
|
||||
<div className="timeline-track">
|
||||
<div className="timeline-buffered" style={{ width: `${buffered}%` }} />
|
||||
<div className="timeline-played" style={{ width: `${pct}%` }} />
|
||||
{duration > 0 &&
|
||||
markers
|
||||
.filter((m) => m.type === 'intro' || m.type === 'credits')
|
||||
.map((m) => <div key={m.id + m.start} className={`timeline-marker ${m.type}`} style={{ left: `${(m.start / 1000 / duration) * 100}%`, width: `${((m.end - m.start) / 1000 / duration) * 100}%` }} />)}
|
||||
{duration > 0 && chapters.slice(1).map((c) => <div key={c.time} className="timeline-chapter" style={{ left: `${(c.time / duration) * 100}%` }} />)}
|
||||
</div>
|
||||
<div className="timeline-thumb" style={{ left: `${pct}%` }} />
|
||||
{hover && (
|
||||
<div className="timeline-preview" style={{ left: Math.min(Math.max(hover.x, 110), width - 110) }}>
|
||||
{preview && <img src={preview} alt="" draggable={false} />}
|
||||
<div className="timeline-preview-text">
|
||||
{chapter && chapters.length > 1 && <span>{chapter.title}</span>}
|
||||
<b>{clock(hover.t, duration >= 3600)}</b>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Panel({ title, onClose, children, className = '' }: { title: string; onClose: () => void; children: ReactNode; className?: string }) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
return () => window.removeEventListener('keydown', onKey, true);
|
||||
}, [onClose]);
|
||||
return (
|
||||
<div className={`player-panel ${className}`} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<div className="player-panel-title">{title}</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Option({ selected, label, detail, onClick }: { selected: boolean; label: string; detail?: string; onClick: () => void }) {
|
||||
return (
|
||||
<button className={`panel-option${selected ? ' selected' : ''}`} onClick={onClick}>
|
||||
<span className="panel-check">{selected && <Icon name="check" size={16} />}</span>
|
||||
<span className="panel-label">
|
||||
{label}
|
||||
{detail && <small>{detail}</small>}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function TracksPanel({ onClose }: { onClose: () => void }) {
|
||||
const st = usePlayer();
|
||||
return (
|
||||
<Panel title="Audio & Subtitles" onClose={onClose} className="tracks">
|
||||
<div className="panel-columns">
|
||||
<div>
|
||||
<h4>Audio</h4>
|
||||
{st.audioTracks.map((t) => (
|
||||
<Option key={t.key} selected={t.key === st.audioKey} label={t.label} detail={t.detail} onClick={() => st.selectAudio(t.key)} />
|
||||
))}
|
||||
{!st.audioTracks.length && <div className="panel-empty">No audio tracks</div>}
|
||||
</div>
|
||||
<div>
|
||||
<h4>Subtitles</h4>
|
||||
<Option selected={!st.subKey} label="Off" onClick={() => st.selectSubtitle('')} />
|
||||
{st.subTracks.map((t) => (
|
||||
<Option key={t.key} selected={t.key === st.subKey} label={t.label} detail={t.detail} onClick={() => st.selectSubtitle(t.key)} />
|
||||
))}
|
||||
{st.subKey && st.delivery?.mode !== 'transcode' && (
|
||||
<div className="panel-delay">
|
||||
<span>Timing</span>
|
||||
<button onClick={() => st.setSubDelay(st.subDelay - 0.1)}>−</button>
|
||||
<b>{st.subDelay > 0 ? '+' : ''}{st.subDelay.toFixed(1)}s</b>
|
||||
<button onClick={() => st.setSubDelay(st.subDelay + 0.1)}>+</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function SettingsPanel({ onClose }: { onClose: () => void }) {
|
||||
const st = usePlayer();
|
||||
const [view, setView] = useState<'main' | 'quality' | 'speed' | 'version' | 'chapters'>('main');
|
||||
const speeds = [0.5, 0.75, 1, 1.25, 1.5, 2];
|
||||
const media = st.item?.media ?? [];
|
||||
const local = st.delivery?.mode === 'local';
|
||||
if (view === 'quality')
|
||||
return (
|
||||
<Panel title="Quality" onClose={onClose}>
|
||||
{(Object.keys(QUALITY_LABEL) as Quality[]).map((q) => (
|
||||
<Option key={q} selected={st.quality === q} label={QUALITY_LABEL[q]} detail={q === 'original' ? 'Direct play of the source file' : 'Converted by your Plex server'} onClick={() => (st.setQuality(q), onClose())} />
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
if (view === 'speed')
|
||||
return (
|
||||
<Panel title="Playback speed" onClose={onClose}>
|
||||
{speeds.map((s) => (
|
||||
<Option key={s} selected={Math.abs(st.speed - s) < 0.01} label={s === 1 ? 'Normal' : `${s}×`} onClick={() => (st.setSpeed(s), onClose())} />
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
if (view === 'version')
|
||||
return (
|
||||
<Panel title="Version" onClose={onClose}>
|
||||
{media.map((m, i) => (
|
||||
<Option key={m.id} selected={st.mediaIndex === i} label={m.title || `${m.videoResolution.toUpperCase()} ${m.videoCodec.toUpperCase()}`} detail={[m.container.toUpperCase(), m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : ''].filter(Boolean).join(' · ')} onClick={() => (st.selectVersion(i), onClose())} />
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
if (view === 'chapters')
|
||||
return (
|
||||
<Panel title="Chapters" onClose={onClose} className="chapters">
|
||||
{st.chapters.map((c) => (
|
||||
<Option key={c.time} selected={false} label={c.title} detail={clock(c.time)} onClick={() => (st.seek(c.time), onClose())} />
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
const row = (label: string, value: string, go: () => void, disabled = false) => (
|
||||
<button className="panel-row" onClick={go} disabled={disabled}>
|
||||
<span>{label}</span>
|
||||
<b>{value}</b>
|
||||
<Icon name="next" size={14} />
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<Panel title="Playback" onClose={onClose}>
|
||||
{!local && row('Quality', QUALITY_LABEL[st.quality], () => setView('quality'))}
|
||||
{row('Speed', st.speed === 1 ? 'Normal' : `${st.speed}×`, () => setView('speed'))}
|
||||
{media.length > 1 && !local && row('Version', `${st.mediaIndex + 1} of ${media.length}`, () => setView('version'))}
|
||||
{st.chapters.length > 1 && row('Chapters', `${st.chapters.length}`, () => setView('chapters'))}
|
||||
<div className="panel-info">
|
||||
{st.delivery?.mode === 'direct' && 'Direct play'}
|
||||
{st.delivery?.mode === 'transcode' && `Converting to ${st.delivery.label}`}
|
||||
{st.delivery?.mode === 'local' && 'Playing from this computer'}
|
||||
{st.video && st.video.width > 0 && ` · ${st.video.width}×${st.video.height}`}
|
||||
{st.video?.codec && ` · ${st.video.codec.toUpperCase()}`}
|
||||
{st.video?.hwdec && st.video.hwdec !== 'no' ? ' · Hardware decoding' : ''}
|
||||
</div>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function Volume() {
|
||||
const volume = usePlayer((s) => s.volume);
|
||||
const muted = usePlayer((s) => s.muted);
|
||||
const setVolume = usePlayer((s) => s.setVolume);
|
||||
const toggleMute = usePlayer((s) => s.toggleMute);
|
||||
const icon = muted || volume === 0 ? 'mute' : volume < 50 ? 'volumeLow' : 'volume';
|
||||
return (
|
||||
<div className="volume">
|
||||
<button className="player-icon" aria-label={muted ? 'Unmute' : 'Mute'} onClick={toggleMute}>
|
||||
<Icon name={icon} size={22} />
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
value={muted ? 0 : Math.min(100, volume)}
|
||||
onChange={(e) => setVolume(Number(e.target.value))}
|
||||
style={{ ['--v' as string]: `${muted ? 0 : Math.min(100, volume)}%` }}
|
||||
aria-label="Volume"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SkipButton() {
|
||||
const item = usePlayer((s) => s.item);
|
||||
const position = usePlayer((s) => s.position);
|
||||
const seek = usePlayer((s) => s.seek);
|
||||
const nextUp = usePlayer((s) => s.nextUp);
|
||||
const countdown = usePlayer((s) => s.countdown);
|
||||
const skipIntro = useSettings((s) => s.skipIntro);
|
||||
const skipCredits = useSettings((s) => s.skipCredits);
|
||||
const autoSkipped = useRef(new Set<string>());
|
||||
const ms = position * 1000;
|
||||
const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000);
|
||||
const mode = marker?.type === 'intro' ? skipIntro : skipCredits;
|
||||
useEffect(() => {
|
||||
if (marker && mode === 'auto' && !autoSkipped.current.has(marker.id + marker.start) && !(marker.type === 'credits' && nextUp)) {
|
||||
autoSkipped.current.add(marker.id + marker.start);
|
||||
seek(marker.end / 1000);
|
||||
}
|
||||
}, [marker?.id, marker?.start, mode]);
|
||||
if (!marker || mode === 'off' || countdown !== null) return null;
|
||||
if (marker.type === 'credits' && nextUp) return null;
|
||||
return (
|
||||
<button className="skip-button" onClick={() => seek(marker.end / 1000)}>
|
||||
{marker.type === 'intro' ? 'Skip intro' : 'Skip credits'}
|
||||
<Icon name="skipNext" size={16} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function PostPlay() {
|
||||
const server = useSession((s) => s.server);
|
||||
const nextUp = usePlayer((s) => s.nextUp);
|
||||
const countdown = usePlayer((s) => s.countdown);
|
||||
const playNext = usePlayer((s) => s.playNext);
|
||||
const cancel = usePlayer((s) => s.cancelCountdown);
|
||||
if (!nextUp || countdown === null || !server) return null;
|
||||
return (
|
||||
<div className="post-play" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<div className="post-play-art">
|
||||
<img src={server.image(nextUp.thumb, 360, 202)} alt="" draggable={false} />
|
||||
{countdown > 0 && (
|
||||
<svg className="post-play-ring" viewBox="0 0 40 40">
|
||||
<circle cx="20" cy="20" r="17" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
<div className="post-play-text">
|
||||
<span className="micro">Next episode{countdown > 0 ? ` in ${countdown}` : ''}</span>
|
||||
<b>
|
||||
{episodeLabel(nextUp)} · {nextUp.title}
|
||||
</b>
|
||||
<div className="actions">
|
||||
<Button variant="primary" size="sm" icon="play" onClick={playNext}>
|
||||
Play now
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={cancel}>
|
||||
{countdown > 0 ? 'Cancel' : 'Dismiss'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TitleBlock({ item }: { item: Item }) {
|
||||
return (
|
||||
<div className="player-title">
|
||||
<TitleArt item={item.type === 'episode' ? { ...item, logo: item.raw?.Image?.find?.((i: any) => i.type === 'clearLogo')?.url ?? '' } : item} maxWidth={240} maxHeight={60} as="h2" />
|
||||
{item.type === 'episode' && (
|
||||
<div className="player-episode">
|
||||
{episodeLabel(item)} · {item.title}
|
||||
</div>
|
||||
)}
|
||||
{item.type !== 'clip' && <Facts item={item} withFormats={false} episode={false} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlayerOverlay() {
|
||||
const st = usePlayer();
|
||||
const server = useSession((s) => s.server);
|
||||
const [panel, setPanel] = useState<'' | 'tracks' | 'settings'>('');
|
||||
const [scrubbing, setScrubbing] = useState(false);
|
||||
const [flash, setFlash] = useState<{ icon: string; key: number } | null>(null);
|
||||
const { visible, poke } = useAutoHide(st.paused || st.ended, !!panel || scrubbing || st.countdown !== null);
|
||||
const clickTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const seekStep = useSettings((s) => s.seekStep);
|
||||
|
||||
const showFlash = (icon: string) => setFlash({ icon, key: Date.now() });
|
||||
|
||||
useEffect(() => {
|
||||
if (!st.open) setPanel('');
|
||||
}, [st.open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!st.open) return;
|
||||
const onKey = async (e: KeyboardEvent) => {
|
||||
if ((e.target as HTMLElement)?.tagName === 'INPUT' && (e.target as HTMLInputElement).type !== 'range') return;
|
||||
const p = usePlayer.getState();
|
||||
let handled = true;
|
||||
switch (e.key) {
|
||||
case ' ':
|
||||
case 'k':
|
||||
case 'K':
|
||||
p.togglePause();
|
||||
showFlash(p.paused ? 'play' : 'pause');
|
||||
break;
|
||||
case 'ArrowLeft':
|
||||
case 'j':
|
||||
case 'J':
|
||||
p.seekBy(e.shiftKey ? -60 : e.key === 'ArrowLeft' ? -seekStep : -10);
|
||||
showFlash('replay10');
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
case 'l':
|
||||
case 'L':
|
||||
p.seekBy(e.shiftKey ? 60 : e.key === 'ArrowRight' ? seekStep : 10);
|
||||
showFlash('forward10');
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
p.setVolume(p.volume + 5);
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
p.setVolume(p.volume - 5);
|
||||
break;
|
||||
case 'm':
|
||||
case 'M':
|
||||
p.toggleMute();
|
||||
break;
|
||||
case 'f':
|
||||
case 'F':
|
||||
case 'F11':
|
||||
p.toggleFullscreen();
|
||||
break;
|
||||
case 'n':
|
||||
case 'N':
|
||||
if (e.shiftKey && p.nextUp) p.playNext();
|
||||
else handled = false;
|
||||
break;
|
||||
case 'c':
|
||||
case 'C': {
|
||||
const subs = p.subTracks;
|
||||
const i = subs.findIndex((t) => t.key === p.subKey);
|
||||
p.selectSubtitle(i + 1 < subs.length ? subs[i + 1].key : '');
|
||||
break;
|
||||
}
|
||||
case 'Escape': {
|
||||
const fs = await win.isFullscreen().catch(() => false);
|
||||
if (fs) p.toggleFullscreen();
|
||||
else p.close();
|
||||
break;
|
||||
}
|
||||
case 'Backspace':
|
||||
p.close();
|
||||
break;
|
||||
case 'Home':
|
||||
p.seek(0);
|
||||
break;
|
||||
default:
|
||||
if (/^[0-9]$/.test(e.key) && p.duration) p.seek((Number(e.key) / 10) * p.duration);
|
||||
else handled = false;
|
||||
}
|
||||
if (handled) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
poke();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [st.open, seekStep, poke]);
|
||||
|
||||
if (!st.open || !st.item) return null;
|
||||
const item = st.item;
|
||||
const loading = !st.firstFrame && !st.error;
|
||||
const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art;
|
||||
const hideChrome = !visible && !loading && !st.error;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`player${hideChrome ? ' idle' : ''}${loading ? ' loading' : ''}`}
|
||||
onMouseMove={poke}
|
||||
onClick={() => {
|
||||
if (panel) return setPanel('');
|
||||
if (clickTimer.current) return;
|
||||
clickTimer.current = setTimeout(() => {
|
||||
clickTimer.current = null;
|
||||
if (!loading && !st.error) {
|
||||
st.togglePause();
|
||||
showFlash(st.paused ? 'play' : 'pause');
|
||||
}
|
||||
}, 220);
|
||||
}}
|
||||
onDoubleClick={() => {
|
||||
if (clickTimer.current) clearTimeout(clickTimer.current);
|
||||
clickTimer.current = null;
|
||||
st.toggleFullscreen();
|
||||
}}
|
||||
onWheel={(e) => st.setVolume(st.volume + (e.deltaY < 0 ? 5 : -5))}
|
||||
>
|
||||
{(loading || st.error) && server && (
|
||||
<div className="player-cover">
|
||||
{art && <img src={server.image(art, 1280, 720, { blur: 0 })} alt="" />}
|
||||
<div className="player-cover-scrim" />
|
||||
</div>
|
||||
)}
|
||||
<div className="player-gradient top" />
|
||||
<div className="player-gradient bottom" />
|
||||
|
||||
<div className="player-top" data-tauri-drag-region={isNative ? true : undefined} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<button className="player-back" onClick={() => st.close()} aria-label="Back">
|
||||
<Icon name="arrowLeft" size={22} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{(loading || st.buffering || st.seeking) && !st.error && (
|
||||
<div className="player-center">
|
||||
<Spinner size={44} />
|
||||
</div>
|
||||
)}
|
||||
{flash && !loading && (
|
||||
<div className="player-flash" key={flash.key}>
|
||||
<Icon name={flash.icon} size={34} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{st.error && (
|
||||
<div className="player-error" onClick={(e) => e.stopPropagation()}>
|
||||
<Icon name="alert" size={28} />
|
||||
<h2>Playback stopped</h2>
|
||||
<p>{st.error}</p>
|
||||
<div className="actions">
|
||||
<Button variant="primary" icon="refresh" onClick={() => st.play(item, { offsetMs: st.position * 1000, quality: st.quality === 'original' ? '1080' : st.quality })}>
|
||||
Try converting
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => st.close()}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<SkipButton />
|
||||
<PostPlay />
|
||||
|
||||
{!st.error && (
|
||||
<div className="player-bottom" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<div className="player-bottom-head">
|
||||
<TitleBlock item={item} />
|
||||
<div className="player-delivery">{st.delivery?.mode === 'transcode' ? st.delivery.label : st.delivery?.mode === 'local' ? 'Offline' : ''}</div>
|
||||
</div>
|
||||
<Timeline onScrub={setScrubbing} />
|
||||
<div className="player-controls">
|
||||
<div className="player-controls-left">
|
||||
<button className="player-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
|
||||
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={26} />
|
||||
</button>
|
||||
<button className="player-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
|
||||
<Icon name="replay10" size={24} />
|
||||
</button>
|
||||
<button className="player-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
|
||||
<Icon name="forward10" size={24} />
|
||||
</button>
|
||||
{st.nextUp && (
|
||||
<button className="player-icon" aria-label="Next episode" title={`Next: ${episodeLabel(st.nextUp)} ${st.nextUp.title}`} onClick={() => st.playNext()}>
|
||||
<Icon name="skipNext" size={22} />
|
||||
</button>
|
||||
)}
|
||||
<Volume />
|
||||
<span className="player-time">
|
||||
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="player-controls-right">
|
||||
<button className={`player-icon${panel === 'tracks' ? ' on' : ''}${st.subKey ? ' lit' : ''}`} aria-label="Audio and subtitles" onClick={() => setPanel(panel === 'tracks' ? '' : 'tracks')}>
|
||||
<Icon name="captions" size={23} />
|
||||
</button>
|
||||
<button className={`player-icon${panel === 'settings' ? ' on' : ''}`} aria-label="Playback settings" onClick={() => setPanel(panel === 'settings' ? '' : 'settings')}>
|
||||
<Icon name="settings" size={22} />
|
||||
</button>
|
||||
<button className="player-icon" aria-label={st.fullscreen ? 'Exit full screen' : 'Full screen'} onClick={() => st.toggleFullscreen()}>
|
||||
<Icon name={st.fullscreen ? 'collapse' : 'expand'} size={21} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{panel === 'tracks' && <TracksPanel onClose={() => setPanel('')} />}
|
||||
{panel === 'settings' && <SettingsPanel onClose={() => setPanel('')} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
src/player/engine.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/** Thin typed wrapper over the native mpv commands and its event stream. */
|
||||
import { invoke, isNative, listen } from '../platform/native';
|
||||
|
||||
export interface MpvTrack {
|
||||
id: number;
|
||||
type: 'video' | 'audio' | 'sub';
|
||||
title?: string;
|
||||
lang?: string;
|
||||
codec?: string;
|
||||
default?: boolean;
|
||||
forced?: boolean;
|
||||
external?: boolean;
|
||||
selected?: boolean;
|
||||
'ff-index'?: number;
|
||||
'demux-channel-count'?: number;
|
||||
'external-filename'?: string;
|
||||
}
|
||||
|
||||
export type MpvEvent =
|
||||
| { type: 'property'; name: string; value: any }
|
||||
| { type: 'start-file' | 'file-loaded' | 'playback-restart' | 'seek' }
|
||||
| { type: 'end-file'; reason: string; error?: string | null }
|
||||
| { type: 'log'; level: string; prefix: string; text: string };
|
||||
|
||||
let initialized: Promise<void> | null = null;
|
||||
|
||||
export const mpv = {
|
||||
available: isNative,
|
||||
init(options: { hwdec: boolean; hdr: boolean }) {
|
||||
if (!initialized) {
|
||||
initialized = invoke<void>('player_init', { options: { hwdec: options.hwdec ? 'auto-safe' : 'no', hdr: options.hdr, extra: [] } }).catch((e) => {
|
||||
initialized = null;
|
||||
throw e;
|
||||
});
|
||||
}
|
||||
return initialized;
|
||||
},
|
||||
command: (...args: (string | number)[]) => invoke<void>('player_command', { args: args.map(String) }),
|
||||
set: (name: string, value: unknown) => invoke<void>('player_set', { name, value }),
|
||||
get: <T = any>(name: string) => invoke<T>('player_get', { name }),
|
||||
show: (visible: boolean) => invoke<void>('player_show', { visible }),
|
||||
on: (handler: (e: MpvEvent) => void) => listen<MpvEvent>('mpv', handler),
|
||||
};
|
||||
693
src/player/store.ts
Normal file
|
|
@ -0,0 +1,693 @@
|
|||
import { create } from 'zustand';
|
||||
import * as api from '../plex/api';
|
||||
import { directUrl, previewUrl, reportTimeline, stopTranscode, transcodeUrl, type Delivery } from '../plex/playback';
|
||||
import type { Item, Stream } from '../plex/types';
|
||||
import { useSession } from '../app/session';
|
||||
import { useSettings, type Quality } from '../app/settings';
|
||||
import { channelLabel } from '../app/format';
|
||||
import { invalidateLibrary } from '../app/queries';
|
||||
import { keepAwake, isNative, win } from '../platform/native';
|
||||
import { mpv, type MpvEvent, type MpvTrack } from './engine';
|
||||
import { toast } from '../ui/overlays';
|
||||
import { stopThemeMusic } from './theme';
|
||||
|
||||
export interface Track {
|
||||
key: string; // stable UI key
|
||||
mpvId: number | null; // null until loaded (external subs)
|
||||
stream?: Stream; // Plex stream, when known
|
||||
label: string;
|
||||
detail: string;
|
||||
language: string;
|
||||
forced: boolean;
|
||||
external: boolean;
|
||||
}
|
||||
|
||||
export interface PlayOptions {
|
||||
/** Start position in ms. Defaults to the saved resume point when `resume` is true. */
|
||||
offsetMs?: number;
|
||||
resume?: boolean;
|
||||
mediaIndex?: number;
|
||||
/** A local file path (offline download). */
|
||||
localFile?: string;
|
||||
quality?: Quality;
|
||||
}
|
||||
|
||||
interface PlayerState {
|
||||
open: boolean;
|
||||
item: Item | null;
|
||||
delivery: Delivery | null;
|
||||
mediaIndex: number;
|
||||
quality: Quality;
|
||||
firstFrame: boolean;
|
||||
error: string;
|
||||
position: number;
|
||||
duration: number;
|
||||
cacheTime: number;
|
||||
paused: boolean;
|
||||
buffering: boolean;
|
||||
seeking: boolean;
|
||||
volume: number;
|
||||
muted: boolean;
|
||||
speed: number;
|
||||
subDelay: number;
|
||||
audioTracks: Track[];
|
||||
subTracks: Track[];
|
||||
audioKey: string;
|
||||
subKey: string; // '' when off
|
||||
chapters: { title: string; time: number }[];
|
||||
video: { width: number; height: number; hwdec: string; codec: string } | null;
|
||||
ended: boolean;
|
||||
nextUp: Item | null;
|
||||
countdown: number | null;
|
||||
postPlayDismissed: boolean;
|
||||
fullscreen: boolean;
|
||||
|
||||
play(item: Item, opts?: PlayOptions): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
togglePause(): void;
|
||||
seek(seconds: number): void;
|
||||
seekBy(delta: number): void;
|
||||
setVolume(v: number): void;
|
||||
toggleMute(): void;
|
||||
setSpeed(s: number): void;
|
||||
setSubDelay(s: number): void;
|
||||
selectAudio(key: string): Promise<void>;
|
||||
selectSubtitle(key: string): Promise<void>;
|
||||
setQuality(q: Quality): Promise<void>;
|
||||
selectVersion(index: number): Promise<void>;
|
||||
playNext(): Promise<void>;
|
||||
cancelCountdown(): void;
|
||||
toggleFullscreen(): Promise<void>;
|
||||
previewAt(seconds: number): string;
|
||||
}
|
||||
|
||||
let session = '';
|
||||
let startOffsetMs = 0;
|
||||
let lastReport = 0;
|
||||
let reportTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let countdownTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let scrobbled = false;
|
||||
let unlisten: (() => void) | null = null;
|
||||
let loadToken = 0;
|
||||
let wasFullscreenBeforePlay = false;
|
||||
let pendingExternal: Track | null = null;
|
||||
|
||||
const server = () => useSession.getState().server;
|
||||
|
||||
function languageName(code: string, fallback: string) {
|
||||
if (!code) return fallback;
|
||||
try {
|
||||
return new Intl.DisplayNames([navigator.language || 'en'], { type: 'language' }).of(code) || fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function audioTrackFromStream(s: Stream): Track {
|
||||
const lang = s.language || languageName(s.languageCode, 'Unknown');
|
||||
const parts = [s.codec.toUpperCase().replace('DCA', 'DTS'), channelLabel(s.channels) || s.audioChannelLayout].filter(Boolean);
|
||||
const title = s.title && !s.title.toLowerCase().includes(lang.toLowerCase()) ? s.title : '';
|
||||
return {
|
||||
key: `p${s.id}`,
|
||||
mpvId: null,
|
||||
stream: s,
|
||||
label: lang,
|
||||
detail: title || parts.join(' '),
|
||||
language: s.languageCode,
|
||||
forced: false,
|
||||
external: false,
|
||||
};
|
||||
}
|
||||
|
||||
function subTrackFromStream(s: Stream): Track {
|
||||
const lang = s.language || languageName(s.languageCode, 'Unknown');
|
||||
const flags = [s.forced ? 'Forced' : '', s.hearingImpaired ? 'SDH' : ''].filter(Boolean);
|
||||
return {
|
||||
key: `p${s.id}`,
|
||||
mpvId: null,
|
||||
stream: s,
|
||||
label: [lang, ...flags].join(' · '),
|
||||
detail: [s.title && s.title !== lang ? s.title : '', s.codec.toUpperCase(), s.key ? 'External' : ''].filter(Boolean).join(' · '),
|
||||
language: s.languageCode,
|
||||
forced: s.forced,
|
||||
external: !!s.key,
|
||||
};
|
||||
}
|
||||
|
||||
function mpvTrackLabel(t: MpvTrack): Track {
|
||||
const lang = t.lang ? languageName(t.lang, t.lang) : t.type === 'sub' ? 'Subtitles' : 'Audio';
|
||||
return {
|
||||
key: `m${t.id}`,
|
||||
mpvId: t.id,
|
||||
label: t.title ? `${lang} · ${t.title}` : lang,
|
||||
detail: [t.codec?.toUpperCase(), t['demux-channel-count'] ? channelLabel(t['demux-channel-count']) : ''].filter(Boolean).join(' '),
|
||||
language: t.lang ?? '',
|
||||
forced: !!t.forced,
|
||||
external: !!t.external,
|
||||
};
|
||||
}
|
||||
|
||||
function report(state: 'playing' | 'paused' | 'buffering' | 'stopped') {
|
||||
const s = server();
|
||||
const { item, position, delivery } = usePlayer.getState();
|
||||
if (!s || !item || !session || item.type === 'clip') return;
|
||||
lastReport = Date.now();
|
||||
const extra: Record<string, string | number> = {};
|
||||
if (delivery?.mode === 'transcode' && delivery.session) extra['X-Plex-Session-Identifier'] = delivery.session;
|
||||
reportTimeline(s, item, state, position * 1000, session, extra).catch(() => {});
|
||||
}
|
||||
|
||||
function checkScrobble() {
|
||||
const { item, position, duration } = usePlayer.getState();
|
||||
const s = server();
|
||||
if (!item || !s || scrobbled || !duration || item.type === 'clip') return;
|
||||
const percent = useSettings.getState().watchedPercent;
|
||||
if (position / duration >= percent / 100) {
|
||||
scrobbled = true;
|
||||
api
|
||||
.setWatched(s, item.id, true)
|
||||
.then(() => invalidateLibrary())
|
||||
.catch(() => (scrobbled = false));
|
||||
}
|
||||
}
|
||||
|
||||
async function findNext(item: Item): Promise<Item | null> {
|
||||
const s = server();
|
||||
if (!s || item.type !== 'episode' || !item.grandparentId) return null;
|
||||
try {
|
||||
const leaves = await api.allLeaves(s, item.grandparentId);
|
||||
const i = leaves.findIndex((e) => e.id === item.id);
|
||||
return i >= 0 ? (leaves[i + 1] ?? null) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function startCountdown() {
|
||||
const st = usePlayer.getState();
|
||||
if (!st.nextUp || st.countdown !== null || st.postPlayDismissed) return;
|
||||
const settings = useSettings.getState();
|
||||
if (!settings.autoplayNext) {
|
||||
usePlayer.setState({ countdown: -1 });
|
||||
return;
|
||||
}
|
||||
usePlayer.setState({ countdown: settings.countdownSeconds });
|
||||
countdownTimer && clearInterval(countdownTimer);
|
||||
countdownTimer = setInterval(() => {
|
||||
const c = usePlayer.getState().countdown;
|
||||
if (c === null || c < 0) return;
|
||||
if (c <= 1) {
|
||||
clearInterval(countdownTimer!);
|
||||
countdownTimer = null;
|
||||
usePlayer.getState().playNext();
|
||||
} else usePlayer.setState({ countdown: c - 1 });
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function stopCountdown() {
|
||||
if (countdownTimer) clearInterval(countdownTimer);
|
||||
countdownTimer = null;
|
||||
}
|
||||
|
||||
/** Applies Plex/user track preferences once mpv has loaded the file. */
|
||||
async function applyInitialTracks(tracks: MpvTrack[]) {
|
||||
const st = usePlayer.getState();
|
||||
const prefs = useSettings.getState();
|
||||
const direct = st.delivery?.mode !== 'transcode';
|
||||
const byFF = (type: string, idx: number) => tracks.find((t) => t.type === type && t['ff-index'] === idx && !t.external);
|
||||
|
||||
let audio = st.audioTracks;
|
||||
let subs = st.subTracks;
|
||||
if (direct) {
|
||||
audio = audio.map((t) => ({ ...t, mpvId: t.stream ? (byFF('audio', t.stream.index)?.id ?? null) : t.mpvId }));
|
||||
subs = subs.map((t) => ({ ...t, mpvId: t.stream && !t.external ? (byFF('sub', t.stream.index)?.id ?? null) : t.mpvId }));
|
||||
// Files without Plex stream info (offline) use mpv's own list.
|
||||
if (!audio.length) audio = tracks.filter((t) => t.type === 'audio').map(mpvTrackLabel);
|
||||
if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel);
|
||||
}
|
||||
|
||||
// Audio: preferred language, else Plex's selection, else the file default.
|
||||
let audioKey = st.audioKey;
|
||||
if (!audioKey) {
|
||||
const lang = prefs.audioLanguage;
|
||||
audioKey =
|
||||
(lang && audio.find((t) => t.language === lang)?.key) ||
|
||||
audio.find((t) => t.stream?.selected)?.key ||
|
||||
audio.find((t) => t.stream?.default)?.key ||
|
||||
audio[0]?.key ||
|
||||
'';
|
||||
}
|
||||
// Subtitles: follow the subtitle mode.
|
||||
let subKey = st.subKey;
|
||||
if (subKey === '__init') {
|
||||
const lang = prefs.subtitleLanguage || audio.find((t) => t.key === audioKey)?.language || '';
|
||||
const inLang = subs.filter((t) => !lang || t.language === lang);
|
||||
switch (prefs.subtitleMode) {
|
||||
case 'off':
|
||||
subKey = '';
|
||||
break;
|
||||
case 'always':
|
||||
subKey = (inLang.find((t) => !t.forced) ?? inLang[0] ?? subs[0])?.key ?? '';
|
||||
break;
|
||||
case 'forced':
|
||||
subKey = inLang.find((t) => t.forced)?.key ?? '';
|
||||
break;
|
||||
default:
|
||||
subKey = subs.find((t) => t.stream?.selected)?.key ?? inLang.find((t) => t.forced)?.key ?? '';
|
||||
}
|
||||
}
|
||||
usePlayer.setState({ audioTracks: audio, subTracks: subs, audioKey, subKey });
|
||||
if (direct) {
|
||||
const a = audio.find((t) => t.key === audioKey);
|
||||
if (a?.mpvId) mpv.set('aid', a.mpvId).catch(() => {});
|
||||
await setMpvSubtitle(subKey);
|
||||
}
|
||||
}
|
||||
|
||||
async function setMpvSubtitle(key: string) {
|
||||
const st = usePlayer.getState();
|
||||
const t = st.subTracks.find((x) => x.key === key);
|
||||
if (!t) {
|
||||
await mpv.set('sid', 'no').catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (t.mpvId) {
|
||||
await mpv.set('sid', t.mpvId).catch(() => {});
|
||||
} else if (t.external && t.stream?.key && server()) {
|
||||
pendingExternal = t;
|
||||
const url = server()!.signed(t.stream.key);
|
||||
await mpv.command('sub-add', url, 'select', t.label, t.language || 'und').catch(() => toast('This subtitle could not be loaded.', 'error'));
|
||||
}
|
||||
}
|
||||
|
||||
function onEvent(e: MpvEvent) {
|
||||
const st = usePlayer.getState();
|
||||
if (!st.open) return;
|
||||
switch (e.type) {
|
||||
case 'property': {
|
||||
const v = e.value;
|
||||
switch (e.name) {
|
||||
case 'time-pos':
|
||||
if (typeof v === 'number') {
|
||||
usePlayer.setState({ position: v });
|
||||
checkScrobble();
|
||||
if (Date.now() - lastReport > 10000) report(st.paused ? 'paused' : 'playing');
|
||||
maybeCredits(v);
|
||||
}
|
||||
break;
|
||||
case 'duration':
|
||||
if (typeof v === 'number' && v > 0) usePlayer.setState({ duration: v });
|
||||
break;
|
||||
case 'pause':
|
||||
usePlayer.setState({ paused: !!v });
|
||||
report(v ? 'paused' : 'playing');
|
||||
keepAwake(!v);
|
||||
break;
|
||||
case 'paused-for-cache':
|
||||
usePlayer.setState({ buffering: !!v });
|
||||
break;
|
||||
case 'seeking':
|
||||
usePlayer.setState({ seeking: !!v });
|
||||
break;
|
||||
case 'demuxer-cache-time':
|
||||
if (typeof v === 'number') usePlayer.setState({ cacheTime: v });
|
||||
break;
|
||||
case 'volume':
|
||||
if (typeof v === 'number') usePlayer.setState({ volume: v });
|
||||
break;
|
||||
case 'mute':
|
||||
usePlayer.setState({ muted: !!v });
|
||||
break;
|
||||
case 'speed':
|
||||
if (typeof v === 'number') usePlayer.setState({ speed: v });
|
||||
break;
|
||||
case 'sub-delay':
|
||||
if (typeof v === 'number') usePlayer.setState({ subDelay: v });
|
||||
break;
|
||||
case 'chapter-list':
|
||||
if (Array.isArray(v) && v.length > 1 && !st.chapters.length)
|
||||
usePlayer.setState({ chapters: v.map((c: any, i: number) => ({ title: c.title && !/^\d\d:\d\d/.test(c.title) ? c.title : `Chapter ${i + 1}`, time: c.time })) });
|
||||
break;
|
||||
case 'video-params':
|
||||
if (v?.w) usePlayer.setState({ video: { ...(st.video ?? { hwdec: '', codec: '' }), width: v.w, height: v.h } });
|
||||
break;
|
||||
case 'hwdec-current':
|
||||
usePlayer.setState({ video: { ...(st.video ?? { width: 0, height: 0, codec: '' }), hwdec: v ?? '' } });
|
||||
break;
|
||||
case 'track-list':
|
||||
if (Array.isArray(v)) {
|
||||
if (pendingExternal) {
|
||||
const ext = (v as MpvTrack[]).filter((t) => t.type === 'sub' && t.external).pop();
|
||||
if (ext) {
|
||||
const key = pendingExternal.key;
|
||||
pendingExternal = null;
|
||||
usePlayer.setState({ subTracks: usePlayer.getState().subTracks.map((t) => (t.key === key ? { ...t, mpvId: ext.id } : t)) });
|
||||
}
|
||||
}
|
||||
const video = (v as MpvTrack[]).find((t) => t.type === 'video' && t.selected);
|
||||
if (video) usePlayer.setState({ video: { ...(usePlayer.getState().video ?? { width: 0, height: 0, hwdec: '' }), codec: video.codec ?? '' } });
|
||||
}
|
||||
break;
|
||||
case 'eof-reached':
|
||||
if (v === true) onEnded();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'file-loaded':
|
||||
mpv
|
||||
.get<MpvTrack[]>('track-list')
|
||||
.then(applyInitialTracks)
|
||||
.catch(() => {});
|
||||
break;
|
||||
case 'playback-restart':
|
||||
if (!st.firstFrame) usePlayer.setState({ firstFrame: true });
|
||||
usePlayer.setState({ buffering: false });
|
||||
break;
|
||||
case 'end-file':
|
||||
if (e.reason === 'error') {
|
||||
usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' });
|
||||
fallbackAfterError();
|
||||
} else if (e.reason === 'eof') onEnded();
|
||||
break;
|
||||
case 'log':
|
||||
if (e.level === 'error' && /http|stream|open/i.test(e.prefix + e.text) && !st.firstFrame) console.warn('[mpv]', e.prefix, e.text);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/** Direct play failed: retry once through Plex's converter. */
|
||||
let triedFallback = false;
|
||||
function fallbackAfterError() {
|
||||
const st = usePlayer.getState();
|
||||
if (triedFallback || !st.item || st.delivery?.mode !== 'direct') return;
|
||||
triedFallback = true;
|
||||
toast('Direct playback failed. Asking Plex to convert this video.');
|
||||
usePlayer.setState({ error: '' });
|
||||
st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080' });
|
||||
}
|
||||
|
||||
function maybeCredits(pos: number) {
|
||||
const st = usePlayer.getState();
|
||||
if (st.item?.type !== 'episode' || !st.nextUp || st.countdown !== null) return;
|
||||
const credits = st.item.markers.find((m) => m.type === 'credits' && (m.final || m.end >= st.item!.duration - 5000));
|
||||
if (credits && pos * 1000 >= credits.start && pos * 1000 < credits.end && useSettings.getState().skipCredits !== 'off') startCountdown();
|
||||
}
|
||||
|
||||
function onEnded() {
|
||||
const st = usePlayer.getState();
|
||||
if (st.ended) return;
|
||||
usePlayer.setState({ ended: true });
|
||||
report('stopped');
|
||||
checkScrobble();
|
||||
if (st.nextUp) startCountdown();
|
||||
}
|
||||
|
||||
export const usePlayer = create<PlayerState>((set, get) => ({
|
||||
open: false,
|
||||
item: null,
|
||||
delivery: null,
|
||||
mediaIndex: 0,
|
||||
quality: 'original',
|
||||
firstFrame: false,
|
||||
error: '',
|
||||
position: 0,
|
||||
duration: 0,
|
||||
cacheTime: 0,
|
||||
paused: false,
|
||||
buffering: false,
|
||||
seeking: false,
|
||||
volume: 100,
|
||||
muted: false,
|
||||
speed: 1,
|
||||
subDelay: 0,
|
||||
audioTracks: [],
|
||||
subTracks: [],
|
||||
audioKey: '',
|
||||
subKey: '',
|
||||
chapters: [],
|
||||
video: null,
|
||||
ended: false,
|
||||
nextUp: null,
|
||||
countdown: null,
|
||||
postPlayDismissed: false,
|
||||
fullscreen: false,
|
||||
|
||||
async play(input, opts = {}) {
|
||||
const token = ++loadToken;
|
||||
const s = server();
|
||||
const prefs = useSettings.getState();
|
||||
stopThemeMusic();
|
||||
stopCountdown();
|
||||
if (!isNative) {
|
||||
toast('Video playback is available in the Kaleido desktop app.', 'error');
|
||||
return;
|
||||
}
|
||||
const previous = get();
|
||||
if (previous.open && previous.item) {
|
||||
report('stopped');
|
||||
if (previous.delivery?.session && s) stopTranscode(s, previous.delivery.session);
|
||||
}
|
||||
if (!previous.open) {
|
||||
triedFallback = false;
|
||||
wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false);
|
||||
}
|
||||
set({
|
||||
open: true,
|
||||
item: input,
|
||||
firstFrame: false,
|
||||
error: '',
|
||||
position: (opts.offsetMs ?? 0) / 1000,
|
||||
duration: input.duration / 1000,
|
||||
cacheTime: 0,
|
||||
paused: false,
|
||||
buffering: true,
|
||||
ended: false,
|
||||
nextUp: null,
|
||||
countdown: null,
|
||||
postPlayDismissed: false,
|
||||
chapters: [],
|
||||
audioTracks: [],
|
||||
subTracks: [],
|
||||
audioKey: '',
|
||||
subKey: '__init',
|
||||
video: null,
|
||||
fullscreen: wasFullscreenBeforePlay,
|
||||
});
|
||||
document.documentElement.classList.add('player-open');
|
||||
|
||||
try {
|
||||
// Full metadata: streams, markers and chapters.
|
||||
let item = input;
|
||||
if (!opts.localFile && s && (!input.media.length || !input.media[0].parts[0]?.streams.length || !input.raw?.Marker)) {
|
||||
item = await api.metadata(s, input.id).catch(() => input);
|
||||
}
|
||||
if (token !== loadToken) return;
|
||||
const mediaIndex = Math.min(opts.mediaIndex ?? 0, Math.max(0, item.media.length - 1));
|
||||
const media = item.media[mediaIndex];
|
||||
let offsetMs = opts.offsetMs ?? (opts.resume !== false && item.viewOffset && item.viewOffset < item.duration * 0.97 ? item.viewOffset : 0);
|
||||
startOffsetMs = offsetMs;
|
||||
const local = useSession.getState().connection?.local ?? true;
|
||||
const quality: Quality = opts.quality ?? (local ? prefs.quality : prefs.remoteQuality);
|
||||
session = crypto.randomUUID();
|
||||
scrobbled = false;
|
||||
|
||||
let delivery: Delivery;
|
||||
if (opts.localFile) {
|
||||
delivery = { url: opts.localFile, mode: 'local', label: 'Downloaded', absoluteTime: false };
|
||||
} else if (!s || !media) {
|
||||
throw new Error('This title has no playable media.');
|
||||
} else if (quality === 'original') {
|
||||
delivery = { url: directUrl(s, media), mode: 'direct', label: 'Original', absoluteTime: false };
|
||||
} else {
|
||||
const tsession = crypto.randomUUID();
|
||||
delivery = {
|
||||
url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local }),
|
||||
mode: 'transcode',
|
||||
session: tsession,
|
||||
label: quality === '2160' ? '4K' : `${quality}p`,
|
||||
absoluteTime: true,
|
||||
};
|
||||
}
|
||||
|
||||
const streams = media?.parts.flatMap((p) => p.streams) ?? [];
|
||||
set({
|
||||
item,
|
||||
delivery,
|
||||
mediaIndex,
|
||||
quality,
|
||||
duration: (item.duration || media?.duration || 0) / 1000,
|
||||
audioTracks: streams.filter((x) => x.streamType === 2).map(audioTrackFromStream),
|
||||
subTracks: streams.filter((x) => x.streamType === 3).map(subTrackFromStream),
|
||||
});
|
||||
|
||||
await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough });
|
||||
if (!unlisten) unlisten = await mpv.on(onEvent);
|
||||
if (token !== loadToken) return;
|
||||
await mpv.set('mute', false);
|
||||
await mpv.set('volume', prefs.volume);
|
||||
await mpv.set('speed', 1);
|
||||
await mpv.set('sub-scale', prefs.subtitleScale);
|
||||
await mpv.set('sub-back-color', prefs.subtitleBackground ? '#C0000000' : '#00000000');
|
||||
await mpv.set('sub-border-style', prefs.subtitleBackground ? 'opaque-box' : 'outline-and-shadow');
|
||||
await mpv.set('force-media-title', item.type === 'episode' ? `${item.grandparentTitle} — ${item.title}` : item.title);
|
||||
await mpv.show(true);
|
||||
const fileOpts = [
|
||||
delivery.mode === 'transcode' ? 'rebase-start-time=no' : 'rebase-start-time=yes',
|
||||
offsetMs > 0 && delivery.mode !== 'transcode' ? `start=${(offsetMs / 1000).toFixed(2)}` : 'start=none',
|
||||
].join(',');
|
||||
await mpv.command('loadfile', delivery.url, 'replace', -1, fileOpts);
|
||||
keepAwake(true);
|
||||
report('buffering');
|
||||
reportTimer && clearInterval(reportTimer);
|
||||
reportTimer = setInterval(() => {
|
||||
const st = get();
|
||||
if (st.open && !st.ended) report(st.paused ? 'paused' : st.buffering ? 'buffering' : 'playing');
|
||||
}, 10000);
|
||||
findNext(item).then((next) => token === loadToken && set({ nextUp: next }));
|
||||
} catch (e: any) {
|
||||
if (token !== loadToken) return;
|
||||
set({ error: e?.message ?? String(e), buffering: false });
|
||||
}
|
||||
},
|
||||
|
||||
async close() {
|
||||
loadToken++;
|
||||
const st = get();
|
||||
stopCountdown();
|
||||
if (reportTimer) clearInterval(reportTimer);
|
||||
reportTimer = null;
|
||||
if (st.item && !st.error) report('stopped');
|
||||
const s = server();
|
||||
if (st.delivery?.session && s) stopTranscode(s, st.delivery.session);
|
||||
keepAwake(false);
|
||||
if (isNative) {
|
||||
await mpv.command('stop').catch(() => {});
|
||||
await mpv.show(false).catch(() => {});
|
||||
}
|
||||
document.documentElement.classList.remove('player-open', 'video-active');
|
||||
set({ open: false, item: null, delivery: null, error: '', countdown: null, nextUp: null, firstFrame: false });
|
||||
const fs = await win.isFullscreen().catch(() => false);
|
||||
if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false);
|
||||
if (st.item) invalidateLibrary();
|
||||
},
|
||||
|
||||
togglePause() {
|
||||
const st = get();
|
||||
if (st.ended) {
|
||||
st.seek(0);
|
||||
set({ ended: false });
|
||||
}
|
||||
mpv.command('cycle', 'pause').catch(() => {});
|
||||
},
|
||||
|
||||
seek(seconds) {
|
||||
const st = get();
|
||||
const target = Math.max(0, Math.min(seconds, (st.duration || seconds) - 0.5));
|
||||
set({ position: target, ended: false });
|
||||
if (st.countdown !== null) {
|
||||
stopCountdown();
|
||||
set({ countdown: null });
|
||||
}
|
||||
mpv.command('seek', target.toFixed(3), 'absolute+exact').catch(() => {});
|
||||
},
|
||||
|
||||
seekBy(delta) {
|
||||
const st = get();
|
||||
st.seek(st.position + delta);
|
||||
},
|
||||
|
||||
setVolume(v) {
|
||||
const volume = Math.max(0, Math.min(150, Math.round(v)));
|
||||
set({ volume });
|
||||
useSettings.getState().set('volume', Math.min(100, volume));
|
||||
mpv.set('volume', volume).catch(() => {});
|
||||
if (get().muted && volume > 0) mpv.set('mute', false).catch(() => {});
|
||||
},
|
||||
|
||||
toggleMute() {
|
||||
mpv.command('cycle', 'mute').catch(() => {});
|
||||
},
|
||||
|
||||
setSpeed(speed) {
|
||||
mpv.set('speed', speed).catch(() => {});
|
||||
},
|
||||
|
||||
setSubDelay(delay) {
|
||||
mpv.set('sub-delay', delay).catch(() => {});
|
||||
},
|
||||
|
||||
async selectAudio(key) {
|
||||
const st = get();
|
||||
const t = st.audioTracks.find((x) => x.key === key);
|
||||
if (!t) return;
|
||||
set({ audioKey: key });
|
||||
const s = server();
|
||||
const part = st.item?.media[st.mediaIndex]?.parts[0];
|
||||
if (s && part && t.stream) api.selectStreams(s, part.id, { audioStreamID: t.stream.id }).catch(() => {});
|
||||
if (st.delivery?.mode === 'transcode' && st.item) {
|
||||
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality });
|
||||
return;
|
||||
}
|
||||
if (t.mpvId) await mpv.set('aid', t.mpvId).catch(() => {});
|
||||
},
|
||||
|
||||
async selectSubtitle(key) {
|
||||
const st = get();
|
||||
set({ subKey: key });
|
||||
const s = server();
|
||||
const part = st.item?.media[st.mediaIndex]?.parts[0];
|
||||
const t = st.subTracks.find((x) => x.key === key);
|
||||
if (s && part) api.selectStreams(s, part.id, { subtitleStreamID: t?.stream?.id ?? '0' }).catch(() => {});
|
||||
if (st.delivery?.mode === 'transcode' && st.item) {
|
||||
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality });
|
||||
usePlayer.setState({ subKey: key });
|
||||
return;
|
||||
}
|
||||
await setMpvSubtitle(key);
|
||||
},
|
||||
|
||||
async setQuality(q) {
|
||||
const st = get();
|
||||
if (!st.item || q === st.quality) return;
|
||||
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q });
|
||||
},
|
||||
|
||||
async selectVersion(index) {
|
||||
const st = get();
|
||||
if (!st.item || index === st.mediaIndex) return;
|
||||
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: index, quality: st.quality });
|
||||
},
|
||||
|
||||
async playNext() {
|
||||
const st = get();
|
||||
stopCountdown();
|
||||
if (!st.nextUp) return;
|
||||
await st.play(st.nextUp, { resume: true, quality: st.quality });
|
||||
},
|
||||
|
||||
cancelCountdown() {
|
||||
stopCountdown();
|
||||
set({ countdown: null, postPlayDismissed: true });
|
||||
},
|
||||
|
||||
async toggleFullscreen() {
|
||||
const fs = await win.isFullscreen().catch(() => false);
|
||||
await win.setFullscreen(!fs);
|
||||
set({ fullscreen: !fs });
|
||||
},
|
||||
|
||||
previewAt(seconds) {
|
||||
const st = get();
|
||||
const s = server();
|
||||
if (!s || !st.item || st.delivery?.mode === 'local') return '';
|
||||
return previewUrl(s, st.item.media[st.mediaIndex], seconds * 1000);
|
||||
},
|
||||
}));
|
||||
|
||||
/** Shown once the first frame is ready, the page turns transparent over the video. */
|
||||
usePlayer.subscribe((st, prev) => {
|
||||
if (st.firstFrame !== prev.firstFrame || st.open !== prev.open || st.error !== prev.error) {
|
||||
document.documentElement.classList.toggle('video-active', st.open && st.firstFrame && !st.error);
|
||||
}
|
||||
});
|
||||
52
src/player/theme.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
/** Optional title theme music on detail pages, faded in and out. */
|
||||
import { useSession } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
|
||||
let audio: HTMLAudioElement | null = null;
|
||||
let current = '';
|
||||
let fade: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function fadeTo(target: number, done?: () => void) {
|
||||
if (!audio) return;
|
||||
if (fade) clearInterval(fade);
|
||||
const a = audio;
|
||||
fade = setInterval(() => {
|
||||
const step = 0.02;
|
||||
if (Math.abs(a.volume - target) <= step) {
|
||||
a.volume = target;
|
||||
clearInterval(fade!);
|
||||
fade = null;
|
||||
done?.();
|
||||
} else a.volume += a.volume < target ? step : -step;
|
||||
}, 40);
|
||||
}
|
||||
|
||||
export function playThemeMusic(path: string) {
|
||||
const prefs = useSettings.getState();
|
||||
const server = useSession.getState().server;
|
||||
if (!prefs.themeMusic || !path || !server || document.documentElement.classList.contains('player-open')) return;
|
||||
if (path === current && audio && !audio.paused) return;
|
||||
stopThemeMusic(true);
|
||||
current = path;
|
||||
audio = new Audio(server.signed(path));
|
||||
audio.volume = 0;
|
||||
audio.loop = false;
|
||||
audio.play().then(() => fadeTo(prefs.themeVolume / 100), () => {});
|
||||
}
|
||||
|
||||
export function stopThemeMusic(immediate = false) {
|
||||
current = '';
|
||||
if (!audio) return;
|
||||
const a = audio;
|
||||
audio = null;
|
||||
if (immediate) {
|
||||
a.pause();
|
||||
return;
|
||||
}
|
||||
const prev = audio;
|
||||
audio = a;
|
||||
fadeTo(0, () => {
|
||||
a.pause();
|
||||
if (audio === a) audio = prev;
|
||||
});
|
||||
}
|
||||
182
src/plex/account.ts
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
import { arr, bool, num, str } from './parse';
|
||||
import { clientIdentifier, PlexError, plexRequest, PRODUCT } from './client';
|
||||
import type { HomeUser, PlexUser, ServerConnection, ServerResource } from './types';
|
||||
|
||||
const TV = 'https://plex.tv/api/v2';
|
||||
|
||||
export interface Pin {
|
||||
id: number;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export async function createPin(strong: boolean): Promise<Pin> {
|
||||
const j = await plexRequest(`${TV}/pins`, null, { method: 'POST', params: { strong } });
|
||||
return { id: num(j.id), code: str(j.code) };
|
||||
}
|
||||
|
||||
export async function checkPin(pin: Pin): Promise<string | null> {
|
||||
const j = await plexRequest(`${TV}/pins/${pin.id}`, null);
|
||||
const token = str(j.authToken);
|
||||
return token && token !== 'null' ? token : null;
|
||||
}
|
||||
|
||||
/** The browser sign-in page for a strong PIN. */
|
||||
export function authUrl(pin: Pin): string {
|
||||
const params = new URLSearchParams({
|
||||
clientID: clientIdentifier(),
|
||||
code: pin.code,
|
||||
'context[device][product]': PRODUCT,
|
||||
'context[device][platform]': 'Windows',
|
||||
'context[device][device]': 'Windows',
|
||||
});
|
||||
return `https://app.plex.tv/auth#?${params.toString()}`;
|
||||
}
|
||||
|
||||
export async function getUser(token: string): Promise<PlexUser> {
|
||||
const j = await plexRequest(`${TV}/user`, token);
|
||||
return {
|
||||
id: num(j.id),
|
||||
uuid: str(j.uuid),
|
||||
username: str(j.username),
|
||||
title: str(j.title || j.friendlyName || j.username),
|
||||
email: str(j.email),
|
||||
thumb: str(j.thumb),
|
||||
home: bool(j.home),
|
||||
homeAdmin: bool(j.homeAdmin),
|
||||
protected: bool(j.protected),
|
||||
subscription: bool(j.subscription?.active),
|
||||
};
|
||||
}
|
||||
|
||||
export async function signOut(token: string) {
|
||||
await plexRequest(`${TV}/users/signout`, token, { method: 'DELETE' }).catch(() => {});
|
||||
}
|
||||
|
||||
export async function getResources(token: string): Promise<ServerResource[]> {
|
||||
const list = await plexRequest<any[]>(`${TV}/resources`, token, {
|
||||
params: { includeHttps: 1, includeRelay: 1, includeIPv6: 1 },
|
||||
});
|
||||
return arr(list)
|
||||
.filter((r) => str(r.provides).split(',').includes('server'))
|
||||
.map((r) => ({
|
||||
id: str(r.clientIdentifier),
|
||||
name: str(r.name),
|
||||
owned: bool(r.owned),
|
||||
accessToken: str(r.accessToken) || token,
|
||||
productVersion: str(r.productVersion),
|
||||
platform: str(r.platform),
|
||||
presence: bool(r.presence),
|
||||
publicAddress: str(r.publicAddress),
|
||||
sourceTitle: str(r.sourceTitle),
|
||||
httpsRequired: bool(r.httpsRequired),
|
||||
connections: arr(r.connections).map(
|
||||
(c): ServerConnection => ({
|
||||
uri: str(c.uri),
|
||||
local: bool(c.local),
|
||||
relay: bool(c.relay),
|
||||
protocol: str(c.protocol),
|
||||
address: str(c.address),
|
||||
port: num(c.port),
|
||||
IPv6: bool(c.IPv6),
|
||||
}),
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getHomeUsers(token: string): Promise<HomeUser[]> {
|
||||
const j = await plexRequest(`${TV}/home/users`, token);
|
||||
return arr(j.users ?? j).map((u: any) => ({
|
||||
id: num(u.id),
|
||||
uuid: str(u.uuid),
|
||||
title: str(u.title || u.username),
|
||||
username: str(u.username),
|
||||
thumb: str(u.thumb),
|
||||
admin: bool(u.admin),
|
||||
protected: bool(u.protected),
|
||||
restricted: bool(u.restricted),
|
||||
guest: bool(u.guest),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Switches to a Plex Home user; returns that user's account token. */
|
||||
export async function switchHomeUser(token: string, uuid: string, pin?: string): Promise<string> {
|
||||
const j = await plexRequest(`${TV}/home/users/${uuid}/switch`, token, { method: 'POST', params: { pin } });
|
||||
const t = str(j.authToken);
|
||||
if (!t) throw new PlexError('Plex did not accept this profile PIN.', 401);
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Whether a server address is on this network: plex.direct names encode the server's IP. */
|
||||
export function isLocalAddress(url: string): boolean {
|
||||
let host = '';
|
||||
try {
|
||||
host = new URL(url).hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const ip = host.endsWith('.plex.direct') ? host.split('.')[0].replace(/-/g, '.') : host;
|
||||
if (host === 'localhost' || host.endsWith('.local') || (!host.includes('.') && !host.includes(':'))) return true;
|
||||
if (ip.startsWith('fd') || ip.startsWith('fe80')) return true;
|
||||
const o = ip.split('.').map(Number);
|
||||
if (o.length !== 4 || o.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
|
||||
const [a, b] = o;
|
||||
return a === 10 || a === 127 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
|
||||
}
|
||||
|
||||
export interface Reachable {
|
||||
uri: string;
|
||||
machineId: string;
|
||||
name: string;
|
||||
local: boolean;
|
||||
relay: boolean;
|
||||
latency: number;
|
||||
}
|
||||
|
||||
async function probe(uri: string, token: string, timeout: number): Promise<Reachable> {
|
||||
const start = performance.now();
|
||||
const j = await plexRequest(`${uri.replace(/\/$/, '')}/identity`, token, { timeout });
|
||||
const machineId = str(j?.MediaContainer?.machineIdentifier);
|
||||
if (!machineId) throw new PlexError('Not a Plex Media Server');
|
||||
return { uri, machineId, name: '', local: isLocalAddress(uri), relay: false, latency: performance.now() - start };
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the best reachable connection. Local direct connections win, then
|
||||
* remote direct, then Plex Relay. Each tier is probed concurrently.
|
||||
*/
|
||||
export async function connect(resource: ServerResource, preferred?: string): Promise<Reachable> {
|
||||
const conns = resource.connections.filter((c) => c.uri.startsWith('http'));
|
||||
const tiers: ServerConnection[][] = [];
|
||||
if (preferred) {
|
||||
const p = conns.find((c) => c.uri === preferred);
|
||||
if (p) tiers.push([p]);
|
||||
}
|
||||
tiers.push(
|
||||
conns.filter((c) => c.local && !c.relay),
|
||||
conns.filter((c) => !c.local && !c.relay),
|
||||
conns.filter((c) => c.relay),
|
||||
);
|
||||
for (const tier of tiers) {
|
||||
if (!tier.length) continue;
|
||||
try {
|
||||
const winner = await Promise.any(
|
||||
tier.map((c) =>
|
||||
probe(c.uri, resource.accessToken, c.relay ? 12000 : 6000).then((r) => ({ ...r, local: c.local, relay: c.relay, name: resource.name })),
|
||||
),
|
||||
);
|
||||
return winner;
|
||||
} catch {
|
||||
/* next tier */
|
||||
}
|
||||
}
|
||||
throw new PlexError(`Cannot reach ${resource.name}. Check that the server is online and reachable from this computer.`);
|
||||
}
|
||||
|
||||
/** Validates a manual server address with a token. */
|
||||
export async function connectManual(uri: string, token: string): Promise<Reachable & { name: string }> {
|
||||
const base = uri.replace(/\/$/, '');
|
||||
const j = await plexRequest(`${base}/`, token, { timeout: 8000 });
|
||||
const mc = j?.MediaContainer;
|
||||
if (!mc?.machineIdentifier) throw new PlexError('This address is not a Plex Media Server.');
|
||||
return { uri: base, machineId: str(mc.machineIdentifier), name: str(mc.friendlyName) || 'Plex', local: isLocalAddress(base), relay: false, latency: 0 };
|
||||
}
|
||||
361
src/plex/admin.ts
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
/** Plex Media Server administration (owner accounts). */
|
||||
import type { PlexServer } from './client';
|
||||
import { arr, bool, num, parseItem, parseSection, str } from './parse';
|
||||
import type { Item, Section } from './types';
|
||||
|
||||
export interface ServerSetting {
|
||||
id: string;
|
||||
label: string;
|
||||
summary: string;
|
||||
type: 'text' | 'bool' | 'int' | 'double' | string;
|
||||
default: unknown;
|
||||
value: unknown;
|
||||
hidden: boolean;
|
||||
advanced: boolean;
|
||||
group: string;
|
||||
options: { value: string; label: string }[] | null;
|
||||
}
|
||||
|
||||
export async function prefs(s: PlexServer): Promise<ServerSetting[]> {
|
||||
const mc = await s.container('/:/prefs');
|
||||
return arr(mc.Setting).map((x: any) => ({
|
||||
id: str(x.id),
|
||||
label: str(x.label) || str(x.id),
|
||||
summary: str(x.summary),
|
||||
type: str(x.type),
|
||||
default: x.default,
|
||||
value: x.value,
|
||||
hidden: bool(x.hidden),
|
||||
advanced: bool(x.advanced),
|
||||
group: str(x.group),
|
||||
options: x.enumValues
|
||||
? str(x.enumValues)
|
||||
.split('|')
|
||||
.map((pair) => {
|
||||
const i = pair.indexOf(':');
|
||||
return i < 0 ? { value: pair, label: pair } : { value: pair.slice(0, i), label: pair.slice(i + 1) };
|
||||
})
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function setPrefs(s: PlexServer, values: Record<string, string | number | boolean>) {
|
||||
const params: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(values)) params[k] = typeof v === 'boolean' ? (v ? 'true' : 'false') : String(v);
|
||||
await s.send('PUT', '/:/prefs', params);
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
sessionKey: string;
|
||||
sessionId: string;
|
||||
item: Item;
|
||||
user: { title: string; thumb: string };
|
||||
player: { title: string; product: string; platform: string; device: string; state: string; local: boolean; address: string; secure: boolean };
|
||||
bandwidth: number;
|
||||
location: string;
|
||||
decision: { video: string; audio: string; container: string; transcodeHw: boolean; progress: number; speed: number; throttled: boolean; videoCodec: string; audioCodec: string; reason: string } | null;
|
||||
viewOffset: number;
|
||||
}
|
||||
|
||||
export async function sessions(s: PlexServer): Promise<Session[]> {
|
||||
const mc = await s.container('/status/sessions');
|
||||
return arr(mc.Metadata).map((m: any) => {
|
||||
const t = m.TranscodeSession;
|
||||
const sess = m.Session ?? {};
|
||||
return {
|
||||
sessionKey: str(m.sessionKey),
|
||||
sessionId: str(sess.id),
|
||||
item: parseItem(m),
|
||||
user: { title: str(m.User?.title), thumb: str(m.User?.thumb) },
|
||||
player: {
|
||||
title: str(m.Player?.title),
|
||||
product: str(m.Player?.product),
|
||||
platform: str(m.Player?.platform),
|
||||
device: str(m.Player?.device),
|
||||
state: str(m.Player?.state),
|
||||
local: bool(m.Player?.local),
|
||||
address: str(m.Player?.address),
|
||||
secure: bool(m.Player?.secure),
|
||||
},
|
||||
bandwidth: num(sess.bandwidth),
|
||||
location: str(sess.location),
|
||||
viewOffset: num(m.viewOffset),
|
||||
decision: t
|
||||
? {
|
||||
video: str(t.videoDecision),
|
||||
audio: str(t.audioDecision),
|
||||
container: str(t.container),
|
||||
transcodeHw: bool(t.transcodeHwRequested) || bool(t.transcodeHwFullPipeline),
|
||||
progress: num(t.progress),
|
||||
speed: num(t.speed),
|
||||
throttled: bool(t.throttled),
|
||||
videoCodec: str(t.videoCodec),
|
||||
audioCodec: str(t.audioCodec),
|
||||
reason: str(t.transcodeReason ?? ''),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export const terminateSession = (s: PlexServer, sessionId: string, reason: string) => s.get('/status/sessions/terminate', { sessionId, reason });
|
||||
|
||||
export interface HistoryEntry {
|
||||
id: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
thumb: string;
|
||||
viewedAt: number;
|
||||
accountId: number;
|
||||
deviceId: number;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export async function history(s: PlexServer, size = 30): Promise<HistoryEntry[]> {
|
||||
const mc = await s.container('/status/sessions/history/all', { sort: 'viewedAt:desc', 'X-Plex-Container-Size': size, 'X-Plex-Container-Start': 0 });
|
||||
return arr(mc.Metadata).map((m: any) => ({
|
||||
id: str(m.historyKey ?? m.ratingKey),
|
||||
title: str(m.grandparentTitle || m.title),
|
||||
subtitle: m.type === 'episode' ? `S${num(m.parentIndex)} · E${num(m.index)} ${str(m.title)}` : str(m.year ?? ''),
|
||||
thumb: str(m.grandparentThumb || m.thumb),
|
||||
viewedAt: num(m.viewedAt),
|
||||
accountId: num(m.accountID),
|
||||
deviceId: num(m.deviceID),
|
||||
type: str(m.type),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function accounts(s: PlexServer): Promise<Record<number, string>> {
|
||||
const mc = await s.container('/accounts');
|
||||
return Object.fromEntries(arr(mc.Account).map((a: any) => [num(a.id), str(a.name) || 'Owner']));
|
||||
}
|
||||
|
||||
export interface Device {
|
||||
id: number;
|
||||
name: string;
|
||||
platform: string;
|
||||
clientIdentifier: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export async function devices(s: PlexServer): Promise<Device[]> {
|
||||
const mc = await s.container('/devices');
|
||||
return arr(mc.Device).map((d: any) => ({ id: num(d.id), name: str(d.name), platform: str(d.platform), clientIdentifier: str(d.clientIdentifier), createdAt: num(d.createdAt) }));
|
||||
}
|
||||
|
||||
export const removeDevice = (s: PlexServer, id: number) => s.send('DELETE', `/devices/${id}`);
|
||||
|
||||
export interface BandwidthPoint {
|
||||
at: number;
|
||||
lan: number;
|
||||
wan: number;
|
||||
}
|
||||
|
||||
/** Bandwidth samples grouped by time (bytes per sample interval). */
|
||||
export async function bandwidth(s: PlexServer, timespan = 6): Promise<{ points: BandwidthPoint[]; devices: Record<number, string> }> {
|
||||
const mc = await s.container('/statistics/bandwidth', { timespan });
|
||||
const byAt = new Map<number, BandwidthPoint>();
|
||||
for (const b of arr(mc.StatisticsBandwidth)) {
|
||||
const at = num(b.at);
|
||||
const p = byAt.get(at) ?? { at, lan: 0, wan: 0 };
|
||||
if (bool(b.lan)) p.lan += num(b.bytes);
|
||||
else p.wan += num(b.bytes);
|
||||
byAt.set(at, p);
|
||||
}
|
||||
return {
|
||||
points: [...byAt.values()].sort((a, b) => a.at - b.at),
|
||||
devices: Object.fromEntries(arr(mc.Device).map((d: any) => [num(d.id), str(d.name)])),
|
||||
};
|
||||
}
|
||||
|
||||
export interface ResourcePoint {
|
||||
at: number;
|
||||
hostCpu: number;
|
||||
processCpu: number;
|
||||
hostMemory: number;
|
||||
processMemory: number;
|
||||
}
|
||||
|
||||
export async function resources(s: PlexServer, timespan = 6): Promise<ResourcePoint[]> {
|
||||
const mc = await s.container('/statistics/resources', { timespan });
|
||||
return arr(mc.StatisticsResources)
|
||||
.map((r: any) => ({
|
||||
at: num(r.at),
|
||||
hostCpu: num(r.hostCpuUtilization),
|
||||
processCpu: num(r.processCpuUtilization),
|
||||
hostMemory: num(r.hostMemoryUtilization),
|
||||
processMemory: num(r.processMemoryUtilization),
|
||||
}))
|
||||
.sort((a, b) => a.at - b.at);
|
||||
}
|
||||
|
||||
export interface Activity {
|
||||
uuid: string;
|
||||
type: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
progress: number;
|
||||
cancellable: boolean;
|
||||
}
|
||||
|
||||
export async function activities(s: PlexServer): Promise<Activity[]> {
|
||||
const mc = await s.container('/activities');
|
||||
return arr(mc.Activity).map((a: any) => ({
|
||||
uuid: str(a.uuid),
|
||||
type: str(a.type),
|
||||
title: str(a.title),
|
||||
subtitle: str(a.subtitle),
|
||||
progress: num(a.progress),
|
||||
cancellable: bool(a.cancellable),
|
||||
}));
|
||||
}
|
||||
|
||||
export const cancelActivity = (s: PlexServer, uuid: string) => s.send('DELETE', `/activities/${uuid}`);
|
||||
|
||||
export interface ButlerTask {
|
||||
name: string;
|
||||
title: string;
|
||||
description: string;
|
||||
interval: number;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export async function butlerTasks(s: PlexServer): Promise<ButlerTask[]> {
|
||||
const j = await s.get('/butler');
|
||||
return arr(j?.ButlerTasks?.ButlerTask).map((t: any) => ({
|
||||
name: str(t.name),
|
||||
title: str(t.title) || str(t.name).replace(/^ButlerTask/, '').replace(/([a-z])([A-Z])/g, '$1 $2'),
|
||||
description: str(t.description),
|
||||
interval: num(t.interval),
|
||||
enabled: bool(t.enabled),
|
||||
}));
|
||||
}
|
||||
|
||||
export const runButlerTask = (s: PlexServer, name: string) => s.send('POST', `/butler/${name}`);
|
||||
export const stopButlerTasks = (s: PlexServer) => s.send('DELETE', '/butler');
|
||||
|
||||
export interface RemoteAccess {
|
||||
mappingState: string;
|
||||
mappingError: string;
|
||||
signInState: string;
|
||||
publicAddress: string;
|
||||
publicPort: number;
|
||||
privateAddress: string;
|
||||
privatePort: number;
|
||||
reachabilityPending: boolean;
|
||||
}
|
||||
|
||||
export async function remoteAccess(s: PlexServer): Promise<RemoteAccess> {
|
||||
const j = await s.get('/myplex/account');
|
||||
const m = j?.MyPlex ?? {};
|
||||
return {
|
||||
mappingState: str(m.mappingState),
|
||||
mappingError: str(m.mappingError),
|
||||
signInState: str(m.signInState),
|
||||
publicAddress: str(m.publicAddress),
|
||||
publicPort: num(m.publicPort),
|
||||
privateAddress: str(m.privateAddress),
|
||||
privatePort: num(m.privatePort),
|
||||
reachabilityPending: bool(m.reachabilityPending),
|
||||
};
|
||||
}
|
||||
|
||||
export const refreshReachability = (s: PlexServer) => s.send('PUT', '/myplex/refreshReachability');
|
||||
|
||||
// —— Libraries ——————————————————————————————————————————————————————
|
||||
|
||||
export const scanLibrary = (s: PlexServer, id: string, force = false) => s.get(`/library/sections/${id}/refresh`, force ? { force: 1 } : undefined);
|
||||
export const cancelScan = (s: PlexServer, id: string) => s.send('DELETE', `/library/sections/${id}/refresh`);
|
||||
export const emptyTrash = (s: PlexServer, id: string) => s.send('PUT', `/library/sections/${id}/emptyTrash`);
|
||||
export const analyzeLibrary = (s: PlexServer, id: string) => s.send('PUT', `/library/sections/${id}/analyze`);
|
||||
export const deleteLibrary = (s: PlexServer, id: string) => s.send('DELETE', `/library/sections/${id}`);
|
||||
export const cleanBundles = (s: PlexServer) => s.send('PUT', '/library/clean/bundles');
|
||||
export const optimizeDatabase = (s: PlexServer) => s.send('PUT', '/library/optimize', { async: 1 });
|
||||
export const scanAll = (s: PlexServer) => s.get('/library/sections/all/refresh');
|
||||
|
||||
export async function librarySize(s: PlexServer, sec: Section): Promise<number> {
|
||||
const mc = await s.container(`/library/sections/${sec.id}/all`, { 'X-Plex-Container-Size': 0, type: sec.type === 'show' ? 2 : sec.type === 'artist' ? 8 : undefined });
|
||||
return num(mc.totalSize ?? mc.size);
|
||||
}
|
||||
|
||||
export interface Agent {
|
||||
identifier: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export async function agents(s: PlexServer, mediaType: number): Promise<Agent[]> {
|
||||
const mc = await s.container('/system/agents', { mediaType });
|
||||
return arr(mc.Agent).map((a: any) => ({ identifier: str(a.identifier), name: str(a.name ?? a.title) }));
|
||||
}
|
||||
|
||||
export async function scanners(s: PlexServer, type: number): Promise<string[]> {
|
||||
const mc = await s.container(`/system/scanners/${type}`);
|
||||
return arr(mc.Scanner).map((x: any) => str(x.name));
|
||||
}
|
||||
|
||||
export interface BrowseEntry {
|
||||
key: string;
|
||||
path: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
/** The server's file system, for choosing library folders. */
|
||||
export async function browse(s: PlexServer, key?: string): Promise<BrowseEntry[]> {
|
||||
const mc = await s.container(key ?? '/services/browse', { includeFiles: 0 });
|
||||
return arr(mc.Path).map((p: any) => ({ key: str(p.key), path: str(p.path), title: str(p.title) }));
|
||||
}
|
||||
|
||||
export async function createLibrary(s: PlexServer, opts: { name: string; type: 'movie' | 'show'; agent: string; scanner: string; language: string; locations: string[] }) {
|
||||
const u = new URL(s.url('/library/sections'));
|
||||
u.searchParams.set('name', opts.name);
|
||||
u.searchParams.set('type', opts.type);
|
||||
u.searchParams.set('agent', opts.agent);
|
||||
u.searchParams.set('scanner', opts.scanner);
|
||||
u.searchParams.set('language', opts.language);
|
||||
for (const l of opts.locations) u.searchParams.append('location', l);
|
||||
await s.send('POST', u.toString());
|
||||
}
|
||||
|
||||
export async function updateLibrary(s: PlexServer, sec: Section, opts: { name: string; locations: string[] }) {
|
||||
const u = new URL(s.url(`/library/sections/${sec.id}`));
|
||||
u.searchParams.set('name', opts.name);
|
||||
u.searchParams.set('agent', sec.agent);
|
||||
u.searchParams.set('language', sec.language);
|
||||
for (const l of opts.locations) u.searchParams.append('location', l);
|
||||
await s.send('PUT', u.toString());
|
||||
}
|
||||
|
||||
export async function sectionDetail(s: PlexServer, id: string): Promise<Section> {
|
||||
const mc = await s.container('/library/sections');
|
||||
const d = arr(mc.Directory).find((x: any) => str(x.key) === id);
|
||||
return parseSection(d ?? {});
|
||||
}
|
||||
|
||||
// —— Updates & diagnostics ————————————————————————————————————————————
|
||||
|
||||
export interface UpdateStatus {
|
||||
canInstall: boolean;
|
||||
checkedAt: number;
|
||||
status: number;
|
||||
version: string;
|
||||
added: string;
|
||||
fixed: string;
|
||||
state: string;
|
||||
}
|
||||
|
||||
export async function updateStatus(s: PlexServer): Promise<UpdateStatus | null> {
|
||||
const mc = await s.container('/updater/status');
|
||||
const r = arr(mc.Release)[0];
|
||||
return {
|
||||
canInstall: bool(mc.canInstall),
|
||||
checkedAt: num(mc.checkedAt),
|
||||
status: num(mc.status),
|
||||
version: str(r?.version),
|
||||
added: str(r?.added),
|
||||
fixed: str(r?.fixed),
|
||||
state: str(r?.state),
|
||||
};
|
||||
}
|
||||
|
||||
export const checkForUpdates = (s: PlexServer) => s.send('PUT', '/updater/check', { download: 1 });
|
||||
export const applyUpdate = (s: PlexServer) => s.send('PUT', '/updater/apply');
|
||||
348
src/plex/api.ts
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
/** Library browsing and title operations against one server. */
|
||||
import type { PlexServer, Params } from './client';
|
||||
import { arr, num, parseHub, parseItem, parseSection, str } from './parse';
|
||||
import type { FilterOption, Hub, Item, Page, Section } from './types';
|
||||
|
||||
const items = (mc: any) => arr(mc.Metadata).map(parseItem);
|
||||
|
||||
export async function sections(s: PlexServer): Promise<Section[]> {
|
||||
const mc = await s.container('/library/sections');
|
||||
return arr(mc.Directory).map(parseSection);
|
||||
}
|
||||
|
||||
export async function serverInfo(s: PlexServer) {
|
||||
return s.container('/');
|
||||
}
|
||||
|
||||
const VIDEO_TYPES = new Set(['movie', 'show', 'season', 'episode', 'collection', 'clip']);
|
||||
|
||||
export async function homeHubs(s: PlexServer): Promise<Hub[]> {
|
||||
const mc = await s.container('/hubs', { count: 20, includeExternalMetadata: 1, includeLibraryPlaylists: 0 });
|
||||
return arr(mc.Hub)
|
||||
.map(parseHub)
|
||||
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type));
|
||||
}
|
||||
|
||||
export async function sectionHubs(s: PlexServer, sectionId: string): Promise<Hub[]> {
|
||||
const mc = await s.container(`/hubs/sections/${sectionId}`, { count: 20, includeExternalMetadata: 1 });
|
||||
return arr(mc.Hub)
|
||||
.map(parseHub)
|
||||
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type));
|
||||
}
|
||||
|
||||
/** Continue Watching across libraries (Plex's own hub honors removals). */
|
||||
export async function continueWatching(s: PlexServer, sectionId?: string): Promise<Item[]> {
|
||||
const path = sectionId ? `/hubs/sections/${sectionId}/continueWatching/items` : '/hubs/continueWatching/items';
|
||||
try {
|
||||
const mc = await s.container(path, { 'X-Plex-Container-Size': 40, includeExternalMetadata: 1 });
|
||||
return items(mc);
|
||||
} catch {
|
||||
const mc = await s.container('/library/onDeck', { 'X-Plex-Container-Size': 40 });
|
||||
return items(mc).filter((i) => !sectionId || i.librarySectionId === sectionId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function hubItems(s: PlexServer, key: string, start = 0, size = 60): Promise<Page<Item>> {
|
||||
const mc = await s.container(key, { 'X-Plex-Container-Start': start, 'X-Plex-Container-Size': size, includeExternalMetadata: 1 });
|
||||
const list = items(mc).length ? items(mc) : arr(mc.Hub).flatMap((h: any) => arr(h.Metadata).map(parseItem));
|
||||
return { items: list, total: num(mc.totalSize ?? mc.size), offset: start };
|
||||
}
|
||||
|
||||
/** Metadata types used by library queries. */
|
||||
export const TYPE_ID: Record<string, number> = { movie: 1, show: 2, season: 3, episode: 4, collection: 18 };
|
||||
|
||||
export async function libraryPage(
|
||||
s: PlexServer,
|
||||
sectionId: string,
|
||||
opts: { type?: number; sort?: string; filters?: Record<string, string>; title?: string; start: number; size: number },
|
||||
): Promise<Page<Item>> {
|
||||
const params: Params = {
|
||||
'X-Plex-Container-Start': opts.start,
|
||||
'X-Plex-Container-Size': opts.size,
|
||||
type: opts.type,
|
||||
sort: opts.sort,
|
||||
includeGuids: 0,
|
||||
...opts.filters,
|
||||
};
|
||||
if (opts.title) params['title'] = opts.title;
|
||||
const mc = await s.container(`/library/sections/${sectionId}/all`, params);
|
||||
return { items: items(mc), total: num(mc.totalSize ?? mc.size), offset: opts.start };
|
||||
}
|
||||
|
||||
export interface LibraryMeta {
|
||||
filters: { filter: string; type: string; title: string; key: string }[];
|
||||
sorts: { key: string; title: string; defaultDirection: string }[];
|
||||
}
|
||||
|
||||
export async function libraryMeta(s: PlexServer, sectionId: string, type: number): Promise<LibraryMeta> {
|
||||
const mc = await s.container(`/library/sections/${sectionId}/all`, { includeMeta: 1, 'X-Plex-Container-Size': 0, type });
|
||||
const name = Object.entries(TYPE_ID).find(([, v]) => v === type)?.[0];
|
||||
const t = arr(mc.Meta?.Type).find((x: any) => x.type === name) ?? arr(mc.Meta?.Type)[0];
|
||||
return {
|
||||
filters: arr(t?.Filter).map((f: any) => ({ filter: str(f.filter), type: str(f.filterType), title: str(f.title), key: str(f.key) })),
|
||||
sorts: arr(t?.Sort).map((x: any) => ({ key: str(x.key), title: str(x.title), defaultDirection: str(x.defaultDirection) || 'asc' })),
|
||||
};
|
||||
}
|
||||
|
||||
export async function filterOptions(s: PlexServer, path: string, type?: number): Promise<FilterOption[]> {
|
||||
const mc = await s.container(path, { type });
|
||||
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title) }));
|
||||
}
|
||||
|
||||
export async function firstCharacters(s: PlexServer, sectionId: string, params: Params): Promise<{ key: string; title: string; size: number }[]> {
|
||||
const mc = await s.container(`/library/sections/${sectionId}/firstCharacter`, params);
|
||||
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title), size: num(d.size) }));
|
||||
}
|
||||
|
||||
export async function collections(s: PlexServer, sectionId: string): Promise<Item[]> {
|
||||
const mc = await s.container(`/library/sections/${sectionId}/collections`, { includeCollections: 1, sort: 'titleSort:asc' });
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
export async function metadata(s: PlexServer, id: string): Promise<Item> {
|
||||
const mc = await s.container(`/library/metadata/${id}`, {
|
||||
includeMarkers: 1,
|
||||
includeChapters: 1,
|
||||
includeExtras: 1,
|
||||
includeConcerts: 1,
|
||||
includeOnDeck: 1,
|
||||
includeReviews: 0,
|
||||
includePreferences: 1,
|
||||
includeExternalMedia: 0,
|
||||
checkFiles: 1,
|
||||
asyncAugmentMetadata: 0,
|
||||
});
|
||||
const first = arr(mc.Metadata)[0];
|
||||
if (!first) throw new Error('This title is unavailable.');
|
||||
const item = parseItem(first);
|
||||
item.raw.__librarySectionID = mc.librarySectionID;
|
||||
if (!item.librarySectionId) item.librarySectionId = str(mc.librarySectionID);
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function children(s: PlexServer, id: string): Promise<Item[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/children`, { includeMarkers: 0, excludeAllLeaves: 1 });
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
export async function allLeaves(s: PlexServer, id: string): Promise<Item[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/allLeaves`);
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
/** The show's next episode (Plex's OnDeck), if any. */
|
||||
export async function onDeckFor(_s: PlexServer, item: Item): Promise<Item | null> {
|
||||
const od = arr(item.raw?.OnDeck?.Metadata)[0];
|
||||
if (od) return parseItem(od);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function related(s: PlexServer, id: string): Promise<Hub[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/related`, { includeExternalMetadata: 1, count: 20 });
|
||||
return arr(mc.Hub).map(parseHub).filter((h) => h.items.length);
|
||||
}
|
||||
|
||||
export async function collectionItems(s: PlexServer, id: string): Promise<Item[]> {
|
||||
const mc = await s.container(`/library/collections/${id}/children`);
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
/** Titles featuring a person, across the server's movie and TV libraries. */
|
||||
export async function personTitles(s: PlexServer, personId: string, libs: Section[]): Promise<Item[]> {
|
||||
const video = libs.filter((l) => l.type === 'movie' || l.type === 'show');
|
||||
const results = await Promise.all(
|
||||
video.map(async (l) => {
|
||||
const out: Item[] = [];
|
||||
let start = 0;
|
||||
for (let guard = 0; guard < 10; guard++) {
|
||||
const mc = await s.container(`/library/sections/${l.id}/all`, {
|
||||
actor: personId,
|
||||
sort: 'originallyAvailableAt:desc',
|
||||
'X-Plex-Container-Start': start,
|
||||
'X-Plex-Container-Size': 100,
|
||||
});
|
||||
const batch = items(mc);
|
||||
out.push(...batch);
|
||||
start += batch.length;
|
||||
if (!batch.length || start >= num(mc.totalSize ?? mc.size)) break;
|
||||
}
|
||||
// Directors and writers too, when the person has no acting credits here.
|
||||
if (!out.length) {
|
||||
for (const tag of ['director', 'writer']) {
|
||||
const mc = await s.container(`/library/sections/${l.id}/all`, { [tag]: personId, sort: 'originallyAvailableAt:desc' });
|
||||
out.push(...items(mc));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}),
|
||||
);
|
||||
const seen = new Set<string>();
|
||||
return results.flat().filter((i) => (seen.has(i.id) ? false : (seen.add(i.id), true)));
|
||||
}
|
||||
|
||||
export async function person(s: PlexServer, id: string): Promise<any> {
|
||||
try {
|
||||
const mc = await s.container(`/library/people/${id}`);
|
||||
return arr(mc.Directory)[0] ?? arr(mc.Metadata)[0] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
hubs: Hub[];
|
||||
people: { id: string; tag: string; thumb: string }[];
|
||||
}
|
||||
|
||||
export async function search(s: PlexServer, query: string, sectionId?: string): Promise<SearchResult> {
|
||||
const mc = await s.container('/hubs/search', { query, limit: 30, includeCollections: 1, sectionId, includeExternalMedia: 0 });
|
||||
const hubs = arr(mc.Hub);
|
||||
const people = hubs
|
||||
.filter((h: any) => h.type === 'actor' || h.type === 'director')
|
||||
.flatMap((h: any) => arr(h.Directory ?? h.Metadata))
|
||||
.map((p: any) => ({ id: str(p.id ?? p.ratingKey), tag: str(p.tag ?? p.title), thumb: str(p.thumb) }))
|
||||
.filter((p: any) => p.id && p.tag);
|
||||
const seenPeople = new Set<string>();
|
||||
return {
|
||||
hubs: hubs
|
||||
.map(parseHub)
|
||||
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type)),
|
||||
people: people.filter((p) => (seenPeople.has(p.id) ? false : (seenPeople.add(p.id), true))),
|
||||
};
|
||||
}
|
||||
|
||||
// —— Watch state ————————————————————————————————————————————————
|
||||
|
||||
export async function setWatched(s: PlexServer, id: string, watched: boolean) {
|
||||
await s.get(watched ? '/:/scrobble' : '/:/unscrobble', { key: id, identifier: 'com.plexapp.plugins.library' });
|
||||
}
|
||||
|
||||
export async function removeFromContinueWatching(s: PlexServer, id: string) {
|
||||
await s.send('PUT', '/actions/removeFromContinueWatching', { ratingKey: id });
|
||||
}
|
||||
|
||||
export async function rate(s: PlexServer, id: string, rating: number) {
|
||||
await s.send('PUT', '/:/rate', { key: id, identifier: 'com.plexapp.plugins.library', rating: rating < 0 ? -1 : rating });
|
||||
}
|
||||
|
||||
export async function selectStreams(s: PlexServer, partId: string, sel: { audioStreamID?: string; subtitleStreamID?: string }) {
|
||||
await s.send('PUT', `/library/parts/${partId}`, { allParts: 1, ...sel });
|
||||
}
|
||||
|
||||
// —— Library management ——————————————————————————————————————————
|
||||
|
||||
export const refreshMetadata = (s: PlexServer, id: string, force = true) => s.send('PUT', `/library/metadata/${id}/refresh`, { force: force ? 1 : 0 });
|
||||
export const analyze = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/analyze`);
|
||||
export const unmatch = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/unmatch`);
|
||||
export const splitApart = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/split`);
|
||||
export const merge = (s: PlexServer, id: string, others: string[]) => s.send('PUT', `/library/metadata/${id}/merge`, { ids: others.join(',') });
|
||||
export const deleteItem = (s: PlexServer, id: string) => s.send('DELETE', `/library/metadata/${id}`);
|
||||
export const deleteMedia = (s: PlexServer, id: string, mediaId: string) => s.send('DELETE', `/library/metadata/${id}/media/${mediaId}`);
|
||||
|
||||
export interface MatchCandidate {
|
||||
guid: string;
|
||||
name: string;
|
||||
year: number;
|
||||
score: number;
|
||||
thumb: string;
|
||||
summary: string;
|
||||
matched: boolean;
|
||||
}
|
||||
|
||||
export async function matches(s: PlexServer, id: string, opts: { title?: string; year?: string; agent?: string; language?: string }): Promise<MatchCandidate[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/matches`, {
|
||||
manual: 1,
|
||||
title: opts.title,
|
||||
year: opts.year,
|
||||
agent: opts.agent,
|
||||
language: opts.language,
|
||||
});
|
||||
return arr(mc.SearchResult).map((r: any) => ({
|
||||
guid: str(r.guid),
|
||||
name: str(r.name),
|
||||
year: num(r.year),
|
||||
score: num(r.score),
|
||||
thumb: str(r.thumb),
|
||||
summary: str(r.summary),
|
||||
matched: r.matched === 1 || r.matched === true || r.matched === '1',
|
||||
}));
|
||||
}
|
||||
|
||||
export const applyMatch = (s: PlexServer, id: string, guid: string, name: string, year?: number) =>
|
||||
s.send('PUT', `/library/metadata/${id}/match`, { guid, name, year });
|
||||
|
||||
export async function artworkOptions(s: PlexServer, id: string, kind: 'posters' | 'arts' | 'clearLogos'): Promise<{ key: string; thumb: string; selected: boolean; provider: string }[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/${kind}`);
|
||||
return arr(mc.Metadata).map((m: any) => ({ key: str(m.key), thumb: str(m.thumb || m.key), selected: m.selected === true || m.selected === 1, provider: str(m.provider) }));
|
||||
}
|
||||
|
||||
export const selectArtwork = (s: PlexServer, id: string, kind: 'poster' | 'art' | 'clearLogo', url: string) =>
|
||||
s.send('PUT', `/library/metadata/${id}/${kind}`, { url });
|
||||
|
||||
export async function uploadArtwork(s: PlexServer, id: string, kind: 'posters' | 'arts' | 'clearLogos', data: Blob) {
|
||||
await s.send('POST', `/library/metadata/${id}/${kind}`, undefined, { body: data });
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits metadata through the section `all` endpoint, as Plex Web does. Field
|
||||
* values are locked so later refreshes keep them.
|
||||
*/
|
||||
export async function editMetadata(
|
||||
s: PlexServer,
|
||||
item: Item,
|
||||
fields: Record<string, string>,
|
||||
tagFields: Record<string, { add: string[]; remove: string[] }> = {},
|
||||
locks: Record<string, boolean> = {},
|
||||
) {
|
||||
const type = TYPE_ID[item.type] ?? 1;
|
||||
const params: Params = { type, id: item.id, includeExternalMedia: 1 };
|
||||
for (const [k, v] of Object.entries(fields)) {
|
||||
params[`${k}.value`] = v;
|
||||
params[`${k}.locked`] = locks[k] === false ? 0 : 1;
|
||||
}
|
||||
for (const [tag, change] of Object.entries(tagFields)) {
|
||||
change.add.forEach((v, i) => (params[`${tag}[${i}].tag.tag`] = v));
|
||||
if (change.remove.length) params[`${tag}[].tag.tag-`] = change.remove.join(',');
|
||||
params[`${tag}.locked`] = locks[tag] === false ? 0 : 1;
|
||||
}
|
||||
for (const [k, locked] of Object.entries(locks)) {
|
||||
if (!(k in fields) && !(k in tagFields)) params[`${k}.locked`] = locked ? 1 : 0;
|
||||
}
|
||||
const section = item.librarySectionId || str(item.raw?.__librarySectionID);
|
||||
await s.send('PUT', `/library/sections/${section}/all`, params);
|
||||
}
|
||||
|
||||
/** Collections: create, add, remove. */
|
||||
export async function addToCollection(s: PlexServer, item: Item, collection: string) {
|
||||
await editMetadata(s, item, {}, { collection: { add: [collection], remove: [] } });
|
||||
}
|
||||
|
||||
export async function removeFromCollection(s: PlexServer, collectionId: string, itemId: string) {
|
||||
await s.send('DELETE', `/library/collections/${collectionId}/items/${itemId}`);
|
||||
}
|
||||
|
||||
export async function playlists(s: PlexServer): Promise<Item[]> {
|
||||
const mc = await s.container('/playlists', { playlistType: 'video', smart: 0 });
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
export async function addToPlaylist(s: PlexServer, playlistId: string, machineId: string, itemId: string) {
|
||||
await s.send('PUT', `/playlists/${playlistId}/items`, { uri: `server://${machineId}/com.plexapp.plugins.library/library/metadata/${itemId}` });
|
||||
}
|
||||
|
||||
export async function createPlaylist(s: PlexServer, title: string, machineId: string, itemId: string) {
|
||||
await s.send('POST', '/playlists', {
|
||||
type: 'video',
|
||||
title,
|
||||
smart: 0,
|
||||
uri: `server://${machineId}/com.plexapp.plugins.library/library/metadata/${itemId}`,
|
||||
});
|
||||
}
|
||||
|
||||
/** Library change detection: small response; compared every few seconds. */
|
||||
export async function libraryRevision(s: PlexServer): Promise<string> {
|
||||
const mc = await s.container('/library/sections');
|
||||
return arr(mc.Directory)
|
||||
.map((d: any) => [d.key, d.contentChangedAt, d.scannedAt, d.updatedAt].join(':'))
|
||||
.join('|');
|
||||
}
|
||||
183
src/plex/client.ts
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import { httpFetch } from '../platform/native';
|
||||
|
||||
export const PRODUCT = 'Kaleido';
|
||||
export const PLATFORM = 'Windows';
|
||||
|
||||
export class PlexError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status = 0,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
let clientId = '';
|
||||
let version = '0.1.0';
|
||||
let deviceName = 'Windows PC';
|
||||
|
||||
/** A stable, random identifier for this installation (not secret). */
|
||||
export function clientIdentifier(): string {
|
||||
if (clientId) return clientId;
|
||||
clientId = localStorage.getItem('kaleido.clientId') ?? '';
|
||||
if (!clientId) {
|
||||
clientId = crypto.randomUUID();
|
||||
localStorage.setItem('kaleido.clientId', clientId);
|
||||
}
|
||||
return clientId;
|
||||
}
|
||||
|
||||
export function configureClient(opts: { version?: string; deviceName?: string }) {
|
||||
if (opts.version) version = opts.version;
|
||||
if (opts.deviceName) deviceName = opts.deviceName;
|
||||
}
|
||||
|
||||
export function plexHeaders(token?: string | null): Record<string, string> {
|
||||
const h: Record<string, string> = {
|
||||
Accept: 'application/json',
|
||||
'X-Plex-Product': PRODUCT,
|
||||
'X-Plex-Version': version,
|
||||
'X-Plex-Client-Identifier': clientIdentifier(),
|
||||
'X-Plex-Platform': PLATFORM,
|
||||
'X-Plex-Platform-Version': '11',
|
||||
'X-Plex-Device': 'Windows',
|
||||
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
|
||||
'X-Plex-Model': 'Desktop',
|
||||
'X-Plex-Provides': 'player',
|
||||
'X-Plex-Language': navigator.language || 'en',
|
||||
};
|
||||
if (token) h['X-Plex-Token'] = token;
|
||||
return h;
|
||||
}
|
||||
|
||||
/** Query-string equivalents of the identification headers (for media URLs). */
|
||||
export function plexQuery(token?: string | null): Record<string, string> {
|
||||
const q: Record<string, string> = {
|
||||
'X-Plex-Product': PRODUCT,
|
||||
'X-Plex-Version': version,
|
||||
'X-Plex-Client-Identifier': clientIdentifier(),
|
||||
'X-Plex-Platform': PLATFORM,
|
||||
'X-Plex-Device': 'Windows',
|
||||
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
|
||||
};
|
||||
if (token) q['X-Plex-Token'] = token;
|
||||
return q;
|
||||
}
|
||||
|
||||
export type Params = Record<string, string | number | boolean | undefined | null>;
|
||||
|
||||
export function withParams(url: string, params?: Params): string {
|
||||
if (!params) return url;
|
||||
const u = new URL(url);
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v === undefined || v === null || v === '') continue;
|
||||
u.searchParams.set(k, typeof v === 'boolean' ? (v ? '1' : '0') : String(v));
|
||||
}
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
params?: Params;
|
||||
body?: BodyInit | null;
|
||||
headers?: Record<string, string>;
|
||||
timeout?: number;
|
||||
signal?: AbortSignal;
|
||||
/** Return raw text instead of parsed JSON. */
|
||||
text?: boolean;
|
||||
}
|
||||
|
||||
const statusMessage = (status: number) =>
|
||||
status === 401 || status === 403
|
||||
? 'Plex declined this request. Sign in again or check your access to this server.'
|
||||
: status === 404
|
||||
? 'This item is no longer available.'
|
||||
: status === 400
|
||||
? 'Plex could not process this request.'
|
||||
: status >= 500
|
||||
? `The Plex server reported an error (${status}).`
|
||||
: `Plex could not complete the request (${status}).`;
|
||||
|
||||
export async function plexRequest<T = any>(url: string, token: string | null | undefined, opts: RequestOptions = {}): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), opts.timeout ?? 30000);
|
||||
const onAbort = () => controller.abort();
|
||||
opts.signal?.addEventListener('abort', onAbort);
|
||||
let response: Response;
|
||||
try {
|
||||
response = await httpFetch(withParams(url, opts.params), {
|
||||
method: opts.method ?? 'GET',
|
||||
headers: { ...plexHeaders(token), ...opts.headers },
|
||||
body: opts.body ?? undefined,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (e: any) {
|
||||
if (opts.signal?.aborted) throw e;
|
||||
throw new PlexError(controller.signal.aborted ? 'The server took too long to respond.' : 'Could not reach the server.', 0);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
opts.signal?.removeEventListener('abort', onAbort);
|
||||
}
|
||||
if (!response.ok) throw new PlexError(statusMessage(response.status), response.status);
|
||||
const text = await response.text();
|
||||
if (opts.text) return text as unknown as T;
|
||||
if (!text.trim()) return {} as T;
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return text as unknown as T;
|
||||
}
|
||||
}
|
||||
|
||||
/** A connection to one Plex Media Server. */
|
||||
export class PlexServer {
|
||||
constructor(
|
||||
public readonly uri: string,
|
||||
public readonly token: string,
|
||||
public readonly machineId: string,
|
||||
public readonly name: string,
|
||||
public readonly owned: boolean,
|
||||
public readonly local: boolean,
|
||||
) {}
|
||||
|
||||
url(path: string, params?: Params): string {
|
||||
const base = path.startsWith('http') ? path : `${this.uri.replace(/\/$/, '')}/${path.replace(/^\//, '')}`;
|
||||
return withParams(base, params);
|
||||
}
|
||||
|
||||
/** URL including the token, for media loaded outside fetch (images, video). */
|
||||
signed(path: string, params?: Params): string {
|
||||
return this.url(path, { ...params, 'X-Plex-Token': this.token });
|
||||
}
|
||||
|
||||
async get<T = any>(path: string, params?: Params, opts: RequestOptions = {}): Promise<T> {
|
||||
return plexRequest<T>(this.url(path), this.token, { ...opts, params });
|
||||
}
|
||||
|
||||
async container(path: string, params?: Params, opts: RequestOptions = {}): Promise<any> {
|
||||
const j = await this.get(path, params, opts);
|
||||
return j?.MediaContainer ?? {};
|
||||
}
|
||||
|
||||
async send(method: 'POST' | 'PUT' | 'DELETE', path: string, params?: Params, opts: RequestOptions = {}): Promise<any> {
|
||||
return plexRequest(this.url(path), this.token, { ...opts, method, params });
|
||||
}
|
||||
|
||||
/** Photo transcoder URL, sized for the device pixel ratio. */
|
||||
image(path: string | undefined, width: number, height: number, opts: { blur?: number; quality?: number; format?: 'jpeg' | 'png' } = {}): string {
|
||||
if (!path) return '';
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
const w = Math.round(width * dpr);
|
||||
const h = Math.round(height * dpr);
|
||||
return this.signed('/photo/:/transcode', {
|
||||
url: path,
|
||||
width: w,
|
||||
height: h,
|
||||
minSize: 1,
|
||||
upscale: 1,
|
||||
quality: opts.quality,
|
||||
blur: opts.blur,
|
||||
format: opts.format ?? 'jpeg',
|
||||
});
|
||||
}
|
||||
}
|
||||
248
src/plex/parse.ts
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
import type { AudienceScore, Chapter, Hub, Item, Marker, Media, Part, Role, Section, Stream, Tag } from './types';
|
||||
|
||||
const arr = (v: any): any[] => (Array.isArray(v) ? v : v ? [v] : []);
|
||||
const str = (v: any): string => (v === undefined || v === null ? '' : String(v));
|
||||
const num = (v: any): number => {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
};
|
||||
const bool = (v: any): boolean => v === true || v === 1 || v === '1' || v === 'true';
|
||||
|
||||
const tags = (v: any): Tag[] =>
|
||||
arr(v).map((t) => ({ id: str(t.id), tag: str(t.tag), filter: str(t.filter) })).filter((t) => t.tag);
|
||||
|
||||
export function parseStream(s: any): Stream {
|
||||
return {
|
||||
id: str(s.id),
|
||||
streamType: num(s.streamType),
|
||||
codec: str(s.codec),
|
||||
index: s.index === undefined ? -1 : num(s.index),
|
||||
language: str(s.language),
|
||||
languageCode: str(s.languageCode ?? s.languageTag),
|
||||
displayTitle: str(s.displayTitle ?? s.title ?? s.language),
|
||||
extendedDisplayTitle: str(s.extendedDisplayTitle ?? s.displayTitle),
|
||||
title: str(s.title),
|
||||
selected: bool(s.selected),
|
||||
default: bool(s.default),
|
||||
forced: bool(s.forced),
|
||||
key: str(s.key),
|
||||
channels: num(s.channels),
|
||||
audioChannelLayout: str(s.audioChannelLayout),
|
||||
bitrate: num(s.bitrate),
|
||||
width: num(s.width),
|
||||
height: num(s.height),
|
||||
frameRate: num(s.frameRate),
|
||||
profile: str(s.profile),
|
||||
colorTrc: str(s.colorTrc),
|
||||
colorPrimaries: str(s.colorPrimaries),
|
||||
bitDepth: num(s.bitDepth),
|
||||
doviPresent: bool(s.DOVIPresent),
|
||||
hearingImpaired: bool(s.hearingImpaired),
|
||||
samplingRate: num(s.samplingRate),
|
||||
};
|
||||
}
|
||||
|
||||
function parsePart(p: any): Part {
|
||||
return {
|
||||
id: str(p.id),
|
||||
key: str(p.key),
|
||||
file: str(p.file),
|
||||
size: num(p.size),
|
||||
duration: num(p.duration),
|
||||
container: str(p.container),
|
||||
indexes: str(p.indexes),
|
||||
streams: arr(p.Stream).map(parseStream),
|
||||
accessible: p.accessible === undefined ? true : bool(p.accessible),
|
||||
exists: p.exists === undefined ? true : bool(p.exists),
|
||||
};
|
||||
}
|
||||
|
||||
export function dynamicRange(video?: Stream): string {
|
||||
if (!video) return '';
|
||||
if (video.doviPresent) return 'Dolby Vision';
|
||||
if (video.colorTrc === 'smpte2084') return 'HDR10';
|
||||
if (video.colorTrc === 'arib-std-b67') return 'HLG';
|
||||
return '';
|
||||
}
|
||||
|
||||
function parseMedia(m: any): Media {
|
||||
const parts = arr(m.Part).map(parsePart);
|
||||
const streams = parts.flatMap((p) => p.streams);
|
||||
const video = streams.find((s) => s.streamType === 1);
|
||||
const audio = streams.filter((s) => s.streamType === 2);
|
||||
return {
|
||||
id: str(m.id),
|
||||
container: str(m.container),
|
||||
videoCodec: str(m.videoCodec),
|
||||
audioCodec: str(m.audioCodec),
|
||||
videoResolution: str(m.videoResolution),
|
||||
width: num(m.width),
|
||||
height: num(m.height),
|
||||
bitrate: num(m.bitrate),
|
||||
duration: num(m.duration),
|
||||
audioChannels: num(m.audioChannels),
|
||||
videoProfile: str(m.videoProfile),
|
||||
videoFrameRate: str(m.videoFrameRate),
|
||||
aspectRatio: num(m.aspectRatio),
|
||||
optimizedForStreaming: bool(m.optimizedForStreaming),
|
||||
title: str(m.title),
|
||||
parts,
|
||||
dynamicRange: dynamicRange(video) || (str(m.videoDynamicRange ?? '') === 'HDR' ? 'HDR10' : ''),
|
||||
atmos: audio.some((s) => /atmos/i.test(s.displayTitle + s.extendedDisplayTitle + s.title)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Plex normalizes external ratings to 0–10. Never substitute the critic `rating` field. */
|
||||
export function parseScores(j: any): AudienceScore[] {
|
||||
const out: AudienceScore[] = [];
|
||||
const add = (image: string, value: number, kind: 'audience' | 'critic') => {
|
||||
if (!Number.isFinite(value) || value < 0 || value > 10 || !image) return;
|
||||
let source: AudienceScore['source'] | null = null;
|
||||
if (image.startsWith('rottentomatoes://')) source = 'Rotten Tomatoes';
|
||||
else if (image.startsWith('imdb://')) source = 'IMDb';
|
||||
else if (image.startsWith('themoviedb://')) source = 'TMDB';
|
||||
else if (image.startsWith('thetvdb://') || image.startsWith('tvdb://')) source = 'TVDB';
|
||||
if (!source || out.some((s) => s.source === source && s.kind === kind)) return;
|
||||
out.push({ source, value, kind, image });
|
||||
};
|
||||
for (const r of arr(j.Rating)) add(str(r.image), num(r.value), r.type === 'critic' ? 'critic' : 'audience');
|
||||
if (j.audienceRatingImage) add(str(j.audienceRatingImage), num(j.audienceRating), 'audience');
|
||||
if (j.ratingImage) add(str(j.ratingImage), num(j.rating), 'critic');
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseUltraBlur(j: any): Item['ultraBlur'] {
|
||||
const u = arr(j.UltraBlurColors)[0];
|
||||
if (!u?.topLeft) return null;
|
||||
return { topLeft: str(u.topLeft), topRight: str(u.topRight), bottomRight: str(u.bottomRight), bottomLeft: str(u.bottomLeft) };
|
||||
}
|
||||
|
||||
export function parseItem(j: any): Item {
|
||||
const images = arr(j.Image);
|
||||
const image = (type: string) => str(images.find((i) => i.type === type)?.url);
|
||||
const roles: Role[] = arr(j.Role)
|
||||
.map((r) => ({
|
||||
id: str(r.id) || str(r.filter).replace(/^actor=/, ''),
|
||||
tag: str(r.tag),
|
||||
filter: str(r.filter),
|
||||
role: str(r.role),
|
||||
thumb: str(r.thumb),
|
||||
}))
|
||||
.filter((r) => r.tag);
|
||||
const type = str(j.type);
|
||||
return {
|
||||
id: str(j.ratingKey ?? j.key),
|
||||
key: str(j.key),
|
||||
guid: str(j.guid),
|
||||
guids: arr(j.Guid).map((g) => str(g.id)),
|
||||
type,
|
||||
subtype: str(j.subtype),
|
||||
title: str(j.title),
|
||||
titleSort: str(j.titleSort),
|
||||
originalTitle: str(j.originalTitle),
|
||||
summary: str(j.summary),
|
||||
tagline: str(j.tagline),
|
||||
year: num(j.year ?? j.parentYear),
|
||||
originallyAvailableAt: str(j.originallyAvailableAt),
|
||||
duration: num(j.duration),
|
||||
viewOffset: num(j.viewOffset),
|
||||
viewCount: num(j.viewCount),
|
||||
lastViewedAt: num(j.lastViewedAt),
|
||||
addedAt: num(j.addedAt),
|
||||
updatedAt: num(j.updatedAt),
|
||||
thumb: str(j.thumb),
|
||||
art: str(j.art ?? j.grandparentArt ?? j.parentArt),
|
||||
logo: image('clearLogo'),
|
||||
theme: str(j.theme ?? j.parentTheme ?? j.grandparentTheme),
|
||||
contentRating: str(j.contentRating),
|
||||
studio: str(j.studio),
|
||||
parentId: str(j.parentRatingKey),
|
||||
parentKey: str(j.parentKey),
|
||||
parentTitle: str(j.parentTitle),
|
||||
parentIndex: num(j.parentIndex),
|
||||
parentThumb: str(j.parentThumb),
|
||||
grandparentId: str(j.grandparentRatingKey),
|
||||
grandparentKey: str(j.grandparentKey),
|
||||
grandparentTitle: str(j.grandparentTitle),
|
||||
grandparentThumb: str(j.grandparentThumb),
|
||||
grandparentArt: str(j.grandparentArt),
|
||||
index: num(j.index),
|
||||
leafCount: num(j.leafCount),
|
||||
viewedLeafCount: num(j.viewedLeafCount),
|
||||
childCount: num(j.childCount),
|
||||
genres: tags(j.Genre),
|
||||
directors: tags(j.Director),
|
||||
writers: tags(j.Writer),
|
||||
producers: tags(j.Producer),
|
||||
countries: tags(j.Country),
|
||||
labels: tags(j.Label),
|
||||
collections: tags(j.Collection),
|
||||
roles,
|
||||
scores: parseScores(j),
|
||||
userRating: num(j.userRating),
|
||||
media: arr(j.Media).map(parseMedia),
|
||||
markers: arr(j.Marker).map(
|
||||
(m): Marker => ({
|
||||
id: str(m.id),
|
||||
type: str(m.type),
|
||||
start: num(m.startTimeOffset),
|
||||
end: num(m.endTimeOffset),
|
||||
final: bool(m.final),
|
||||
}),
|
||||
),
|
||||
chapters: arr(j.Chapter).map(
|
||||
(c, i): Chapter => ({
|
||||
index: num(c.index) || i + 1,
|
||||
title: str(c.tag ?? c.title) || `Chapter ${i + 1}`,
|
||||
start: num(c.startTimeOffset),
|
||||
end: num(c.endTimeOffset),
|
||||
thumb: str(c.thumb),
|
||||
}),
|
||||
),
|
||||
extras: arr(j.Extras?.Metadata).map(parseItem),
|
||||
librarySectionId: str(j.librarySectionID),
|
||||
librarySectionTitle: str(j.librarySectionTitle),
|
||||
librarySectionKey: str(j.librarySectionKey),
|
||||
smart: bool(j.smart),
|
||||
editionTitle: str(j.editionTitle),
|
||||
skipChildren: bool(j.skipChildren),
|
||||
ultraBlur: parseUltraBlur(j),
|
||||
raw: j,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseHub(h: any): Hub {
|
||||
return {
|
||||
id: str(h.hubIdentifier ?? h.key ?? h.title),
|
||||
key: str(h.key),
|
||||
title: str(h.title),
|
||||
type: str(h.type),
|
||||
context: str(h.context),
|
||||
size: num(h.size),
|
||||
more: bool(h.more),
|
||||
style: str(h.style),
|
||||
items: arr(h.Metadata).map(parseItem),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSection(d: any): Section {
|
||||
return {
|
||||
id: str(d.key),
|
||||
key: str(d.key),
|
||||
title: str(d.title),
|
||||
type: str(d.type),
|
||||
agent: str(d.agent),
|
||||
scanner: str(d.scanner),
|
||||
language: str(d.language),
|
||||
thumb: str(d.thumb),
|
||||
art: str(d.art),
|
||||
locations: arr(d.Location).map((l) => ({ id: str(l.id), path: str(l.path) })),
|
||||
scannedAt: num(d.scannedAt),
|
||||
updatedAt: num(d.updatedAt),
|
||||
contentChangedAt: num(d.contentChangedAt),
|
||||
refreshing: bool(d.refreshing),
|
||||
hidden: num(d.hidden) > 0,
|
||||
};
|
||||
}
|
||||
|
||||
export { arr, str, num, bool };
|
||||
109
src/plex/playback.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
/** Delivery decisions, stream URLs and progress reporting for playback. */
|
||||
import { plexQuery, type PlexServer } from './client';
|
||||
import type { Item, Media, Part } from './types';
|
||||
import { QUALITY_PROFILE, type Quality } from '../app/settings';
|
||||
|
||||
export interface Delivery {
|
||||
url: string;
|
||||
mode: 'direct' | 'transcode' | 'local';
|
||||
/** Plex transcode session; stopped when playback ends. */
|
||||
session?: string;
|
||||
label: string;
|
||||
/** Media timestamps are absolute (Plex HLS); don't rebase to zero. */
|
||||
absoluteTime: boolean;
|
||||
}
|
||||
|
||||
/** mpv EDL joins multi-part files (CD1/CD2) into one timeline. */
|
||||
function edl(urls: string[]): string {
|
||||
return 'edl://' + urls.map((u) => `%${new TextEncoder().encode(u).length}%${u}`).join(';');
|
||||
}
|
||||
|
||||
export function directUrl(server: PlexServer, media: Media): string {
|
||||
const urls = media.parts.map((p) => server.signed(p.key, plexQuery()));
|
||||
return urls.length > 1 ? edl(urls) : urls[0];
|
||||
}
|
||||
|
||||
export function transcodeUrl(
|
||||
server: PlexServer,
|
||||
item: Item,
|
||||
opts: { mediaIndex: number; quality: Exclude<Quality, 'original'> | 'remux'; offsetMs: number; session: string; local: boolean; audioStreamID?: string; subtitleStreamID?: string },
|
||||
): string {
|
||||
const media = item.media[opts.mediaIndex];
|
||||
const profile = opts.quality === 'remux' ? null : QUALITY_PROFILE[opts.quality];
|
||||
const extra = [
|
||||
'add-transcode-target(type=videoProfile&context=streaming&protocol=hls&container=mpegts&videoCodec=h264,hevc&audioCodec=aac,ac3,eac3,mp3,opus)',
|
||||
'add-limitation(scope=videoCodec&scopeName=hevc&type=upperBound&name=video.bitDepth&value=10)',
|
||||
].join('+');
|
||||
return server.signed('/video/:/transcode/universal/start.m3u8', {
|
||||
...plexQuery(),
|
||||
path: `/library/metadata/${item.id}`,
|
||||
mediaIndex: opts.mediaIndex,
|
||||
partIndex: 0,
|
||||
protocol: 'hls',
|
||||
session: opts.session,
|
||||
offset: (opts.offsetMs / 1000).toFixed(1),
|
||||
fastSeek: 1,
|
||||
directPlay: 0,
|
||||
directStream: profile ? 1 : 1,
|
||||
directStreamAudio: 1,
|
||||
copyts: 1,
|
||||
hasMDE: 1,
|
||||
mediaBufferSize: 102400,
|
||||
location: opts.local ? 'lan' : 'wan',
|
||||
videoQuality: 100,
|
||||
maxVideoBitrate: profile ? profile.kbps : Math.max(media?.bitrate ?? 0, 200000),
|
||||
videoResolution: profile ? `${profile.width}x${profile.height}` : `${media?.width || 3840}x${media?.height || 2160}`,
|
||||
subtitles: 'burn',
|
||||
subtitleSize: 100,
|
||||
audioBoost: 100,
|
||||
autoAdjustQuality: 0,
|
||||
'X-Plex-Session-Identifier': opts.session,
|
||||
'X-Plex-Client-Profile-Extra': extra,
|
||||
});
|
||||
}
|
||||
|
||||
export function partAt(media: Media, timeMs: number): { part: Part; local: number } {
|
||||
let start = 0;
|
||||
for (const p of media.parts) {
|
||||
if (!p.duration || timeMs < start + p.duration) return { part: p, local: timeMs - start };
|
||||
start += p.duration;
|
||||
}
|
||||
const last = media.parts[media.parts.length - 1];
|
||||
return { part: last, local: timeMs - (start - (last?.duration ?? 0)) };
|
||||
}
|
||||
|
||||
/** Server-generated preview thumbnail for a position, if the part has an index. */
|
||||
export function previewUrl(server: PlexServer, media: Media | undefined, timeMs: number): string {
|
||||
if (!media) return '';
|
||||
const { part, local } = partAt(media, timeMs);
|
||||
if (!part?.indexes.split(',').includes('sd')) return '';
|
||||
return server.signed(`/library/parts/${part.id}/indexes/sd/${Math.max(0, Math.floor(local / 5000) * 5000)}`);
|
||||
}
|
||||
|
||||
export async function reportTimeline(
|
||||
server: PlexServer,
|
||||
item: Item,
|
||||
state: 'playing' | 'paused' | 'buffering' | 'stopped',
|
||||
timeMs: number,
|
||||
session: string,
|
||||
extra: Record<string, string | number> = {},
|
||||
) {
|
||||
await server.get(
|
||||
'/:/timeline',
|
||||
{
|
||||
ratingKey: item.id,
|
||||
key: item.key || `/library/metadata/${item.id}`,
|
||||
state,
|
||||
time: Math.max(0, Math.round(timeMs)),
|
||||
duration: Math.round(item.duration),
|
||||
identifier: 'com.plexapp.plugins.library',
|
||||
hasMDE: 1,
|
||||
...extra,
|
||||
},
|
||||
{ headers: { 'X-Plex-Session-Identifier': session }, timeout: 10000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function stopTranscode(server: PlexServer, session: string) {
|
||||
await server.get('/video/:/transcode/universal/stop', { session }).catch(() => {});
|
||||
}
|
||||
114
src/plex/plex.test.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { parseItem, parseScores } from './parse';
|
||||
import { isLocalAddress } from './account';
|
||||
import { partAt } from './playback';
|
||||
import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format';
|
||||
import { buildFeatures } from '../screens/discover';
|
||||
import type { Hub } from './types';
|
||||
|
||||
const movie = (over: Record<string, unknown> = {}) =>
|
||||
parseItem({
|
||||
ratingKey: '9776',
|
||||
key: '/library/metadata/9776',
|
||||
type: 'movie',
|
||||
title: '2 Fast 2 Furious',
|
||||
summary: 'An ex-cop…',
|
||||
art: '/art',
|
||||
year: 2003,
|
||||
duration: 6000000,
|
||||
Image: [{ type: 'clearLogo', url: '/logo' }],
|
||||
UltraBlurColors: [{ topLeft: '162e4f', topRight: '30618f', bottomRight: '345e96', bottomLeft: '1c2c56' }],
|
||||
Media: [
|
||||
{
|
||||
id: '1',
|
||||
videoResolution: '4k',
|
||||
audioChannels: 8,
|
||||
Part: [
|
||||
{
|
||||
id: '10',
|
||||
key: '/library/parts/10/file.mkv',
|
||||
duration: 3000000,
|
||||
Stream: [
|
||||
{ id: 's1', streamType: 1, codec: 'hevc', DOVIPresent: true, index: 0 },
|
||||
{ id: 's2', streamType: 2, codec: 'truehd', displayTitle: 'English (TrueHD 7.1 Atmos)', index: 1 },
|
||||
],
|
||||
},
|
||||
{ id: '11', key: '/library/parts/11/file.mkv', duration: 3000000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('parsing', () => {
|
||||
it('reads logos, UltraBlur colors and format facts', () => {
|
||||
const m = movie();
|
||||
expect(m.logo).toBe('/logo');
|
||||
expect(m.ultraBlur?.topRight).toBe('30618f');
|
||||
expect(m.media[0].dynamicRange).toBe('Dolby Vision');
|
||||
expect(m.media[0].atmos).toBe(true);
|
||||
expect(formatBadges(m)).toEqual(['4K', 'DOLBY VISION', 'ATMOS']);
|
||||
});
|
||||
|
||||
it('keeps audience scores and never substitutes critic ratings', () => {
|
||||
const scores = parseScores({
|
||||
Rating: [
|
||||
{ image: 'rottentomatoes://image.rating.upright', value: 7.9, type: 'audience' },
|
||||
{ image: 'rottentomatoes://image.rating.ripe', value: 9.1, type: 'critic' },
|
||||
{ image: 'imdb://image.rating', value: 7.2, type: 'audience' },
|
||||
],
|
||||
});
|
||||
expect(scores.filter((s) => s.kind === 'audience').map((s) => s.source)).toEqual(['Rotten Tomatoes', 'IMDb']);
|
||||
expect(scores.find((s) => s.kind === 'critic')?.value).toBe(9.1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('watched rules', () => {
|
||||
it('treats a resumed title as watched only past the threshold', () => {
|
||||
expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(false);
|
||||
expect(isWatched(movie({ viewCount: 1, viewOffset: 5700000 }), 90)).toBe(true);
|
||||
expect(isWatched(movie({ viewCount: 1 }), 90)).toBe(true);
|
||||
});
|
||||
|
||||
it('uses episode counts for shows', () => {
|
||||
expect(isWatched(parseItem({ type: 'show', leafCount: 10, viewedLeafCount: 10 }))).toBe(true);
|
||||
expect(isWatched(parseItem({ type: 'show', leafCount: 10, viewedLeafCount: 3 }))).toBe(false);
|
||||
});
|
||||
|
||||
it('formats durations and time left', () => {
|
||||
expect(duration(6000000)).toBe('1h 40m');
|
||||
expect(duration(45 * 60000)).toBe('45m');
|
||||
expect(remaining(movie({ viewOffset: 3000000 }))).toBe('50m left');
|
||||
});
|
||||
});
|
||||
|
||||
describe('connections', () => {
|
||||
it('recognizes local plex.direct and private addresses', () => {
|
||||
expect(isLocalAddress('https://192-168-50-81.abc.plex.direct:32400')).toBe(true);
|
||||
expect(isLocalAddress('http://10.0.0.5:32400')).toBe(true);
|
||||
expect(isLocalAddress('https://38-130-3-235.abc.plex.direct:27015')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('playback', () => {
|
||||
it('maps a position to the right part of a multi-part title', () => {
|
||||
const m = movie().media[0];
|
||||
expect(partAt(m, 1000).part.id).toBe('10');
|
||||
expect(partAt(m, 4000000)).toMatchObject({ local: 1000000 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('features', () => {
|
||||
it('interleaves sources, skips in-progress titles and needs artwork', () => {
|
||||
const hub = (id: string, items: Record<string, unknown>[]): Hub => ({ id, key: '', title: id, type: 'movie', context: '', size: items.length, more: false, style: '', items: items.map((i) => movie(i)) });
|
||||
const features = buildFeatures([
|
||||
hub('movie.recentlyreleased.1', [{ ratingKey: 'a' }, { ratingKey: 'b', viewOffset: 100 }]),
|
||||
hub('movie.topunwatched.1', [{ ratingKey: 'c' }, { ratingKey: 'd', art: '' }]),
|
||||
]);
|
||||
expect(features.map((f) => f.item.id).sort()).toEqual(['a', 'c']);
|
||||
});
|
||||
|
||||
it('builds an artwork wash from UltraBlur colors', () => {
|
||||
expect(washGradient(movie().ultraBlur)).toContain('rgba(48, 97, 143');
|
||||
});
|
||||
});
|
||||
277
src/plex/types.ts
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
/** Normalized Plex models. Parsing lives in parse.ts; raw JSON is kept for editors. */
|
||||
|
||||
export type ItemType =
|
||||
| 'movie'
|
||||
| 'show'
|
||||
| 'season'
|
||||
| 'episode'
|
||||
| 'collection'
|
||||
| 'clip'
|
||||
| 'playlist'
|
||||
| 'person'
|
||||
| 'artist'
|
||||
| 'album'
|
||||
| 'track'
|
||||
| 'photo'
|
||||
| string;
|
||||
|
||||
export interface Stream {
|
||||
id: string;
|
||||
streamType: 1 | 2 | 3 | number; // video, audio, subtitle
|
||||
codec: string;
|
||||
index: number;
|
||||
language: string;
|
||||
languageCode: string;
|
||||
displayTitle: string;
|
||||
extendedDisplayTitle: string;
|
||||
title: string;
|
||||
selected: boolean;
|
||||
default: boolean;
|
||||
forced: boolean;
|
||||
key: string; // external subtitle path
|
||||
channels: number;
|
||||
audioChannelLayout: string;
|
||||
bitrate: number;
|
||||
width: number;
|
||||
height: number;
|
||||
frameRate: number;
|
||||
profile: string;
|
||||
colorTrc: string;
|
||||
colorPrimaries: string;
|
||||
bitDepth: number;
|
||||
doviPresent: boolean;
|
||||
hearingImpaired: boolean;
|
||||
samplingRate: number;
|
||||
}
|
||||
|
||||
export interface Part {
|
||||
id: string;
|
||||
key: string;
|
||||
file: string;
|
||||
size: number;
|
||||
duration: number;
|
||||
container: string;
|
||||
indexes: string;
|
||||
streams: Stream[];
|
||||
accessible: boolean;
|
||||
exists: boolean;
|
||||
}
|
||||
|
||||
export interface Media {
|
||||
id: string;
|
||||
container: string;
|
||||
videoCodec: string;
|
||||
audioCodec: string;
|
||||
videoResolution: string;
|
||||
width: number;
|
||||
height: number;
|
||||
bitrate: number;
|
||||
duration: number;
|
||||
audioChannels: number;
|
||||
videoProfile: string;
|
||||
videoFrameRate: string;
|
||||
aspectRatio: number;
|
||||
optimizedForStreaming: boolean;
|
||||
title: string;
|
||||
parts: Part[];
|
||||
dynamicRange: string; // 'Dolby Vision' | 'HDR10' | 'HLG' | ''
|
||||
atmos: boolean;
|
||||
}
|
||||
|
||||
export interface Marker {
|
||||
id: string;
|
||||
type: 'intro' | 'credits' | 'commercial' | string;
|
||||
start: number;
|
||||
end: number;
|
||||
final: boolean;
|
||||
}
|
||||
|
||||
export interface Chapter {
|
||||
index: number;
|
||||
title: string;
|
||||
start: number;
|
||||
end: number;
|
||||
thumb: string;
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
id: string;
|
||||
tag: string;
|
||||
filter: string;
|
||||
}
|
||||
|
||||
export interface Role extends Tag {
|
||||
role: string;
|
||||
thumb: string;
|
||||
}
|
||||
|
||||
export interface AudienceScore {
|
||||
source: 'Rotten Tomatoes' | 'IMDb' | 'TMDB' | 'TVDB';
|
||||
value: number; // 0–10
|
||||
kind: 'audience' | 'critic';
|
||||
image: string;
|
||||
}
|
||||
|
||||
export interface Item {
|
||||
id: string;
|
||||
key: string;
|
||||
guid: string;
|
||||
guids: string[];
|
||||
type: ItemType;
|
||||
subtype: string;
|
||||
title: string;
|
||||
titleSort: string;
|
||||
originalTitle: string;
|
||||
summary: string;
|
||||
tagline: string;
|
||||
year: number;
|
||||
originallyAvailableAt: string;
|
||||
duration: number;
|
||||
viewOffset: number;
|
||||
viewCount: number;
|
||||
lastViewedAt: number;
|
||||
addedAt: number;
|
||||
updatedAt: number;
|
||||
thumb: string;
|
||||
art: string;
|
||||
logo: string;
|
||||
theme: string;
|
||||
contentRating: string;
|
||||
studio: string;
|
||||
parentId: string;
|
||||
parentKey: string;
|
||||
parentTitle: string;
|
||||
parentIndex: number;
|
||||
parentThumb: string;
|
||||
grandparentId: string;
|
||||
grandparentKey: string;
|
||||
grandparentTitle: string;
|
||||
grandparentThumb: string;
|
||||
grandparentArt: string;
|
||||
index: number;
|
||||
leafCount: number;
|
||||
viewedLeafCount: number;
|
||||
childCount: number;
|
||||
genres: Tag[];
|
||||
directors: Tag[];
|
||||
writers: Tag[];
|
||||
producers: Tag[];
|
||||
countries: Tag[];
|
||||
labels: Tag[];
|
||||
collections: Tag[];
|
||||
roles: Role[];
|
||||
scores: AudienceScore[];
|
||||
userRating: number;
|
||||
media: Media[];
|
||||
markers: Marker[];
|
||||
chapters: Chapter[];
|
||||
extras: Item[];
|
||||
librarySectionId: string;
|
||||
librarySectionTitle: string;
|
||||
librarySectionKey: string;
|
||||
/** For collections: number of members. For people (search hubs): unused. */
|
||||
smart: boolean;
|
||||
editionTitle: string;
|
||||
skipChildren: boolean;
|
||||
/** Plex UltraBlur corner colors (hex without #), for artwork-led washes. */
|
||||
ultraBlur: { topLeft: string; topRight: string; bottomRight: string; bottomLeft: string } | null;
|
||||
raw: any;
|
||||
}
|
||||
|
||||
export interface Hub {
|
||||
id: string;
|
||||
key: string;
|
||||
title: string;
|
||||
type: string;
|
||||
context: string;
|
||||
size: number;
|
||||
more: boolean;
|
||||
style: string;
|
||||
items: Item[];
|
||||
}
|
||||
|
||||
export interface Section {
|
||||
id: string;
|
||||
key: string;
|
||||
title: string;
|
||||
type: 'movie' | 'show' | 'artist' | 'photo' | string;
|
||||
agent: string;
|
||||
scanner: string;
|
||||
language: string;
|
||||
thumb: string;
|
||||
art: string;
|
||||
locations: { id: string; path: string }[];
|
||||
scannedAt: number;
|
||||
updatedAt: number;
|
||||
contentChangedAt: number;
|
||||
refreshing: boolean;
|
||||
hidden: boolean;
|
||||
}
|
||||
|
||||
export interface Page<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface PlexUser {
|
||||
id: number;
|
||||
uuid: string;
|
||||
username: string;
|
||||
title: string;
|
||||
email: string;
|
||||
thumb: string;
|
||||
home: boolean;
|
||||
homeAdmin: boolean;
|
||||
protected: boolean;
|
||||
subscription: boolean;
|
||||
}
|
||||
|
||||
export interface HomeUser {
|
||||
id: number;
|
||||
uuid: string;
|
||||
title: string;
|
||||
username: string;
|
||||
thumb: string;
|
||||
admin: boolean;
|
||||
protected: boolean;
|
||||
restricted: boolean;
|
||||
guest: boolean;
|
||||
}
|
||||
|
||||
export interface ServerConnection {
|
||||
uri: string;
|
||||
local: boolean;
|
||||
relay: boolean;
|
||||
protocol: string;
|
||||
address: string;
|
||||
port: number;
|
||||
IPv6: boolean;
|
||||
}
|
||||
|
||||
export interface ServerResource {
|
||||
id: string; // clientIdentifier / machineIdentifier
|
||||
name: string;
|
||||
owned: boolean;
|
||||
accessToken: string;
|
||||
productVersion: string;
|
||||
platform: string;
|
||||
presence: boolean;
|
||||
publicAddress: string;
|
||||
connections: ServerConnection[];
|
||||
sourceTitle: string;
|
||||
httpsRequired: boolean;
|
||||
}
|
||||
|
||||
export interface FilterOption {
|
||||
key: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface LibraryQuery {
|
||||
sectionId: string;
|
||||
type?: number; // 1 movie, 2 show, 3 season, 4 episode
|
||||
sort: string; // e.g. titleSort:asc
|
||||
filters: Record<string, string>; // e.g. genre=12, unwatched=1
|
||||
title?: string;
|
||||
}
|
||||
222
src/screens/Downloads.tsx
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useDownloads, type Download } from '../downloads/store';
|
||||
import { useSession } from '../app/session';
|
||||
import { navigate } from '../app/router';
|
||||
import { duration, episodeLabel, fileSize } from '../app/format';
|
||||
import { usePlayer } from '../player/store';
|
||||
import { invoke, isNative, localFileUrl, revealPath } from '../platform/native';
|
||||
import { Button, EmptyState, IconButton } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { confirmDialog, openMenu } from '../ui/overlays';
|
||||
|
||||
function useLocalArt(d: Download, key: string) {
|
||||
const [url, setUrl] = useState('');
|
||||
const path = d.meta.localAssets?.[key];
|
||||
useEffect(() => {
|
||||
if (path) localFileUrl(path).then(setUrl);
|
||||
}, [path]);
|
||||
return url;
|
||||
}
|
||||
|
||||
function DownloadRow({ d }: { d: Download }) {
|
||||
const store = useDownloads();
|
||||
const server = useSession((s) => s.server);
|
||||
const item = store.itemOf(d);
|
||||
const still = useLocalArt(d, item.type === 'episode' ? 'still' : 'art');
|
||||
const poster = useLocalArt(d, 'poster');
|
||||
const pct = d.total ? Math.min(100, (d.received / d.total) * 100) : 0;
|
||||
const isEp = item.type === 'episode';
|
||||
const onServer = server?.machineId === d.meta.serverId;
|
||||
const play = () => usePlayer.getState().play(item, { localFile: d.filePath, resume: true });
|
||||
const remove = async () => {
|
||||
if (await confirmDialog({ title: 'Remove download?', message: `“${item.title}” will be deleted from this computer. It stays available on your Plex server.`, confirm: 'Remove', danger: true })) store.remove(d.id);
|
||||
};
|
||||
const status =
|
||||
d.status === 'completed'
|
||||
? fileSize(d.total || d.received)
|
||||
: d.status === 'downloading'
|
||||
? `${fileSize(d.received)} of ${fileSize(d.total)}${d.speed ? ` · ${fileSize(d.speed)}/s` : ''}`
|
||||
: d.status === 'queued'
|
||||
? 'Waiting…'
|
||||
: d.status === 'paused'
|
||||
? `Paused · ${fileSize(d.received)} of ${fileSize(d.total)}`
|
||||
: (d.error ?? 'Failed');
|
||||
return (
|
||||
<div className={`download-row ${d.status}`}>
|
||||
<button className="dl-thumb" onClick={d.status === 'completed' ? play : undefined} aria-label={`Play ${item.title}`}>
|
||||
{(still || poster) && <img src={still || poster} alt="" draggable={false} className={still ? '' : 'poster'} />}
|
||||
{d.status === 'completed' && (
|
||||
<span className="dl-play">
|
||||
<Icon name="play" size={18} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<div className="dl-details">
|
||||
<h3>{isEp ? item.grandparentTitle : item.title}</h3>
|
||||
<p>
|
||||
{isEp ? `${episodeLabel(item)} · ${item.title}` : [item.year, duration(item.duration)].filter(Boolean).join(' · ')}
|
||||
{d.meta.serverName && <span className="dim"> · {d.meta.serverName}</span>}
|
||||
</p>
|
||||
{d.status !== 'completed' ? (
|
||||
<div className="dl-progress">
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
<span className="dl-status">{status}</span>
|
||||
</div>
|
||||
) : (
|
||||
<span className="file-status">
|
||||
<Icon name="check" size={14} /> Ready offline · {status}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="dl-actions">
|
||||
{d.status === 'completed' && (
|
||||
<Button variant="ghost" size="sm" icon="play" onClick={play}>
|
||||
Play
|
||||
</Button>
|
||||
)}
|
||||
{d.status === 'downloading' || d.status === 'queued' ? (
|
||||
<IconButton icon="pause" label="Pause" onClick={() => store.pause(d.id)} />
|
||||
) : d.status === 'paused' || d.status === 'failed' ? (
|
||||
<IconButton icon="refresh" label="Resume" onClick={() => store.resume(d.id)} />
|
||||
) : null}
|
||||
<IconButton
|
||||
icon="dots"
|
||||
label="More"
|
||||
onClick={(e) =>
|
||||
openMenu(
|
||||
[
|
||||
...(onServer ? [{ label: 'Details', icon: 'info', onSelect: () => navigate({ name: 'item', id: item.id }) }] : []),
|
||||
...(d.status === 'completed' ? [{ label: 'Show in folder', icon: 'folder', onSelect: () => revealPath(d.filePath) }] : []),
|
||||
{ divider: true },
|
||||
{ label: 'Remove download', icon: 'trash', danger: true, onSelect: remove },
|
||||
],
|
||||
e.currentTarget,
|
||||
{ align: 'end' },
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Downloads({ offline }: { offline?: boolean }) {
|
||||
const store = useDownloads();
|
||||
const [space, setSpace] = useState<{ free: number; total: number } | null>(null);
|
||||
useEffect(() => {
|
||||
store.init();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (isNative && store.dir) invoke<{ free: number; total: number }>('disk_space', { path: store.dir }).then(setSpace).catch(() => {});
|
||||
}, [store.dir, store.items.length]);
|
||||
|
||||
const active = store.items.filter((d) => d.status !== 'completed');
|
||||
const done = store.items.filter((d) => d.status === 'completed');
|
||||
const used = store.items.reduce((a, d) => a + (d.status === 'completed' ? d.total || d.received : d.received), 0);
|
||||
const movies = done.filter((d) => d.meta.raw?.type !== 'episode');
|
||||
const episodes = done.filter((d) => d.meta.raw?.type === 'episode');
|
||||
const shows = new Map<string, Download[]>();
|
||||
for (const e of episodes) {
|
||||
const k = e.meta.raw?.grandparentTitle ?? 'Episodes';
|
||||
shows.set(k, [...(shows.get(k) ?? []), e]);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`downloads-page page-pad${offline ? '' : ' top'}`}>
|
||||
<div className="download-intro">
|
||||
<div>
|
||||
<div className="micro">Offline · This computer</div>
|
||||
<h1 className="page-title">Downloads</h1>
|
||||
<p className="page-subtitle">Movies and episodes saved to this computer play without a connection. Progress syncs to Plex when you’re back online.</p>
|
||||
</div>
|
||||
{isNative && (
|
||||
<div className="storage-card">
|
||||
<div className="storage-head">
|
||||
<b>Storage</b>
|
||||
<span>{space ? `${fileSize(space.free)} free` : ''}</span>
|
||||
</div>
|
||||
<div className="storage-bar">
|
||||
{space && (
|
||||
<>
|
||||
<span className="other" style={{ width: `${Math.max(0, ((space.total - space.free - used) / space.total) * 100)}%` }} />
|
||||
<span className="mine" style={{ width: `${(used / space.total) * 100}%` }} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="storage-caption">
|
||||
{fileSize(used) || '0 MB'} used by Kaleido
|
||||
{store.dir && (
|
||||
<button className="inline-link" onClick={() => revealPath(store.dir)} title={store.dir}>
|
||||
Open folder
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isNative && (
|
||||
<EmptyState icon="download" title="Downloads need the desktop app">
|
||||
Install Kaleido for Windows to save movies and episodes for offline viewing.
|
||||
</EmptyState>
|
||||
)}
|
||||
{isNative && !store.items.length && (
|
||||
<EmptyState icon="download" title="Nothing downloaded yet" action={!offline && <Button variant="ghost" icon="film" onClick={() => navigate({ name: 'section', kind: 'movie', tab: 'library' })}>Browse movies</Button>}>
|
||||
Choose Download on a movie or episode, or download a whole season from its page.
|
||||
</EmptyState>
|
||||
)}
|
||||
|
||||
{active.length > 0 && (
|
||||
<section className="dl-section">
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
In progress <small>{active.length}</small>
|
||||
</h2>
|
||||
<div className="actions">
|
||||
{active.some((d) => d.status === 'downloading' || d.status === 'queued') ? (
|
||||
<Button variant="text" onClick={() => active.forEach((d) => (d.status === 'downloading' || d.status === 'queued') && store.pause(d.id))}>
|
||||
Pause all
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="text" onClick={() => active.forEach((d) => store.resume(d.id))}>
|
||||
Resume all
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{active.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{movies.length > 0 && (
|
||||
<section className="dl-section">
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
Movies <small>{movies.length}</small>
|
||||
</h2>
|
||||
</div>
|
||||
{movies.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{[...shows.entries()].map(([show, list]) => (
|
||||
<section className="dl-section" key={show}>
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
{show} <small>{list.length} episode{list.length === 1 ? '' : 's'}</small>
|
||||
</h2>
|
||||
</div>
|
||||
{list
|
||||
.sort((a, b) => (a.meta.raw.parentIndex - b.meta.raw.parentIndex) * 1000 + (a.meta.raw.index - b.meta.raw.index))
|
||||
.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
53
src/screens/Home.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import * as api from '../plex/api';
|
||||
import { useSections, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { navigate } from '../app/router';
|
||||
import { Hero } from '../ui/Hero';
|
||||
import { HubShelf } from '../ui/media';
|
||||
import { ErrorState, PageLoader } from '../ui/primitives';
|
||||
import { buildFeatures, HIDDEN_HUBS } from './discover';
|
||||
|
||||
export function Home() {
|
||||
const server = useServer();
|
||||
const sections = useSections();
|
||||
const video = (sections.data ?? []).filter((s) => (s.type === 'movie' || s.type === 'show') && !s.hidden);
|
||||
|
||||
const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s));
|
||||
const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), { staleTime: 15_000 });
|
||||
// Section hubs feed the hero and the release shelves; shared with Discover.
|
||||
const sectionHubs = useQuery({
|
||||
queryKey: [server.machineId, 'sectionHubsAll', video.map((s) => s.id).join(',')],
|
||||
queryFn: async () => (await Promise.all(video.map((s) => api.sectionHubs(server, s.id).catch(() => [])))).flat(),
|
||||
enabled: video.length > 0,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const features = useMemo(() => buildFeatures(sectionHubs.data ?? [], 8), [sectionHubs.data]);
|
||||
const extra = (sectionHubs.data ?? []).filter((h) => /recentlyreleased|recentlyaired|topunwatched|toprated/.test(h.id));
|
||||
|
||||
if (home.isError && !home.data) return <ErrorState error={home.error} onRetry={() => home.refetch()} />;
|
||||
if (!home.data || sections.isLoading) return <PageLoader />;
|
||||
|
||||
const hubs = home.data.filter((h) => !HIDDEN_HUBS.test(h.id));
|
||||
const cw = continueWatching.data ?? [];
|
||||
const homeIds = new Set(hubs.map((h) => h.title));
|
||||
|
||||
return (
|
||||
<div className="home">
|
||||
<Hero features={features} variant="home" />
|
||||
<div className="shelves over-hero">
|
||||
<HubShelf title="Continue Watching" items={cw} continueWatching />
|
||||
{hubs.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} onViewAll={h.more ? () => navigate({ name: 'hub', key: h.key, title: h.title }) : undefined} />
|
||||
))}
|
||||
{extra
|
||||
.filter((h) => !homeIds.has(h.title))
|
||||
.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} onViewAll={() => navigate({ name: 'hub', key: h.key, title: h.title })} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
src/screens/HubScreen.tsx
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useServer } from '../app/session';
|
||||
import { LandscapeCard, PosterCard } from '../ui/media';
|
||||
import { EmptyState, ErrorState, PageLoader, Spinner } from '../ui/primitives';
|
||||
|
||||
/** "View all" for a hub, paged as it scrolls. */
|
||||
export default function HubScreen({ hubKey, title }: { hubKey: string; title: string }) {
|
||||
const server = useServer();
|
||||
const q = useInfiniteQuery({
|
||||
queryKey: [server.machineId, 'hubAll', hubKey],
|
||||
queryFn: ({ pageParam }) => api.hubItems(server, hubKey, pageParam, 72),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (last, pages) => {
|
||||
const loaded = pages.reduce((a, p) => a + p.items.length, 0);
|
||||
return last.items.length && loaded < last.total ? loaded : undefined;
|
||||
},
|
||||
});
|
||||
const sentinel = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const el = sentinel.current;
|
||||
if (!el) return;
|
||||
const io = new IntersectionObserver(([e]) => e.isIntersecting && q.hasNextPage && !q.isFetchingNextPage && q.fetchNextPage(), { rootMargin: '800px' });
|
||||
io.observe(el);
|
||||
return () => io.disconnect();
|
||||
}, [q.hasNextPage, q.isFetchingNextPage]);
|
||||
|
||||
const items = q.data?.pages.flatMap((p) => p.items) ?? [];
|
||||
const wide = items.length > 0 && items.every((i) => i.type === 'episode');
|
||||
return (
|
||||
<div className="page-pad top hub-page">
|
||||
<h1 className="page-title">{title}</h1>
|
||||
{q.isError && <ErrorState error={q.error} onRetry={() => q.refetch()} />}
|
||||
{q.isLoading && <PageLoader />}
|
||||
{q.data && !items.length && <EmptyState title="Nothing here yet" />}
|
||||
<div className={`poster-grid auto${wide ? ' wide' : ''}`}>{items.map((i) => (wide ? <LandscapeCard key={i.id} item={i} /> : <PosterCard key={i.id} item={i} />))}</div>
|
||||
<div ref={sentinel} className="grid-sentinel">
|
||||
{q.isFetchingNextPage && <Spinner />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
616
src/screens/Item.tsx
Normal file
|
|
@ -0,0 +1,616 @@
|
|||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item } from '../plex/types';
|
||||
import { invalidateLibrary, useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { goBack, navigate, useRouter } from '../app/router';
|
||||
import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
|
||||
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format';
|
||||
import { Backdrop } from '../ui/Backdrop';
|
||||
import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
|
||||
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { openMenu, toastError } from '../ui/overlays';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { playThemeMusic, stopThemeMusic } from '../player/theme';
|
||||
|
||||
export function ItemScreen({ id }: { id: string }) {
|
||||
const q = useItem(id);
|
||||
const item = q.data;
|
||||
useEffect(() => {
|
||||
if (item?.theme && item.type !== 'collection') playThemeMusic(item.theme);
|
||||
}, [item?.theme]);
|
||||
useEffect(() => () => stopThemeMusic(), []);
|
||||
if (q.isError) return <div className="page-pad top"><ErrorState error={q.error} onRetry={() => q.refetch()} /></div>;
|
||||
if (!item) return <PageLoader />;
|
||||
switch (item.type) {
|
||||
case 'show':
|
||||
return <ShowDetail item={item} />;
|
||||
case 'season':
|
||||
return <SeasonDetail item={item} />;
|
||||
case 'episode':
|
||||
return <EpisodeDetail item={item} />;
|
||||
case 'collection':
|
||||
return <CollectionDetail item={item} />;
|
||||
default:
|
||||
return <MovieDetail item={item} />;
|
||||
}
|
||||
}
|
||||
|
||||
// —— Shared pieces ————————————————————————————————————————————————
|
||||
|
||||
function Synopsis({ item, text }: { item: Item; text: string }) {
|
||||
const [clamped, setClamped] = useState(false);
|
||||
if (!text) return null;
|
||||
return (
|
||||
<div className="synopsis-wrap">
|
||||
<p
|
||||
className="synopsis"
|
||||
ref={(el) => {
|
||||
if (el) setClamped(el.scrollHeight > el.clientHeight + 2);
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</p>
|
||||
{clamped && (
|
||||
<button className="btn text synopsis-more" onClick={() => openDialog({ kind: 'synopsis', item })}>
|
||||
More
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WatchedButton({ item }: { item: Item }) {
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const watched = isWatched(item, percent);
|
||||
return (
|
||||
<Button variant="ghost" icon={watched ? 'check' : 'plus'} onClick={() => setWatched(item, !watched)} className={watched ? 'is-on' : ''}>
|
||||
{watched ? 'Watched' : 'Mark watched'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadButton({ item }: { item: Item }) {
|
||||
const downloads = useDownloads();
|
||||
const isSeries = item.type === 'show' || item.type === 'season';
|
||||
const dl = downloads.items.find((d) => d.id === downloads.idFor(item.id));
|
||||
if (isSeries) return <IconButton round icon="download" label={item.type === 'show' ? 'Download unwatched episodes' : 'Download season'} onClick={() => downloads.startAll(item)} />;
|
||||
if (dl?.status === 'completed') return <IconButton round icon="downloaded" label="Downloaded" className="on" onClick={() => navigate({ name: 'downloads' })} />;
|
||||
if (dl) {
|
||||
const pct = dl.total ? Math.round((dl.received / dl.total) * 100) : 0;
|
||||
return (
|
||||
<button className="circle-btn download-progress" aria-label={`Downloading ${pct}%`} title={`Downloading ${pct}%`} onClick={() => navigate({ name: 'downloads' })}>
|
||||
<svg viewBox="0 0 36 36" width="42" height="42">
|
||||
<circle cx="18" cy="18" r="15" fill="none" stroke="rgba(255,255,255,.2)" strokeWidth="2.4" />
|
||||
<circle cx="18" cy="18" r="15" fill="none" stroke="currentColor" strokeWidth="2.4" strokeDasharray={`${pct * 0.94} 100`} transform="rotate(-90 18 18)" strokeLinecap="round" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return <IconButton round icon="download" label="Download" onClick={() => downloads.start(item)} />;
|
||||
}
|
||||
|
||||
function MoreButton({ item, onDeleted }: { item: Item; onDeleted?: () => void }) {
|
||||
return <IconButton round icon="dots" label="More actions" onClick={(e) => openMenu(itemMenu(item, { detail: true, onDeleted }), e.currentTarget)} />;
|
||||
}
|
||||
|
||||
function TrailerButton({ item }: { item: Item }) {
|
||||
const trailer = item.extras.find((e) => e.subtype === 'trailer' && e.media.length);
|
||||
if (!trailer) return null;
|
||||
return (
|
||||
<Button variant="ghost" icon="film" onClick={() => playItem(trailer, { resume: false })}>
|
||||
Trailer
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailHero({ item, backdropItem, children, title, below }: { item: Item; backdropItem?: Item; children: ReactNode; title?: ReactNode; below?: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<Backdrop item={backdropItem ?? item} className="detail-backdrop" />
|
||||
<header className="detail-hero">
|
||||
<div className="detail-head">
|
||||
{title ?? <TitleArt item={item} maxWidth={440} maxHeight={140} />}
|
||||
{children}
|
||||
</div>
|
||||
{below}
|
||||
</header>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CastRow({ item, title = 'Cast & Crew' }: { item: Item; title?: string }) {
|
||||
const people = [
|
||||
...item.roles.map((r) => ({ id: r.id, name: r.tag, role: r.role, thumb: r.thumb })),
|
||||
...item.directors.map((d) => ({ id: d.id, name: d.tag, role: 'Director', thumb: (d as any).thumb ?? item.raw?.Director?.find((x: any) => x.tag === d.tag)?.thumb })),
|
||||
...item.writers.slice(0, 3).map((d) => ({ id: d.id, name: d.tag, role: 'Writer', thumb: item.raw?.Writer?.find((x: any) => x.tag === d.tag)?.thumb })),
|
||||
];
|
||||
if (!people.length) return null;
|
||||
return (
|
||||
<Shelf title={title} kind="people">
|
||||
{people.map((p, i) => (
|
||||
<PersonCard key={`${p.id}-${i}`} name={p.name} role={p.role} thumb={p.thumb} onClick={p.id ? () => navigate({ name: 'person', id: p.id, title: p.name, thumb: p.thumb }) : undefined} />
|
||||
))}
|
||||
</Shelf>
|
||||
);
|
||||
}
|
||||
|
||||
function ExtrasRow({ item }: { item: Item }) {
|
||||
const extras = item.extras.filter((e) => e.media.length);
|
||||
if (!extras.length) return null;
|
||||
return (
|
||||
<Shelf title="Trailers & Extras" kind="landscape">
|
||||
{extras.map((e) => (
|
||||
<article key={e.id} className="card landscape extra" role="button" tabIndex={0} onClick={() => playItem(e, { resume: false })} onKeyDown={(ev) => ev.key === 'Enter' && playItem(e, { resume: false })}>
|
||||
<ExtraCover item={e} />
|
||||
<div className="card-caption">
|
||||
<div className="card-title">{e.title}</div>
|
||||
<div className="card-meta">{[extraLabel(e), duration(e.duration)].filter(Boolean).join(' · ')}</div>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</Shelf>
|
||||
);
|
||||
}
|
||||
|
||||
function ExtraCover({ item }: { item: Item }) {
|
||||
const server = useServer();
|
||||
return (
|
||||
<div className="card-cover">
|
||||
<Artwork src={server.image(item.thumb, 400, 225)} />
|
||||
<div className="card-hover" />
|
||||
<span className="extra-play">
|
||||
<Icon name="play" size={18} />
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RelatedRows({ item }: { item: Item }) {
|
||||
const related = useRelated(item.id);
|
||||
const hubs = (related.data ?? []).map((h) => ({ ...h, items: h.items.filter((i) => i.id !== item.id && ['movie', 'show'].includes(i.type)) })).filter((h) => h.items.length);
|
||||
return (
|
||||
<>
|
||||
{hubs.slice(0, 3).map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} landscape={false} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function StarRating({ item }: { item: Item }) {
|
||||
const server = useServer();
|
||||
const [value, setValue] = useState(item.userRating);
|
||||
const [hover, setHover] = useState(0);
|
||||
useEffect(() => setValue(item.userRating), [item.userRating]);
|
||||
const set = async (stars: number) => {
|
||||
const rating = stars * 2 === value ? -1 : stars * 2;
|
||||
setValue(Math.max(0, rating));
|
||||
try {
|
||||
await api.rate(server, item.id, rating);
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
};
|
||||
const shown = hover || value / 2;
|
||||
return (
|
||||
<span className="star-rating" onMouseLeave={() => setHover(0)} aria-label="Your rating">
|
||||
{[1, 2, 3, 4, 5].map((n) => (
|
||||
<button key={n} onMouseEnter={() => setHover(n)} onClick={() => set(n)} aria-label={`${n} star${n > 1 ? 's' : ''}`}>
|
||||
<Icon name={n <= shown ? 'starFill' : 'star'} size={15} />
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function AboutPanel({ item }: { item: Item }) {
|
||||
const m = item.media[0];
|
||||
const rows: [string, ReactNode][] = [];
|
||||
const tags = (list: { tag: string; id: string }[], filter: string, limit = 3) =>
|
||||
list.slice(0, limit).map((t, i) => (
|
||||
<span key={t.tag}>
|
||||
{i > 0 && ', '}
|
||||
{filter === 'person' ? (
|
||||
<button className="inline-link" onClick={() => t.id && navigate({ name: 'person', id: t.id, title: t.tag })}>
|
||||
{t.tag}
|
||||
</button>
|
||||
) : (
|
||||
t.tag
|
||||
)}
|
||||
</span>
|
||||
));
|
||||
if (item.directors.length) rows.push([item.directors.length > 1 ? 'Directors' : 'Director', tags(item.directors, 'person')]);
|
||||
if (item.writers.length) rows.push(['Writers', tags(item.writers, 'person')]);
|
||||
if (item.studio) rows.push([item.type === 'show' || item.type === 'episode' ? 'Network' : 'Studio', item.studio]);
|
||||
if (item.originallyAvailableAt) rows.push([item.type === 'show' ? 'Premiered' : 'Released', date(item.originallyAvailableAt)]);
|
||||
if (item.genres.length) rows.push(['Genres', item.genres.map((g) => g.tag).join(', ')]);
|
||||
if (item.countries.length) rows.push(['Country', item.countries.map((c) => c.tag).join(', ')]);
|
||||
if (item.contentRating) rows.push(['Rated', item.contentRating]);
|
||||
if (item.duration && item.type !== 'show') rows.push(['Runtime', duration(item.duration)]);
|
||||
for (const s of item.scores) rows.push([`${s.source}${s.kind === 'critic' ? ' critics' : ''}`, s.source === 'Rotten Tomatoes' ? `${Math.round(s.value * 10)}%` : `${s.value.toFixed(1)} / 10`]);
|
||||
if (item.collections.length) rows.push(['Collections', item.collections.map((c) => c.tag).join(', ')]);
|
||||
if (item.labels.length) rows.push(['Labels', item.labels.map((c) => c.tag).join(', ')]);
|
||||
if (item.editionTitle) rows.push(['Edition', item.editionTitle]);
|
||||
if (m) {
|
||||
rows.push(['Video', [resolutionLabel(m), m.dynamicRange, m.videoCodec.toUpperCase(), m.videoFrameRate].filter(Boolean).join(' · ')]);
|
||||
rows.push(['Audio', [m.audioCodec.toUpperCase(), channelLabel(m.audioChannels), m.atmos ? 'Atmos' : ''].filter(Boolean).join(' · ')]);
|
||||
if (m.bitrate) rows.push(['Bitrate', bitrate(m.bitrate)]);
|
||||
const size = m.parts.reduce((a, p) => a + p.size, 0);
|
||||
if (size) rows.push(['File size', fileSize(size)]);
|
||||
if (item.media.length > 1) rows.push(['Versions', `${item.media.length} available`]);
|
||||
}
|
||||
if (item.addedAt) rows.push(['Added', date(item.addedAt)]);
|
||||
return (
|
||||
<aside className="about-panel">
|
||||
<div className="about-head">
|
||||
<h3>About</h3>
|
||||
{['movie', 'show', 'episode', 'season'].includes(item.type) && <StarRating item={item} />}
|
||||
</div>
|
||||
{item.tagline && <p className="about-tagline">“{item.tagline}”</p>}
|
||||
{rows.map(([k, v]) => (
|
||||
<div className="about-line" key={k}>
|
||||
<span>{k}</span>
|
||||
<strong>{v}</strong>
|
||||
</div>
|
||||
))}
|
||||
{(m || canManage()) && (
|
||||
<div className="about-actions">
|
||||
{m && (
|
||||
<Button variant="outline" size="sm" icon="info" onClick={() => openDialog({ kind: 'info', item })}>
|
||||
Media info
|
||||
</Button>
|
||||
)}
|
||||
{canManage() && (
|
||||
<Button variant="outline" size="sm" icon="edit" onClick={() => openDialog({ kind: 'edit', item })}>
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Movie ——————————————————————————————————————————————————————————
|
||||
|
||||
function MovieDetail({ item }: { item: Item }) {
|
||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
||||
return (
|
||||
<div className="detail movie">
|
||||
<DetailHero item={item}>
|
||||
<Facts item={item} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
{resume ? `Resume · ${remaining(item)}` : 'Play'}
|
||||
</Button>
|
||||
{resume && (
|
||||
<Button variant="ghost" icon="replay10" onClick={() => playWithVersion(item, { offsetMs: 0, resume: false })}>
|
||||
From beginning
|
||||
</Button>
|
||||
)}
|
||||
<TrailerButton item={item} />
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
{resume && (
|
||||
<div className="detail-progress">
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${(item.viewOffset / item.duration) * 100}%` }} />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="detail-tech">{technicalLine(item.media[0])}</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
<CastRow item={item} />
|
||||
<ExtrasRow item={item} />
|
||||
<RelatedRows item={item} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Shows and seasons ————————————————————————————————————————————
|
||||
|
||||
function EpisodeRow({ ep }: { ep: Item }) {
|
||||
const server = useServer();
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const watched = isWatched(ep, percent);
|
||||
const p = ep.viewOffset && ep.duration ? ep.viewOffset / ep.duration : 0;
|
||||
return (
|
||||
<div
|
||||
className="episode-row"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => openItem(ep)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && openItem(ep)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
openMenu(itemMenu(ep), { x: e.clientX, y: e.clientY });
|
||||
}}
|
||||
>
|
||||
<div className="episode-index">{ep.index || '–'}</div>
|
||||
<div className="episode-pic">
|
||||
<Artwork src={server.image(ep.thumb, 320, 180)} />
|
||||
<button
|
||||
className="episode-play"
|
||||
aria-label={`Play ${ep.title}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
playWithVersion(ep);
|
||||
}}
|
||||
>
|
||||
<Icon name="play" size={18} />
|
||||
</button>
|
||||
{p > 0 && !watched && (
|
||||
<span className="progress-line">
|
||||
<i style={{ width: `${p * 100}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="episode-text">
|
||||
<h3>
|
||||
{ep.title}
|
||||
{watched && <Icon name="check" size={15} className="episode-watched" />}
|
||||
</h3>
|
||||
<div className="episode-meta">
|
||||
{[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
{ep.summary && <p>{ep.summary}</p>}
|
||||
</div>
|
||||
<button
|
||||
className="icon-btn episode-more"
|
||||
aria-label="More"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
openMenu(itemMenu(ep), e.currentTarget);
|
||||
}}
|
||||
>
|
||||
<Icon name="dots" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) {
|
||||
const saved = useRouter((s) => s.current.state.season as string | undefined);
|
||||
const [seasonId, setSeasonId] = useState(saved ?? initialSeason ?? seasons[0]?.id);
|
||||
useEffect(() => {
|
||||
if (!seasonId && seasons[0]) setSeasonId(initialSeason ?? seasons[0].id);
|
||||
}, [seasons, initialSeason]);
|
||||
const episodes = useChildren(seasonId);
|
||||
const season = seasons.find((s) => s.id === seasonId);
|
||||
if (!seasons.length) return null;
|
||||
return (
|
||||
<section className="episodes">
|
||||
<div className="episodes-head">
|
||||
<h2>Episodes</h2>
|
||||
{showPicker && seasons.length > 1 && (
|
||||
<Select
|
||||
value={seasonId!}
|
||||
label="Season"
|
||||
options={seasons.map((s) => ({ value: s.id, label: s.title, hint: s.leafCount ? `${s.leafCount} ep` : undefined }))}
|
||||
onChange={(v) => {
|
||||
setSeasonId(v);
|
||||
useRouter.getState().setState({ season: v });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{season && (
|
||||
<span className="episodes-sub">
|
||||
{season.leafCount} episodes{season.year ? ` · ${season.year}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{season?.summary && <p className="season-summary">{season.summary}</p>}
|
||||
<div className="episode-list">
|
||||
{episodes.isLoading && <PageLoader />}
|
||||
{episodes.data?.map((ep) => <EpisodeRow key={ep.id} ep={ep} />)}
|
||||
{episodes.data && !episodes.data.length && <EmptyState icon="tv" title="No episodes" />}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ShowDetail({ item }: { item: Item }) {
|
||||
const seasons = useChildren(item.id);
|
||||
const server = useServer();
|
||||
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), { staleTime: 15_000 });
|
||||
const nextEp = next.data;
|
||||
const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season');
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const playLabel = nextEp ? (nextEp.viewOffset ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
|
||||
void server;
|
||||
return (
|
||||
<div className="detail show">
|
||||
<DetailHero item={item}>
|
||||
<Facts item={item} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => (nextEp ? playWithVersion(nextEp) : playItem(item))}>
|
||||
{playLabel}
|
||||
</Button>
|
||||
<Button variant="ghost" icon="shuffle" onClick={() => shuffleItem(item)}>
|
||||
Shuffle
|
||||
</Button>
|
||||
<TrailerButton item={item} />
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
{nextEp && (
|
||||
<div className="detail-tech">
|
||||
Up next: {episodeLabel(nextEp)} · {nextEp.title}
|
||||
</div>
|
||||
)}
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
{seasonList.length > 1 && (
|
||||
<Shelf title="Seasons">
|
||||
{seasonList.map((s) => (
|
||||
<PosterCard key={s.id} item={s} caption="episodes" />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{seasons.isLoading ? <PageLoader /> : <Episodes seasons={seasonList} initialSeason={nextEp?.parentId} />}
|
||||
<CastRow item={item} />
|
||||
<ExtrasRow item={item} />
|
||||
<RelatedRows item={item} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeasonDetail({ item }: { item: Item }) {
|
||||
const show = useItem(item.parentId);
|
||||
const siblings = useChildren(item.parentId);
|
||||
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
|
||||
const episodes = useChildren(item.id);
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const next = (episodes.data ?? []).find((e) => !isWatched(e, percent)) ?? episodes.data?.[0];
|
||||
const showItem = show.data;
|
||||
return (
|
||||
<div className="detail season">
|
||||
<DetailHero
|
||||
item={item}
|
||||
backdropItem={showItem ?? item}
|
||||
title={
|
||||
<>
|
||||
{showItem ? (
|
||||
<button className="title-link" onClick={() => navigate({ name: 'item', id: showItem.id })}>
|
||||
<TitleArt item={showItem} maxWidth={340} maxHeight={96} as="h2" />
|
||||
</button>
|
||||
) : (
|
||||
<h2 className="title-text small">{item.parentTitle}</h2>
|
||||
)}
|
||||
<h1 className="detail-subtitle">{item.title}</h1>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Facts item={{ ...item, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
|
||||
<Synopsis item={item} text={item.summary || showItem?.summary || ''} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next)}>
|
||||
{next ? (next.viewOffset ? `Resume ${episodeLabel(next)}` : `Play ${episodeLabel(next)}`) : 'Play'}
|
||||
</Button>
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body single">
|
||||
<div className="detail-main">
|
||||
<Episodes seasons={seasonList.length ? seasonList : [item]} initialSeason={item.id} />
|
||||
{showItem && <CastRow item={showItem} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EpisodeDetail({ item }: { item: Item }) {
|
||||
const show = useItem(item.grandparentId);
|
||||
const siblings = useChildren(item.parentId);
|
||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
||||
const showItem = show.data;
|
||||
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
|
||||
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
|
||||
const ordered = useMemo(() => [...others.slice(startIndex), ...others.slice(0, startIndex)], [siblings.data, item.id]);
|
||||
return (
|
||||
<div className="detail episode">
|
||||
<DetailHero
|
||||
item={item}
|
||||
backdropItem={{ ...item, art: item.thumb, grandparentArt: item.thumb, ultraBlur: showItem?.ultraBlur ?? item.ultraBlur }}
|
||||
title={
|
||||
<>
|
||||
{showItem ? (
|
||||
<button className="title-link" onClick={() => navigate({ name: 'item', id: showItem.id })}>
|
||||
<TitleArt item={showItem} maxWidth={300} maxHeight={84} as="h2" />
|
||||
</button>
|
||||
) : (
|
||||
<h2 className="title-text small">{item.grandparentTitle}</h2>
|
||||
)}
|
||||
<h1 className="detail-subtitle">{item.title}</h1>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Facts item={{ ...item, contentRating: item.contentRating || showItem?.contentRating || '' }} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
{resume ? `Resume · ${remaining(item)}` : 'Play'}
|
||||
</Button>
|
||||
{resume && (
|
||||
<Button variant="ghost" icon="replay10" onClick={() => playWithVersion(item, { offsetMs: 0, resume: false })}>
|
||||
From beginning
|
||||
</Button>
|
||||
)}
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
<div className="detail-tech">{technicalLine(item.media[0])}</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
{ordered.length > 0 && (
|
||||
<Shelf title={`More from ${item.parentTitle || `Season ${item.parentIndex}`}`} kind="landscape" onViewAll={() => navigate({ name: 'item', id: item.parentId })}>
|
||||
{ordered.map((e) => (
|
||||
<LandscapeCard key={e.id} item={e} episodeStyle />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
<CastRow item={item.roles.length ? item : (showItem ?? item)} title={item.roles.length ? 'Cast & Guest Stars' : 'Cast & Crew'} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Collections ——————————————————————————————————————————————————
|
||||
|
||||
function CollectionDetail({ item }: { item: Item }) {
|
||||
const members = useServerQuery(['collectionItems', item.id], (s) => api.collectionItems(s, item.id));
|
||||
const list = members.data ?? [];
|
||||
const backdropItem = item.art ? item : list.find((m) => m.art);
|
||||
return (
|
||||
<div className="detail collection">
|
||||
<DetailHero item={item} backdropItem={backdropItem} title={<h1 className="title-text">{item.title}</h1>}>
|
||||
<div className="facts">
|
||||
<span className="fact">{list.length ? `${list.length} titles` : 'Collection'}</span>
|
||||
{item.contentRating && <span className="badge">{item.contentRating}</span>}
|
||||
</div>
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" disabled={!list.length} onClick={() => list[0] && playWithVersion(list.find((m) => !isWatched(m)) ?? list[0])}>
|
||||
Play
|
||||
</Button>
|
||||
<MoreButton item={item} />
|
||||
</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body single">
|
||||
<div className="detail-main">
|
||||
{members.isLoading && <PageLoader />}
|
||||
<div className="poster-grid auto">
|
||||
{list.map((m) => (
|
||||
<PosterCard key={m.id} item={m} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
328
src/screens/LibraryBrowser.tsx
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item, Section } from '../plex/types';
|
||||
import { queryClient, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import type { SectionKind } from '../app/router';
|
||||
import { PosterCard } from '../ui/media';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { EmptyState, ErrorState, IconButton, PageLoader, Select, Spinner } from '../ui/primitives';
|
||||
import { openMenu, type MenuItem } from '../ui/overlays';
|
||||
|
||||
const PAGE = 120;
|
||||
const CARD_WIDTH = { compact: 148, comfortable: 182, large: 228 } as const;
|
||||
const BOOLEAN_LABELS: Record<string, string> = {
|
||||
unwatched: 'Unwatched',
|
||||
inProgress: 'In progress',
|
||||
hdr: 'HDR',
|
||||
dovi: 'Dolby Vision',
|
||||
hdr10plus: 'HDR10+',
|
||||
atmos: 'Dolby Atmos',
|
||||
unmatched: 'Unmatched',
|
||||
};
|
||||
const QUICK_FILTERS = ['genre', 'year', 'decade', 'contentRating', 'resolution', 'collection', 'studio', 'country', 'audioLanguage', 'subtitleLanguage', 'label', 'editionTitle', 'network'];
|
||||
|
||||
function useDebounced<T>(value: T, ms: number) {
|
||||
const [v, setV] = useState(value);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setV(value), ms);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, ms]);
|
||||
return v;
|
||||
}
|
||||
|
||||
export function LibraryBrowser({ section, kind }: { section: Section; kind: SectionKind }) {
|
||||
const server = useServer();
|
||||
const type = kind === 'movie' ? 1 : 2;
|
||||
const views = useSettings((s) => s.libraryViews);
|
||||
const setSetting = useSettings((s) => s.set);
|
||||
const posterSize = useSettings((s) => s.posterSize);
|
||||
const view = views[section.id] ?? { sort: 'titleSort:asc', filters: {} };
|
||||
const [query, setQuery] = useState('');
|
||||
const title = useDebounced(query.trim(), 300);
|
||||
const meta = useServerQuery(['libraryMeta', section.id, type], (s) => api.libraryMeta(s, section.id, type), { staleTime: 30 * 60_000 });
|
||||
|
||||
const saveView = (next: Partial<typeof view>) => setSetting('libraryViews', { ...views, [section.id]: { ...view, ...next } });
|
||||
const [sortKey, sortDir] = view.sort.split(':') as [string, 'asc' | 'desc'];
|
||||
const sortTitle = meta.data?.sorts.find((s) => s.key === sortKey)?.title ?? 'Title';
|
||||
|
||||
const filterLabel = (filter: string) => meta.data?.filters.find((f) => f.filter === filter)?.title ?? BOOLEAN_LABELS[filter] ?? filter;
|
||||
|
||||
// Option titles for active filter chips (values are Plex keys).
|
||||
const [chipTitles, setChipTitles] = useState<Record<string, string>>({});
|
||||
|
||||
const loadOptions = async (f: { filter: string; key: string }) =>
|
||||
queryClient.fetchQuery({
|
||||
queryKey: [server.machineId, 'filterOptions', f.key, type],
|
||||
queryFn: () => api.filterOptions(server, f.key, type),
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
|
||||
const openFilters = async (anchor: HTMLElement) => {
|
||||
const filters = meta.data?.filters ?? [];
|
||||
const bools = filters.filter((f) => f.type === 'boolean');
|
||||
const strings = filters.filter((f) => f.type !== 'boolean' && QUICK_FILTERS.includes(f.filter));
|
||||
const options = await Promise.all(strings.map((f) => loadOptions(f).catch(() => [])));
|
||||
const items: MenuItem[] = [
|
||||
...bools.map((f) => ({
|
||||
label: BOOLEAN_LABELS[f.filter] ?? f.title,
|
||||
checked: view.filters[f.filter] === '1',
|
||||
onSelect: () => {
|
||||
const next = { ...view.filters };
|
||||
if (next[f.filter] === '1') delete next[f.filter];
|
||||
else next[f.filter] = '1';
|
||||
saveView({ filters: next });
|
||||
},
|
||||
})),
|
||||
{ divider: true },
|
||||
...strings
|
||||
.map((f, i): MenuItem => ({
|
||||
label: f.title,
|
||||
hint: view.filters[f.filter] ? chipTitles[`${f.filter}=${view.filters[f.filter]}`] ?? '1 selected' : undefined,
|
||||
submenu: options[i].length
|
||||
? options[i].slice(0, 400).map((o) => ({
|
||||
label: o.title,
|
||||
checked: view.filters[f.filter] === o.key,
|
||||
onSelect: () => {
|
||||
const next = { ...view.filters };
|
||||
if (next[f.filter] === o.key) delete next[f.filter];
|
||||
else next[f.filter] = o.key;
|
||||
setChipTitles((c) => ({ ...c, [`${f.filter}=${o.key}`]: o.title }));
|
||||
saveView({ filters: next });
|
||||
},
|
||||
}))
|
||||
: [{ label: 'No options', disabled: true }],
|
||||
}))
|
||||
.filter((m) => m.submenu!.length),
|
||||
];
|
||||
openMenu(items, anchor, { minWidth: 230 });
|
||||
};
|
||||
|
||||
// Resolve chip titles for remembered filters.
|
||||
useEffect(() => {
|
||||
const filters = meta.data?.filters ?? [];
|
||||
for (const [k, v] of Object.entries(view.filters)) {
|
||||
const f = filters.find((x) => x.filter === k);
|
||||
if (!f || f.type === 'boolean' || chipTitles[`${k}=${v}`]) continue;
|
||||
loadOptions(f)
|
||||
.then((opts) => {
|
||||
const o = opts.find((x) => x.key === v);
|
||||
if (o) setChipTitles((c) => ({ ...c, [`${k}=${v}`]: o.title }));
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}, [meta.data, view.filters]);
|
||||
|
||||
if (meta.isError && !meta.data) return <ErrorState error={meta.error} onRetry={() => meta.refetch()} />;
|
||||
|
||||
const activeFilters = Object.entries(view.filters);
|
||||
return (
|
||||
<div className="library">
|
||||
<div className="lib-toolbar">
|
||||
<div className="lib-search">
|
||||
<Icon name="search" size={16} />
|
||||
<input value={query} placeholder={`Search ${section.title}`} onChange={(e) => setQuery(e.target.value)} onKeyDown={(e) => e.key === 'Escape' && (e.stopPropagation(), setQuery(''))} />
|
||||
{query && (
|
||||
<button aria-label="Clear" onClick={() => setQuery('')}>
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button className="select" onClick={(e) => openFilters(e.currentTarget)} disabled={!meta.data}>
|
||||
<Icon name="sliders" size={15} />
|
||||
<span className="select-value">Filter{activeFilters.length ? ` · ${activeFilters.length}` : ''}</span>
|
||||
</button>
|
||||
<div className="sort-group">
|
||||
<Select
|
||||
value={sortKey}
|
||||
prefix="Sort"
|
||||
label="Sort by"
|
||||
options={(meta.data?.sorts ?? [{ key: 'titleSort', title: 'Title', defaultDirection: 'asc' }]).map((s) => ({ value: s.key, label: s.title }))}
|
||||
onChange={(k) => {
|
||||
const s = meta.data?.sorts.find((x) => x.key === k);
|
||||
saveView({ sort: `${k}:${s?.defaultDirection ?? 'asc'}` });
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon={sortDir === 'asc' ? 'chevronUp' : 'chevronDown'}
|
||||
label={sortDir === 'asc' ? 'Ascending' : 'Descending'}
|
||||
className="sort-dir"
|
||||
onClick={() => saveView({ sort: `${sortKey}:${sortDir === 'asc' ? 'desc' : 'asc'}` })}
|
||||
/>
|
||||
</div>
|
||||
<div className="toolbar-spacer" />
|
||||
<div className="density" role="group" aria-label="Poster size">
|
||||
{(['compact', 'comfortable', 'large'] as const).map((s, i) => (
|
||||
<button key={s} className={posterSize === s ? 'on' : ''} aria-label={`${s} posters`} title={`${s[0].toUpperCase()}${s.slice(1)} posters`} onClick={() => setSetting('posterSize', s)}>
|
||||
<span style={{ width: 8 + i * 3, height: 11 + i * 4 }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{activeFilters.length > 0 && (
|
||||
<div className="filter-chips">
|
||||
{activeFilters.map(([k, v]) => (
|
||||
<button
|
||||
key={k}
|
||||
className="chip"
|
||||
onClick={() => {
|
||||
const next = { ...view.filters };
|
||||
delete next[k];
|
||||
saveView({ filters: next });
|
||||
}}
|
||||
>
|
||||
{v === '1' && BOOLEAN_LABELS[k] ? BOOLEAN_LABELS[k] : `${filterLabel(k)}: ${chipTitles[`${k}=${v}`] ?? v}`}
|
||||
<Icon name="x" size={12} />
|
||||
</button>
|
||||
))}
|
||||
<button className="btn text" onClick={() => saveView({ filters: {} })}>
|
||||
Clear all
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<LibraryGrid key={`${section.id}|${view.sort}|${JSON.stringify(view.filters)}|${title}`} section={section} type={type} sort={view.sort} filters={view.filters} title={title} sortTitle={sortTitle} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { section: Section; type: number; sort: string; filters: Record<string, string>; title: string; sortTitle: string }) {
|
||||
const server = useServer();
|
||||
const posterSize = useSettings((s) => s.posterSize);
|
||||
const gridRef = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(0);
|
||||
const [scrollEl, setScrollEl] = useState<HTMLElement | null>(null);
|
||||
const [pages, setPages] = useState<Record<number, Item[]>>({});
|
||||
const [total, setTotal] = useState<number | null>(null);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
const inflight = useRef(new Set<number>());
|
||||
const params = { type, sort, filters, title };
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = gridRef.current;
|
||||
if (!el) return;
|
||||
setScrollEl(el.closest('.main-scroll') as HTMLElement);
|
||||
const ro = new ResizeObserver(() => setWidth(el.clientWidth));
|
||||
ro.observe(el);
|
||||
setWidth(el.clientWidth);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
const loadPage = useCallback(
|
||||
async (p: number) => {
|
||||
if (inflight.current.has(p)) return;
|
||||
inflight.current.add(p);
|
||||
try {
|
||||
const page = await queryClient.fetchQuery({
|
||||
queryKey: [server.machineId, 'libraryPage', section.id, params, p],
|
||||
queryFn: () => api.libraryPage(server, section.id, { ...params, start: p * PAGE, size: PAGE }),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
setPages((prev) => ({ ...prev, [p]: page.items }));
|
||||
setTotal(page.total);
|
||||
} catch (e) {
|
||||
setError(e);
|
||||
} finally {
|
||||
inflight.current.delete(p);
|
||||
}
|
||||
},
|
||||
[server, section.id, JSON.stringify(params)],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
loadPage(0);
|
||||
}, [loadPage]);
|
||||
|
||||
const gap = 16;
|
||||
const target = CARD_WIDTH[posterSize];
|
||||
const cols = Math.max(2, Math.floor((width + gap) / (target + gap)));
|
||||
const cardW = width ? (width - gap * (cols - 1)) / cols : target;
|
||||
const rowH = cardW * 1.5 + 52 + 22;
|
||||
const rows = total === null ? 0 : Math.ceil(total / cols);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rows,
|
||||
getScrollElement: () => scrollEl,
|
||||
estimateSize: () => rowH,
|
||||
overscan: 3,
|
||||
scrollMargin: gridRef.current?.offsetTop ?? 0,
|
||||
// Keep jump targets clear of the sticky top bar and toolbar.
|
||||
scrollPaddingStart: 150,
|
||||
});
|
||||
useEffect(() => virtualizer.measure(), [rowH, cols]);
|
||||
|
||||
const vrows = virtualizer.getVirtualItems();
|
||||
useEffect(() => {
|
||||
if (!vrows.length) return;
|
||||
const first = vrows[0].index * cols;
|
||||
const last = (vrows[vrows.length - 1].index + 1) * cols;
|
||||
for (let p = Math.floor(first / PAGE); p <= Math.floor(Math.min(last, (total ?? 1) - 1) / PAGE); p++) if (!pages[p]) loadPage(p);
|
||||
}, [vrows.map((r) => r.index).join(','), cols, total]);
|
||||
|
||||
const itemAt = (i: number) => pages[Math.floor(i / PAGE)]?.[i % PAGE];
|
||||
|
||||
// A–Z jumps for title order.
|
||||
const alpha = sort.startsWith('titleSort') && !title;
|
||||
const letters = useServerQuery(['firstCharacter', section.id, type, filters], (s) => api.firstCharacters(s, section.id, { type, ...filters }), { enabled: alpha, staleTime: 120_000 });
|
||||
const jump = (char: string) => {
|
||||
if (!letters.data) return;
|
||||
const list = sort.endsWith(':desc') ? [...letters.data].reverse() : letters.data;
|
||||
let offset = 0;
|
||||
for (const l of list) {
|
||||
if (l.title === char) break;
|
||||
offset += l.size;
|
||||
}
|
||||
virtualizer.scrollToIndex(Math.floor(offset / cols), { align: 'start' });
|
||||
};
|
||||
|
||||
if (error && total === null) return <ErrorState error={error} onRetry={() => (setError(null), loadPage(0))} />;
|
||||
return (
|
||||
<div className="library-body">
|
||||
<div className="grid-count">
|
||||
{total === null ? <Spinner size={14} /> : `${total.toLocaleString()} ${total === 1 ? 'title' : 'titles'}`}
|
||||
{total !== null && sortTitle && <span className="dim"> · by {sortTitle.toLowerCase()}</span>}
|
||||
</div>
|
||||
<div className="lib-grid-wrap">
|
||||
<div ref={gridRef} className="lib-grid" style={{ height: virtualizer.getTotalSize() }}>
|
||||
{total === 0 && (
|
||||
<EmptyState icon="search" title="Nothing matches">
|
||||
Try a different search or remove a filter.
|
||||
</EmptyState>
|
||||
)}
|
||||
{vrows.map((row) => (
|
||||
<div
|
||||
key={row.key}
|
||||
className="lib-row"
|
||||
style={{ transform: `translateY(${row.start - virtualizer.options.scrollMargin}px)`, gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gap }}
|
||||
>
|
||||
{Array.from({ length: cols }, (_, c) => {
|
||||
const i = row.index * cols + c;
|
||||
if (total !== null && i >= total) return <div key={c} />;
|
||||
const item = itemAt(i);
|
||||
return item ? (
|
||||
<PosterCard key={item.id} item={item} />
|
||||
) : (
|
||||
<div key={c} className="card poster placeholder">
|
||||
<div className="card-cover skeleton" />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{alpha && letters.data && letters.data.length > 3 && (
|
||||
<div className="alpha-rail" aria-label="Jump to letter">
|
||||
{letters.data.map((l) => (
|
||||
<button key={l.title} onClick={() => jump(l.title)} title={`${l.title} · ${l.size}`}>
|
||||
{l.title}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{total === null && <PageLoader />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
61
src/screens/Person.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import * as api from '../plex/api';
|
||||
import { useSections, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { PosterCard } from '../ui/media';
|
||||
import { Artwork, EmptyState, ErrorState, PageLoader } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
export default function Person({ id, title, thumb }: { id: string; title: string; thumb?: string }) {
|
||||
const server = useServer();
|
||||
const sections = useSections();
|
||||
const titles = useServerQuery(['person', id], (s) => api.personTitles(s, id, sections.data ?? []), { enabled: !!sections.data });
|
||||
const list = titles.data ?? [];
|
||||
const movies = list.filter((i) => i.type === 'movie');
|
||||
const shows = list.filter((i) => i.type === 'show');
|
||||
const years = list.map((i) => i.year).filter(Boolean);
|
||||
return (
|
||||
<div className="person-page page-pad top">
|
||||
<header className="person-header">
|
||||
<div className="person-portrait">{thumb ? <Artwork src={server.image(thumb, 240, 240)} /> : <Icon name="person" size={52} />}</div>
|
||||
<div>
|
||||
<div className="micro">Filmography in your library</div>
|
||||
<h1>{title}</h1>
|
||||
{titles.data && (
|
||||
<p className="muted">
|
||||
{[movies.length ? `${movies.length} movie${movies.length === 1 ? '' : 's'}` : '', shows.length ? `${shows.length} show${shows.length === 1 ? '' : 's'}` : '', years.length ? `${Math.min(...years)}–${Math.max(...years)}` : '']
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
{titles.isError && <ErrorState error={titles.error} onRetry={() => titles.refetch()} />}
|
||||
{titles.isLoading && <PageLoader />}
|
||||
{titles.data && !list.length && (
|
||||
<EmptyState icon="person" title="Nothing in your library">
|
||||
{title} doesn’t appear in any movie or show on this server.
|
||||
</EmptyState>
|
||||
)}
|
||||
{movies.length > 0 && (
|
||||
<section className="person-section">
|
||||
<h2>Movies</h2>
|
||||
<div className="poster-grid auto">
|
||||
{movies.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{shows.length > 0 && (
|
||||
<section className="person-section">
|
||||
<h2>TV Shows</h2>
|
||||
<div className="poster-grid auto">
|
||||
{shows.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
191
src/screens/Search.tsx
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useServerQuery } from '../app/queries';
|
||||
import { navigate, useRouter } from '../app/router';
|
||||
import type { Item } from '../plex/types';
|
||||
import { LandscapeCard, PersonCard, PosterCard, Shelf } from '../ui/media';
|
||||
import { EmptyState, ErrorState, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
const RECENT_KEY = 'kaleido.recentSearches';
|
||||
const loadRecent = (): string[] => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
/** Plex search ranks per hub; float exact and prefix title matches to the top. */
|
||||
function rank(query: string, items: Item[]): Item[] {
|
||||
const q = query.toLowerCase();
|
||||
const score = (i: Item) => {
|
||||
const t = (i.type === 'episode' ? i.title : i.title).toLowerCase();
|
||||
if (t === q) return 0;
|
||||
if (t.startsWith(q)) return 1;
|
||||
if (t.split(/\W+/).some((w) => w.startsWith(q))) return 2;
|
||||
return 3;
|
||||
};
|
||||
return [...items].sort((a, b) => score(a) - score(b));
|
||||
}
|
||||
|
||||
export default function Search({ initial }: { initial?: string }) {
|
||||
const saved = useRouter((s) => s.current.state.query as string | undefined);
|
||||
const [query, setQuery] = useState(saved ?? initial ?? '');
|
||||
const [debounced, setDebounced] = useState(query);
|
||||
const [recent, setRecent] = useState(loadRecent);
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
input.current?.focus();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setDebounced(query.trim()), 250);
|
||||
useRouter.getState().setState({ query });
|
||||
return () => clearTimeout(t);
|
||||
}, [query]);
|
||||
|
||||
const results = useServerQuery(['search', debounced], (s) => api.search(s, debounced), { enabled: debounced.length > 0, staleTime: 60_000 });
|
||||
const recentlyAdded = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), { enabled: !debounced });
|
||||
|
||||
const remember = (q: string) => {
|
||||
const next = [q, ...recent.filter((r) => r.toLowerCase() !== q.toLowerCase())].slice(0, 8);
|
||||
setRecent(next);
|
||||
localStorage.setItem(RECENT_KEY, JSON.stringify(next));
|
||||
};
|
||||
|
||||
const hubs = results.data?.hubs ?? [];
|
||||
const all = hubs.flatMap((h) => h.items);
|
||||
const movies = rank(debounced, all.filter((i) => i.type === 'movie'));
|
||||
const shows = rank(debounced, all.filter((i) => i.type === 'show'));
|
||||
const episodes = rank(debounced, all.filter((i) => i.type === 'episode'));
|
||||
const collections = all.filter((i) => i.type === 'collection');
|
||||
const people = results.data?.people ?? [];
|
||||
const top = rank(debounced, [...movies, ...shows]).slice(0, 6);
|
||||
const inTop = new Set(top.map((i) => i.id));
|
||||
const moreMovies = movies.filter((i) => !inTop.has(i.id));
|
||||
const moreShows = shows.filter((i) => !inTop.has(i.id));
|
||||
|
||||
return (
|
||||
<div className="search-page page-pad top">
|
||||
<div className="search-hero">
|
||||
<div className="search-field">
|
||||
<Icon name="search" size={22} />
|
||||
<input
|
||||
ref={input}
|
||||
value={query}
|
||||
placeholder="Search movies, shows, episodes and people"
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && query.trim()) remember(query.trim());
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
if (query) setQuery('');
|
||||
else useRouter.getState().back();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{results.isFetching && <Spinner size={18} />}
|
||||
{query && (
|
||||
<button className="icon-btn" aria-label="Clear search" onClick={() => (setQuery(''), input.current?.focus())}>
|
||||
<Icon name="x" size={17} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!debounced && (
|
||||
<div className="search-idle">
|
||||
{recent.length > 0 && (
|
||||
<div className="recent-searches">
|
||||
<h3>Recent searches</h3>
|
||||
<div className="chips">
|
||||
{recent.map((r) => (
|
||||
<button key={r} className="chip" onClick={() => setQuery(r)}>
|
||||
<Icon name="clock" size={13} />
|
||||
{r}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className="btn text"
|
||||
onClick={() => {
|
||||
setRecent([]);
|
||||
localStorage.removeItem(RECENT_KEY);
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{recentlyAdded.data
|
||||
?.filter((h) => /recent/.test(h.id))
|
||||
.slice(0, 2)
|
||||
.map((h) => (
|
||||
<Shelf key={h.id} title={h.title} className="flush">
|
||||
{h.items.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{debounced && results.isError && <ErrorState error={results.error} onRetry={() => results.refetch()} />}
|
||||
{debounced && results.data && !all.length && !people.length && (
|
||||
<EmptyState icon="search" title={`No results for “${debounced}”`}>
|
||||
Check the spelling, or search for an actor, director or episode title.
|
||||
</EmptyState>
|
||||
)}
|
||||
{debounced && results.data && (
|
||||
<div className="search-results" onClick={() => remember(debounced)}>
|
||||
{top.length > 0 && (
|
||||
<section className="search-top">
|
||||
<h3>Top results</h3>
|
||||
<div className="poster-grid auto">
|
||||
{top.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{moreMovies.length > 0 && (
|
||||
<Shelf title="More movies" className="flush">
|
||||
{moreMovies.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{moreShows.length > 0 && (
|
||||
<Shelf title="More TV shows" className="flush">
|
||||
{moreShows.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{episodes.length > 0 && (
|
||||
<Shelf title="Episodes" kind="landscape" className="flush">
|
||||
{episodes.map((i) => (
|
||||
<LandscapeCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{people.length > 0 && (
|
||||
<Shelf title="People" kind="people" className="flush">
|
||||
{people.map((p) => (
|
||||
<PersonCard key={p.id} name={p.tag} thumb={p.thumb} onClick={() => navigate({ name: 'person', id: p.id, title: p.tag, thumb: p.thumb })} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{collections.length > 0 && (
|
||||
<Shelf title="Collections" className="flush">
|
||||
{collections.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
111
src/screens/Section.tsx
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { useMemo } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useSectionFor, useServerQuery } from '../app/queries';
|
||||
import { navigate, type SectionKind, type SectionTab } from '../app/router';
|
||||
import { useSettings } from '../app/settings';
|
||||
import type { Section } from '../plex/types';
|
||||
import { Hero } from '../ui/Hero';
|
||||
import { HubShelf, PosterCard } from '../ui/media';
|
||||
import { EmptyState, ErrorState, PageLoader, Select } from '../ui/primitives';
|
||||
import { buildFeatures, HIDDEN_HUBS, recentSeasons } from './discover';
|
||||
import { LibraryBrowser } from './LibraryBrowser';
|
||||
|
||||
const TABS: { id: SectionTab; label: string }[] = [
|
||||
{ id: 'discover', label: 'Discover' },
|
||||
{ id: 'library', label: 'Library' },
|
||||
{ id: 'collections', label: 'Collections' },
|
||||
];
|
||||
|
||||
function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind; tab: SectionTab; section: Section; all: Section[]; overlay: boolean }) {
|
||||
const set = useSettings((s) => s.set);
|
||||
return (
|
||||
<div className={`section-header${overlay ? ' overlay' : ''}`}>
|
||||
<h1>{kind === 'movie' ? 'Movies' : 'TV Shows'}</h1>
|
||||
<nav className="section-tabs" role="tablist">
|
||||
{TABS.map((t) => (
|
||||
<button key={t.id} role="tab" aria-selected={t.id === tab} className={t.id === tab ? 'active' : ''} onClick={() => navigate({ name: 'section', kind, tab: t.id }, { replace: true })}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
{all.length > 1 && (
|
||||
<Select
|
||||
className="section-picker"
|
||||
value={section.id}
|
||||
label="Library"
|
||||
options={all.map((s) => ({ value: s.id, label: s.title }))}
|
||||
onChange={(v) => set(kind === 'movie' ? 'movieSection' : 'showSection', v)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Discover({ kind, section }: { kind: SectionKind; section: Section }) {
|
||||
const hubs = useServerQuery(['sectionHubs', section.id], (s) => api.sectionHubs(s, section.id));
|
||||
const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), { staleTime: 15_000 });
|
||||
const seasons = useServerQuery(['recentSeasons', section.id], (s) => recentSeasons(s, section.id), { enabled: kind === 'show', staleTime: 120_000 });
|
||||
const features = useMemo(() => buildFeatures(hubs.data ?? [], 7, kind === 'movie' ? 1 : 2), [hubs.data, kind]);
|
||||
|
||||
if (hubs.isError && !hubs.data) return <ErrorState error={hubs.error} onRetry={() => hubs.refetch()} />;
|
||||
if (!hubs.data) return <PageLoader />;
|
||||
const rest = hubs.data.filter((h) => !HIDDEN_HUBS.test(h.id));
|
||||
// TV: episodes lead; redundant episode hubs are skipped when they repeat Continue Watching.
|
||||
const cwIds = new Set((cw.data ?? []).map((i) => i.id));
|
||||
const shelves = rest.filter((h) => !(h.items.length && h.items.every((i) => cwIds.has(i.id))));
|
||||
return (
|
||||
<>
|
||||
<Hero features={features} variant="section" />
|
||||
<div className="shelves over-hero">
|
||||
<HubShelf title={kind === 'show' ? 'Next Episodes' : 'Continue Watching'} items={cw.data ?? []} continueWatching />
|
||||
{kind === 'show' && <HubShelf title="New Seasons" items={seasons.data ?? []} landscape={false} />}
|
||||
{shelves.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title.replace(/ in (Movies|TV Shows)$/, '')} items={h.items} onViewAll={h.more || h.key.includes('/all') ? () => navigate({ name: 'hub', key: h.key, title: h.title }) : undefined} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Collections({ section }: { section: Section }) {
|
||||
const q = useServerQuery(['collections', section.id], (s) => api.collections(s, section.id));
|
||||
if (q.isError) return <ErrorState error={q.error} onRetry={() => q.refetch()} />;
|
||||
if (!q.data) return <PageLoader />;
|
||||
if (!q.data.length)
|
||||
return (
|
||||
<EmptyState icon="collection" title="No collections yet">
|
||||
Collections created in Plex for {section.title} appear here.
|
||||
</EmptyState>
|
||||
);
|
||||
return (
|
||||
<div className="page-pad">
|
||||
<div className="grid-count">{q.data.length.toLocaleString()} collections</div>
|
||||
<div className="poster-grid auto">
|
||||
{q.data.map((c) => (
|
||||
<PosterCard key={c.id} item={c} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SectionScreen({ kind, tab }: { kind: SectionKind; tab: SectionTab }) {
|
||||
const { section, all, loading } = useSectionFor(kind);
|
||||
if (loading) return <PageLoader />;
|
||||
if (!section)
|
||||
return (
|
||||
<div className="page-pad top">
|
||||
<EmptyState icon={kind === 'movie' ? 'film' : 'tv'} title={`No ${kind === 'movie' ? 'movie' : 'TV'} libraries`}>
|
||||
This server has no {kind === 'movie' ? 'movie' : 'TV show'} libraries you can access.
|
||||
</EmptyState>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={`section-screen tab-${tab}`} key={section.id}>
|
||||
<SectionHeader kind={kind} tab={tab} section={section} all={all} overlay={tab === 'discover'} />
|
||||
{tab === 'discover' && <Discover kind={kind} section={section} />}
|
||||
{tab === 'library' && <LibraryBrowser section={section} kind={kind} />}
|
||||
{tab === 'collections' && <Collections section={section} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
102
src/screens/ServerPicker.tsx
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSession } from '../app/session';
|
||||
import type { ServerResource } from '../plex/types';
|
||||
import { Button, KaleidoMark, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { WindowDrag } from './WindowDrag';
|
||||
import { useRouter } from '../app/router';
|
||||
|
||||
export function ServerPicker() {
|
||||
const resources = useSession((s) => s.resources);
|
||||
const status = useSession((s) => s.status);
|
||||
const error = useSession((s) => s.error);
|
||||
const user = useSession((s) => s.user);
|
||||
const current = useSession((s) => s.server);
|
||||
const choose = useSession((s) => s.chooseServer);
|
||||
const refresh = useSession((s) => s.refreshResources);
|
||||
const signOut = useSession((s) => s.signOut);
|
||||
const [pending, setPending] = useState('');
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!resources.length) {
|
||||
setRefreshing(true);
|
||||
refresh()
|
||||
.catch(() => {})
|
||||
.finally(() => setRefreshing(false));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const pick = async (r: ServerResource) => {
|
||||
setPending(r.id);
|
||||
await choose(r);
|
||||
setPending('');
|
||||
useRouter.getState().reset({ name: 'home' });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-screen">
|
||||
<WindowDrag />
|
||||
<div className="auth-backdrop" />
|
||||
<div className="auth-card wide">
|
||||
<div className="auth-brand">
|
||||
<KaleidoMark size={40} />
|
||||
<span>KALEIDO</span>
|
||||
</div>
|
||||
<h1>Choose a server</h1>
|
||||
<p className="auth-lede">{user ? `Signed in as ${user.title}.` : 'Pick the Plex Media Server to browse.'}</p>
|
||||
<div className="server-list">
|
||||
{refreshing && !resources.length && (
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Finding your servers…
|
||||
</div>
|
||||
)}
|
||||
{resources.map((r) => (
|
||||
<button key={r.id} className={`server-row${current?.machineId === r.id ? ' current' : ''}`} onClick={() => pick(r)} disabled={!!pending}>
|
||||
<div className="server-glyph">
|
||||
<Icon name="server" size={20} />
|
||||
</div>
|
||||
<div className="server-text">
|
||||
<strong>{r.name}</strong>
|
||||
<small>
|
||||
{r.owned ? 'Your server' : `Shared by ${r.sourceTitle || 'a friend'}`} · {r.platform || 'Plex Media Server'}
|
||||
{r.productVersion ? ` · ${r.productVersion.split('-')[0]}` : ''}
|
||||
</small>
|
||||
</div>
|
||||
<span className={`presence${r.presence ? ' on' : ''}`}>{r.presence ? 'Online' : 'Offline'}</span>
|
||||
{pending === r.id && status === 'connecting' ? <Spinner size={18} /> : <Icon name="next" size={18} className="dim" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{error && (
|
||||
<div className="auth-error">
|
||||
<Icon name="alert" size={16} /> {error}
|
||||
</div>
|
||||
)}
|
||||
<div className="auth-actions spread">
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon="refresh"
|
||||
busy={refreshing}
|
||||
onClick={() => {
|
||||
setRefreshing(true);
|
||||
refresh()
|
||||
.catch(() => {})
|
||||
.finally(() => setRefreshing(false));
|
||||
}}
|
||||
>
|
||||
Refresh
|
||||
</Button>
|
||||
{current && (
|
||||
<Button variant="ghost" onClick={() => useSession.setState({ status: 'ready', error: '' })}>
|
||||
Keep {current.name}
|
||||
</Button>
|
||||
)}
|
||||
<button className="auth-link" onClick={signOut}>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
193
src/screens/SignIn.tsx
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { authUrl, checkPin, createPin, type Pin } from '../plex/account';
|
||||
import { useSession } from '../app/session';
|
||||
import { openExternal } from '../platform/native';
|
||||
import { Button, KaleidoMark, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { WindowDrag } from './WindowDrag';
|
||||
|
||||
type Mode = 'start' | 'browser' | 'code' | 'manual';
|
||||
|
||||
export function SignIn() {
|
||||
const completeSignIn = useSession((s) => s.completeSignIn);
|
||||
const connectManual = useSession((s) => s.connectManual);
|
||||
const sessionError = useSession((s) => s.error);
|
||||
const [mode, setMode] = useState<Mode>('start');
|
||||
const [pin, setPin] = useState<Pin | null>(null);
|
||||
const [error, setError] = useState(sessionError);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [url, setUrl] = useState('');
|
||||
const [token, setToken] = useState('');
|
||||
const poll = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const stopPolling = () => {
|
||||
if (poll.current) clearInterval(poll.current);
|
||||
poll.current = null;
|
||||
};
|
||||
useEffect(() => stopPolling, []);
|
||||
|
||||
const begin = async (strong: boolean) => {
|
||||
setError('');
|
||||
setBusy(true);
|
||||
stopPolling();
|
||||
try {
|
||||
const p = await createPin(strong);
|
||||
setPin(p);
|
||||
setMode(strong ? 'browser' : 'code');
|
||||
if (strong) await openExternal(authUrl(p));
|
||||
const started = Date.now();
|
||||
poll.current = setInterval(async () => {
|
||||
if (Date.now() - started > 15 * 60_000) {
|
||||
stopPolling();
|
||||
setError('The sign-in request expired. Try again.');
|
||||
setMode('start');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const t = await checkPin(p);
|
||||
if (t) {
|
||||
stopPolling();
|
||||
await completeSignIn(t);
|
||||
}
|
||||
} catch {
|
||||
/* keep polling */
|
||||
}
|
||||
}, 1500);
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const manual = async () => {
|
||||
setError('');
|
||||
setBusy(true);
|
||||
try {
|
||||
let u = url.trim();
|
||||
if (!/^https?:\/\//.test(u)) u = `http://${u}`;
|
||||
if (!/:\d+/.test(u.replace(/^https?:\/\//, ''))) u = `${u.replace(/\/$/, '')}:32400`;
|
||||
await connectManual(u, token.trim());
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-screen">
|
||||
<WindowDrag />
|
||||
<div className="auth-backdrop" />
|
||||
<div className="auth-card">
|
||||
<div className="auth-brand">
|
||||
<KaleidoMark size={46} />
|
||||
<span>KALEIDO</span>
|
||||
</div>
|
||||
{mode === 'start' && (
|
||||
<>
|
||||
<h1>Your Plex library, front and center.</h1>
|
||||
<p className="auth-lede">Sign in with your Plex account to browse and play everything on your servers.</p>
|
||||
<div className="auth-actions">
|
||||
<Button variant="primary" size="lg" icon="external" busy={busy} onClick={() => begin(true)}>
|
||||
Sign in with Plex
|
||||
</Button>
|
||||
<button className="auth-link" onClick={() => begin(false)}>
|
||||
Use a code at plex.tv/link instead
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'browser' && (
|
||||
<>
|
||||
<h1>Continue in your browser</h1>
|
||||
<p className="auth-lede">We opened Plex’s sign-in page. Kaleido continues automatically once you approve it.</p>
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Waiting for Plex…
|
||||
</div>
|
||||
<div className="auth-actions">
|
||||
<Button variant="ghost" icon="external" onClick={() => pin && openExternal(authUrl(pin))}>
|
||||
Open the page again
|
||||
</Button>
|
||||
<button
|
||||
className="auth-link"
|
||||
onClick={() => {
|
||||
stopPolling();
|
||||
setMode('start');
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'code' && pin && (
|
||||
<>
|
||||
<h1>Link Kaleido</h1>
|
||||
<p className="auth-lede">
|
||||
On any device, go to <b>plex.tv/link</b> and enter this code.
|
||||
</p>
|
||||
<div className="auth-code selectable">{pin.code}</div>
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Waiting for Plex…
|
||||
</div>
|
||||
<div className="auth-actions">
|
||||
<Button variant="ghost" icon="external" onClick={() => openExternal('https://plex.tv/link')}>
|
||||
Open plex.tv/link
|
||||
</Button>
|
||||
<button
|
||||
className="auth-link"
|
||||
onClick={() => {
|
||||
stopPolling();
|
||||
setMode('start');
|
||||
}}
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'manual' && (
|
||||
<>
|
||||
<h1>Connect to a server</h1>
|
||||
<p className="auth-lede">Enter a Plex Media Server address and an access token. Account features such as profiles need a full sign-in.</p>
|
||||
<form
|
||||
className="auth-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
manual();
|
||||
}}
|
||||
>
|
||||
<label className="field">
|
||||
<span>Server address</span>
|
||||
<input autoFocus value={url} placeholder="192.168.1.20:32400" onChange={(e) => setUrl(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Access token</span>
|
||||
<input type="password" value={token} onChange={(e) => setToken(e.target.value)} />
|
||||
</label>
|
||||
<div className="auth-actions">
|
||||
<Button variant="primary" busy={busy} disabled={!url || !token} type="submit">
|
||||
Connect
|
||||
</Button>
|
||||
<button type="button" className="auth-link" onClick={() => setMode('start')}>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
{error && (
|
||||
<div className="auth-error">
|
||||
<Icon name="alert" size={16} /> {error}
|
||||
</div>
|
||||
)}
|
||||
{mode === 'start' && (
|
||||
<button className="auth-manual" onClick={() => setMode('manual')}>
|
||||
Connect to a server manually
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
44
src/screens/Splash.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSettings } from '../app/settings';
|
||||
|
||||
const FACETS = [
|
||||
{ fill: '#C3E8D3', d: 'M33,4 L55.5,17 L42.5,24.5 L33,19 Z' },
|
||||
{ fill: '#71B9B0', d: 'M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z' },
|
||||
{ fill: '#3D7C7B', d: 'M55.5,47 L33,60 L33,45 L42.5,39.5 Z' },
|
||||
{ fill: '#D0A977', d: 'M31,60 L8.5,47 L21.5,39.5 L31,45 Z' },
|
||||
{ fill: '#E9D8AE', d: 'M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z' },
|
||||
{ fill: '#EEF2DD', d: 'M8.5,17 L31,4 L31,19 L21.5,24.5 Z' },
|
||||
];
|
||||
|
||||
/**
|
||||
* The cold-start aperture: the six facets twist open around the dark center,
|
||||
* hold until startup data is ready, then the view flies through the aperture.
|
||||
*/
|
||||
export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }) {
|
||||
const reduced = useSettings((s) => s.reducedMotion);
|
||||
const [phase, setPhase] = useState<'opening' | 'held' | 'leaving'>('opening');
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setPhase('held'), reduced ? 0 : 1100);
|
||||
return () => clearTimeout(t);
|
||||
}, [reduced]);
|
||||
useEffect(() => {
|
||||
if (phase === 'held' && ready) setPhase('leaving');
|
||||
}, [phase, ready]);
|
||||
useEffect(() => {
|
||||
if (phase !== 'leaving') return;
|
||||
const t = setTimeout(onDone, reduced ? 0 : 620);
|
||||
return () => clearTimeout(t);
|
||||
}, [phase]);
|
||||
return (
|
||||
<div className={`splash ${phase}`} data-tauri-drag-region>
|
||||
<div className="splash-mark">
|
||||
<svg viewBox="0 0 64 64" width="92" height="92" aria-hidden="true">
|
||||
{FACETS.map((f, i) => (
|
||||
<path key={i} d={f.d} fill={f.fill} style={{ ['--i' as string]: i }} />
|
||||
))}
|
||||
</svg>
|
||||
<span className="splash-word">KALEIDO</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
22
src/screens/WindowDrag.tsx
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { isNative, win } from '../platform/native';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
/** A draggable strip with window controls for full-screen states without the top bar. */
|
||||
export function WindowDrag() {
|
||||
if (!isNative) return null;
|
||||
return (
|
||||
<div className="window-drag" data-tauri-drag-region>
|
||||
<div className="window-controls">
|
||||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Maximize" onClick={() => win.toggleMaximize()}>
|
||||
<Icon name="maximize" size={13} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
||||
<Icon name="x" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
96
src/screens/dialogs/Artwork.tsx
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useServerQuery } from '../../app/queries';
|
||||
import { Dialog, promptDialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, EmptyState, PageLoader } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
const KIND = { poster: 'posters', art: 'arts', clearLogo: 'clearLogos' } as const;
|
||||
const LABEL = { poster: 'poster', art: 'background', clearLogo: 'logo' } as const;
|
||||
|
||||
export function ArtworkDialog({ item, type, onClose }: { item: Item; type: 'poster' | 'art' | 'clearLogo'; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const options = useServerQuery(['artwork', item.id, type], (s) => api.artworkOptions(s, item.id, KIND[type]), { staleTime: 0 });
|
||||
const [busy, setBusy] = useState('');
|
||||
|
||||
const choose = async (key: string) => {
|
||||
setBusy(key);
|
||||
try {
|
||||
await api.selectArtwork(server, item.id, type, key);
|
||||
toast(`Updated the ${LABEL[type]}`, 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
|
||||
const upload = () => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,image/webp';
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
setBusy('upload');
|
||||
try {
|
||||
await api.uploadArtwork(server, item.id, KIND[type], file);
|
||||
toast(`Uploaded a new ${LABEL[type]}`, 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
};
|
||||
|
||||
const fromUrl = async () => {
|
||||
const url = await promptDialog({ title: `Use an image from the web`, message: `Plex downloads the image and uses it as the ${LABEL[type]}.`, confirm: 'Use image', input: { label: 'Image URL', placeholder: 'https://…' } });
|
||||
if (url) choose(url);
|
||||
};
|
||||
|
||||
const shape = type === 'poster' ? 'poster' : type === 'art' ? 'landscape' : 'logo';
|
||||
return (
|
||||
<Dialog
|
||||
title={`Choose ${LABEL[type]}`}
|
||||
subtitle={item.title}
|
||||
onClose={onClose}
|
||||
width={880}
|
||||
footer={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" icon="link" onClick={fromUrl}>
|
||||
From URL
|
||||
</Button>
|
||||
<Button variant="ghost" icon="upload" busy={busy === 'upload'} onClick={upload}>
|
||||
Upload image
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{options.isLoading && <PageLoader />}
|
||||
{options.data && !options.data.length && <EmptyState icon="image" title="No alternatives">Upload an image or use one from the web.</EmptyState>}
|
||||
<div className={`artwork-grid ${shape}`}>
|
||||
{options.data?.map((o) => (
|
||||
<button key={o.key} className={`artwork-option${o.selected ? ' selected' : ''}`} onClick={() => choose(o.key)} disabled={!!busy}>
|
||||
<img src={server.image(o.thumb, shape === 'poster' ? 180 : 320, shape === 'poster' ? 270 : 180, { format: shape === 'logo' ? 'png' : 'jpeg' })} alt="" loading="lazy" />
|
||||
{o.selected && (
|
||||
<span className="artwork-selected">
|
||||
<Icon name="check" size={14} strokeWidth={2.4} />
|
||||
</span>
|
||||
)}
|
||||
{o.provider && <span className="artwork-provider">{o.provider.replace(/^com\.plexapp\.agents\.|^tv\.plex\.agents\./, '')}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
60
src/screens/dialogs/DialogHost.tsx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { useDialogs } from '../../app/actions';
|
||||
import { useSession } from '../../app/session';
|
||||
import { Dialog } from '../../ui/overlays';
|
||||
import { EditMetadataDialog } from './EditMetadata';
|
||||
import { FixMatchDialog } from './FixMatch';
|
||||
import { ArtworkDialog } from './Artwork';
|
||||
import { MediaInfoDialog } from './MediaInfo';
|
||||
import { CollectionDialog, PlaylistDialog } from './Lists';
|
||||
import { channelLabel, resolutionLabel } from '../../app/format';
|
||||
|
||||
export function DialogHost() {
|
||||
const dialog = useDialogs((s) => s.dialog);
|
||||
const close = useDialogs((s) => s.close);
|
||||
const server = useSession((s) => s.server);
|
||||
if (!dialog || !server) return null;
|
||||
switch (dialog.kind) {
|
||||
case 'edit':
|
||||
return <EditMetadataDialog item={dialog.item} onClose={close} />;
|
||||
case 'match':
|
||||
return <FixMatchDialog item={dialog.item} onClose={close} />;
|
||||
case 'artwork':
|
||||
return <ArtworkDialog item={dialog.item} type={dialog.type} onClose={close} />;
|
||||
case 'info':
|
||||
return <MediaInfoDialog item={dialog.item} onClose={close} />;
|
||||
case 'collection':
|
||||
return <CollectionDialog item={dialog.item} onClose={close} />;
|
||||
case 'playlist':
|
||||
return <PlaylistDialog item={dialog.item} onClose={close} />;
|
||||
case 'synopsis':
|
||||
return (
|
||||
<Dialog title={dialog.item.title} subtitle={[dialog.item.year, dialog.item.tagline].filter(Boolean).join(' · ')} onClose={close} width={620}>
|
||||
<p className="synopsis-full selectable">{dialog.item.summary}</p>
|
||||
</Dialog>
|
||||
);
|
||||
case 'versions':
|
||||
return (
|
||||
<Dialog title="Choose a version" subtitle={dialog.item.title} onClose={close} width={520}>
|
||||
<div className="version-list">
|
||||
{dialog.item.media.map((m, i) => (
|
||||
<button
|
||||
key={m.id}
|
||||
className="version-row"
|
||||
onClick={() => {
|
||||
close();
|
||||
dialog.onPick(i);
|
||||
}}
|
||||
>
|
||||
<b>{m.title || [resolutionLabel(m), m.dynamicRange].filter(Boolean).join(' ')}</b>
|
||||
<span>
|
||||
{[m.videoCodec.toUpperCase(), `${m.audioCodec.toUpperCase()} ${channelLabel(m.audioChannels)}`, m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : '', m.container.toUpperCase()].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
208
src/screens/dialogs/EditMetadata.tsx
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useItem } from '../../app/queries';
|
||||
import { openDialog } from '../../app/actions';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, PageLoader, Segmented } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
type Tab = 'general' | 'tags' | 'artwork';
|
||||
|
||||
const FIELDS: { key: string; label: string; types: string[]; multiline?: boolean; type?: string }[] = [
|
||||
{ key: 'title', label: 'Title', types: ['movie', 'show', 'season', 'episode', 'collection'] },
|
||||
{ key: 'titleSort', label: 'Sort title', types: ['movie', 'show', 'collection'] },
|
||||
{ key: 'originalTitle', label: 'Original title', types: ['movie', 'show'] },
|
||||
{ key: 'originallyAvailableAt', label: 'Release date', types: ['movie', 'show', 'episode'], type: 'date' },
|
||||
{ key: 'contentRating', label: 'Content rating', types: ['movie', 'show', 'collection'] },
|
||||
{ key: 'studio', label: 'Studio', types: ['movie', 'show'] },
|
||||
{ key: 'tagline', label: 'Tagline', types: ['movie', 'show'] },
|
||||
{ key: 'summary', label: 'Summary', types: ['movie', 'show', 'season', 'episode', 'collection'], multiline: true },
|
||||
];
|
||||
|
||||
const TAGS: { key: string; label: string; source: keyof Item; types: string[] }[] = [
|
||||
{ key: 'genre', label: 'Genres', source: 'genres', types: ['movie', 'show'] },
|
||||
{ key: 'collection', label: 'Collections', source: 'collections', types: ['movie', 'show'] },
|
||||
{ key: 'label', label: 'Labels', source: 'labels', types: ['movie', 'show', 'episode', 'season', 'collection'] },
|
||||
{ key: 'director', label: 'Directors', source: 'directors', types: ['movie', 'episode'] },
|
||||
{ key: 'writer', label: 'Writers', source: 'writers', types: ['movie', 'episode'] },
|
||||
{ key: 'country', label: 'Countries', source: 'countries', types: ['movie', 'show'] },
|
||||
];
|
||||
|
||||
function TagEditor({ label, values, onChange, locked, onLock }: { label: string; values: string[]; onChange: (v: string[]) => void; locked: boolean; onLock: () => void }) {
|
||||
const [draft, setDraft] = useState('');
|
||||
const add = () => {
|
||||
const v = draft.trim();
|
||||
if (v && !values.includes(v)) onChange([...values, v]);
|
||||
setDraft('');
|
||||
};
|
||||
return (
|
||||
<div className="field">
|
||||
<span>
|
||||
{label}
|
||||
<LockToggle locked={locked} onClick={onLock} />
|
||||
</span>
|
||||
<div className="tag-editor">
|
||||
{values.map((v) => (
|
||||
<span key={v} className="chip">
|
||||
{v}
|
||||
<button aria-label={`Remove ${v}`} onClick={() => onChange(values.filter((x) => x !== v))}>
|
||||
<Icon name="x" size={12} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
<input
|
||||
value={draft}
|
||||
placeholder="Add…"
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ',') {
|
||||
e.preventDefault();
|
||||
add();
|
||||
} else if (e.key === 'Backspace' && !draft && values.length) onChange(values.slice(0, -1));
|
||||
}}
|
||||
onBlur={add}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LockToggle({ locked, onClick }: { locked: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button type="button" className={`lock-toggle${locked ? ' on' : ''}`} onClick={onClick} title={locked ? 'Locked: refreshes keep this value' : 'Unlocked: refreshes may replace this value'}>
|
||||
<Icon name={locked ? 'lock' : 'unlock'} size={12} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function EditMetadataDialog({ item: initial, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const full = useItem(initial.id);
|
||||
const item = full.data ?? initial;
|
||||
const [tab, setTab] = useState<Tab>('general');
|
||||
const [values, setValues] = useState<Record<string, string> | null>(null);
|
||||
const [tags, setTags] = useState<Record<string, string[]> | null>(null);
|
||||
const [locks, setLocks] = useState<Record<string, boolean>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const fields = FIELDS.filter((f) => f.types.includes(item.type));
|
||||
const tagFields = TAGS.filter((t) => t.types.includes(item.type));
|
||||
const lockedFields: Record<string, boolean> = Object.fromEntries((item.raw?.Field ?? []).map((f: any) => [f.name, !!f.locked]));
|
||||
|
||||
if (full.data && !values) {
|
||||
setValues(Object.fromEntries(fields.map((f) => [f.key, String(item.raw?.[f.key] ?? '')])));
|
||||
setTags(Object.fromEntries(tagFields.map((t) => [t.key, ((item[t.source] as { tag: string }[]) ?? []).map((x) => x.tag)])));
|
||||
setLocks(lockedFields);
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
if (!values || !tags) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const changed: Record<string, string> = {};
|
||||
for (const f of fields) if ((values[f.key] ?? '') !== String(item.raw?.[f.key] ?? '')) changed[f.key] = values[f.key];
|
||||
const tagChanges: Record<string, { add: string[]; remove: string[] }> = {};
|
||||
for (const t of tagFields) {
|
||||
const before = ((item[t.source] as { tag: string }[]) ?? []).map((x) => x.tag);
|
||||
const after = tags[t.key];
|
||||
if (before.join('\u0000') !== after.join('\u0000')) tagChanges[t.key] = { add: after, remove: before.filter((b) => !after.includes(b)) };
|
||||
}
|
||||
const lockChanges: Record<string, boolean> = {};
|
||||
for (const [k, v] of Object.entries(locks)) if (!!lockedFields[k] !== v) lockChanges[k] = v;
|
||||
for (const k of [...Object.keys(changed), ...Object.keys(tagChanges)]) if (!(k in lockChanges)) lockChanges[k] = true;
|
||||
if (!Object.keys(changed).length && !Object.keys(tagChanges).length && !Object.keys(lockChanges).length) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
await api.editMetadata(server, item, changed, tagChanges, lockChanges);
|
||||
toast('Metadata saved', 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
title="Edit metadata"
|
||||
subtitle={`${item.title}${item.librarySectionTitle ? ` · ${item.librarySectionTitle}` : ''}`}
|
||||
onClose={onClose}
|
||||
width={760}
|
||||
className="edit-dialog"
|
||||
footer={
|
||||
<>
|
||||
<span className="dialog-note">
|
||||
<Icon name="lock" size={13} /> Edited fields are locked so metadata refreshes keep them.
|
||||
</span>
|
||||
<div className="actions">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" icon="check" busy={busy} onClick={save} disabled={!values}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Segmented
|
||||
value={tab}
|
||||
onChange={setTab}
|
||||
options={[
|
||||
{ value: 'general', label: 'General' },
|
||||
...(tagFields.length ? [{ value: 'tags' as Tab, label: 'Tags' }] : []),
|
||||
{ value: 'artwork', label: 'Artwork' },
|
||||
]}
|
||||
className="dialog-tabs"
|
||||
/>
|
||||
{!values || !tags ? (
|
||||
<PageLoader />
|
||||
) : tab === 'general' ? (
|
||||
<div className="field-grid">
|
||||
{fields.map((f) => (
|
||||
<label key={f.key} className="field" style={f.multiline || f.key === 'title' || f.key === 'tagline' ? { gridColumn: '1 / -1' } : undefined}>
|
||||
<span>
|
||||
{f.label}
|
||||
<LockToggle locked={!!locks[f.key]} onClick={() => setLocks((l) => ({ ...l, [f.key]: !l[f.key] }))} />
|
||||
</span>
|
||||
{f.multiline ? (
|
||||
<textarea value={values[f.key]} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} rows={6} />
|
||||
) : (
|
||||
<input type={f.type ?? 'text'} value={values[f.key]} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} />
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
) : tab === 'tags' ? (
|
||||
<div>
|
||||
{tagFields.map((t) => (
|
||||
<TagEditor key={t.key} label={t.label} values={tags[t.key]} onChange={(v) => setTags({ ...tags, [t.key]: v })} locked={!!locks[t.key]} onLock={() => setLocks((l) => ({ ...l, [t.key]: !l[t.key] }))} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="artwork-tab">
|
||||
{(
|
||||
[
|
||||
['poster', 'Poster', item.thumb, 'poster'],
|
||||
['art', 'Background', item.art, 'landscape'],
|
||||
['clearLogo', 'Logo', item.logo, 'logo'],
|
||||
] as const
|
||||
).map(([type, label, path, shape]) => (
|
||||
<button key={type} className={`artwork-choice ${shape}`} onClick={() => openDialog({ kind: 'artwork', item, type })}>
|
||||
<div className="artwork-choice-img">{path ? <img src={server.image(path, shape === 'poster' ? 200 : 360, shape === 'poster' ? 300 : 200, { format: shape === 'logo' ? 'png' : 'jpeg' })} alt="" /> : <Icon name="image" size={24} />}</div>
|
||||
<span>
|
||||
{label} <Icon name="next" size={13} />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
91
src/screens/dialogs/FixMatch.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useSections } from '../../app/queries';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, EmptyState, Spinner } from '../../ui/primitives';
|
||||
|
||||
export function FixMatchDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const sections = useSections();
|
||||
const section = sections.data?.find((s) => s.id === item.librarySectionId);
|
||||
const [title, setTitle] = useState(item.title);
|
||||
const [year, setYear] = useState(item.year ? String(item.year) : '');
|
||||
const [results, setResults] = useState<api.MatchCandidate[] | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [applying, setApplying] = useState('');
|
||||
|
||||
const search = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setResults(await api.matches(server, item.id, { title, year, agent: section?.agent, language: section?.language }));
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
search();
|
||||
}, [section?.agent]);
|
||||
|
||||
const apply = async (m: api.MatchCandidate) => {
|
||||
setApplying(m.guid);
|
||||
try {
|
||||
await api.applyMatch(server, item.id, m.guid, m.name, m.year);
|
||||
toast(`Matched to “${m.name}”. Plex is updating its metadata.`, 'success');
|
||||
setTimeout(() => {
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
}, 2500);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setApplying('');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog title="Fix match" subtitle={`Choose the correct ${item.type === 'show' ? 'series' : 'movie'} for ${item.raw?.Media?.[0]?.Part?.[0]?.file?.split(/[\\/]/).pop() ?? item.title}`} onClose={onClose} width={720}>
|
||||
<form
|
||||
className="match-search"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
search();
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />
|
||||
<input className="text-input year" value={year} onChange={(e) => setYear(e.target.value.replace(/\D/g, '').slice(0, 4))} placeholder="Year" />
|
||||
<Button variant="ghost" icon="search" busy={busy} type="submit">
|
||||
Search
|
||||
</Button>
|
||||
</form>
|
||||
<div className="match-results">
|
||||
{busy && !results && (
|
||||
<div className="center-pad">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
{results && !results.length && <EmptyState icon="search" title="No matches found">Try a different title or year.</EmptyState>}
|
||||
{results?.map((m) => (
|
||||
<button key={m.guid} className="match-row" onClick={() => apply(m)} disabled={!!applying}>
|
||||
<div className="match-thumb">{m.thumb && <img src={m.thumb.startsWith('http') ? m.thumb : server.image(m.thumb, 80, 120)} alt="" />}</div>
|
||||
<div className="match-text">
|
||||
<b>
|
||||
{m.name} {m.year ? <span className="dim">({m.year})</span> : null}
|
||||
</b>
|
||||
{m.summary && <p>{m.summary}</p>}
|
||||
<small>
|
||||
{m.matched ? 'Current match · ' : ''}
|
||||
{m.score}% confidence
|
||||
</small>
|
||||
</div>
|
||||
{applying === m.guid && <Spinner size={18} />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
101
src/screens/dialogs/Lists.tsx
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateLibrary, useServerQuery } from '../../app/queries';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, PageLoader } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
export function CollectionDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const collections = useServerQuery(['collections', item.librarySectionId], (s) => api.collections(s, item.librarySectionId), { enabled: !!item.librarySectionId });
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const current = new Set(item.collections.map((c) => c.tag));
|
||||
const add = async (title: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.addToCollection(server, item, title);
|
||||
toast(`Added to “${title}”`, 'success');
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog title="Add to collection" subtitle={item.title} onClose={onClose} width={480}>
|
||||
<form
|
||||
className="inline-create"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) add(name.trim());
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="New collection name" />
|
||||
<Button variant="ghost" icon="plus" type="submit" disabled={!name.trim() || busy}>
|
||||
Create
|
||||
</Button>
|
||||
</form>
|
||||
{collections.isLoading && <PageLoader />}
|
||||
<div className="list-pick">
|
||||
{collections.data?.map((c) => (
|
||||
<button key={c.id} className="list-pick-row" disabled={busy || current.has(c.title)} onClick={() => add(c.title)}>
|
||||
<Icon name="collection" size={17} />
|
||||
<span>{c.title}</span>
|
||||
{current.has(c.title) && <Icon name="check" size={15} className="dim" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlaylistDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const playlists = useServerQuery(['playlists'], (s) => api.playlists(s));
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const run = async (fn: () => Promise<unknown>, done: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog title="Add to playlist" subtitle={item.title} onClose={onClose} width={480}>
|
||||
<form
|
||||
className="inline-create"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) run(() => api.createPlaylist(server, name.trim(), server.machineId, item.id), `Created “${name.trim()}”`);
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="New playlist name" />
|
||||
<Button variant="ghost" icon="plus" type="submit" disabled={!name.trim() || busy}>
|
||||
Create
|
||||
</Button>
|
||||
</form>
|
||||
{playlists.isLoading && <PageLoader />}
|
||||
<div className="list-pick">
|
||||
{playlists.data?.map((p) => (
|
||||
<button key={p.id} className="list-pick-row" disabled={busy} onClick={() => run(() => api.addToPlaylist(server, p.id, server.machineId, item.id), `Added to “${p.title}”`)}>
|
||||
<Icon name="queue" size={17} />
|
||||
<span>{p.title}</span>
|
||||
<small className="dim">{p.leafCount ? `${p.leafCount} items` : ''}</small>
|
||||
</button>
|
||||
))}
|
||||
{playlists.data && !playlists.data.length && <p className="muted">No video playlists yet. Create one above.</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
109
src/screens/dialogs/MediaInfo.tsx
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import type { Item, Stream } from '../../plex/types';
|
||||
import { useItem } from '../../app/queries';
|
||||
import { bitrate, channelLabel, date, duration, fileSize, resolutionLabel } from '../../app/format';
|
||||
import { Dialog } from '../../ui/overlays';
|
||||
import { PageLoader } from '../../ui/primitives';
|
||||
|
||||
function streamLine(s: Stream): string {
|
||||
if (s.streamType === 1)
|
||||
return [s.codec.toUpperCase(), s.profile, s.width && s.height ? `${s.width}×${s.height}` : '', s.frameRate ? `${s.frameRate} fps` : '', s.bitDepth ? `${s.bitDepth}-bit` : '', s.doviPresent ? 'Dolby Vision' : s.colorTrc === 'smpte2084' ? 'HDR10' : '', bitrate(s.bitrate)]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
if (s.streamType === 2) return [s.extendedDisplayTitle || s.displayTitle, s.samplingRate ? `${(s.samplingRate / 1000).toFixed(1)} kHz` : '', bitrate(s.bitrate)].filter(Boolean).join(' · ');
|
||||
return [s.extendedDisplayTitle || s.displayTitle, s.key ? 'External file' : 'Embedded'].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
export function MediaInfoDialog({ item: initial, onClose }: { item: Item; onClose: () => void }) {
|
||||
const q = useItem(initial.id);
|
||||
const item = q.data ?? initial;
|
||||
return (
|
||||
<Dialog title="Media info" subtitle={item.type === 'episode' ? `${item.grandparentTitle} · ${item.title}` : item.title} onClose={onClose} width={760}>
|
||||
{q.isLoading && <PageLoader />}
|
||||
<div className="media-info selectable">
|
||||
{item.media.map((m, mi) => (
|
||||
<section key={m.id} className="media-version">
|
||||
<h3>
|
||||
{item.media.length > 1 ? `Version ${mi + 1} · ` : ''}
|
||||
{[resolutionLabel(m), m.dynamicRange, m.container.toUpperCase()].filter(Boolean).join(' · ')}
|
||||
</h3>
|
||||
<div className="info-grid">
|
||||
<div>
|
||||
<span>Duration</span>
|
||||
<b>{duration(m.duration || item.duration)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Bitrate</span>
|
||||
<b>{bitrate(m.bitrate) || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Video</span>
|
||||
<b>{[m.videoCodec.toUpperCase(), m.videoProfile, m.videoFrameRate].filter(Boolean).join(' · ')}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Audio</span>
|
||||
<b>{[m.audioCodec.toUpperCase(), channelLabel(m.audioChannels)].filter(Boolean).join(' · ')}</b>
|
||||
</div>
|
||||
</div>
|
||||
{m.parts.map((p) => (
|
||||
<div key={p.id} className="media-part">
|
||||
<div className="media-file">
|
||||
<span>File</span>
|
||||
<code>{p.file || p.key}</code>
|
||||
</div>
|
||||
<div className="info-grid">
|
||||
<div>
|
||||
<span>Size</span>
|
||||
<b>{fileSize(p.size) || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Availability</span>
|
||||
<b>{p.exists === false ? 'Missing' : p.accessible === false ? 'Not accessible' : 'Available'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Previews</span>
|
||||
<b>{p.indexes.includes('sd') ? 'Generated' : 'Not generated'}</b>
|
||||
</div>
|
||||
</div>
|
||||
<table className="stream-table">
|
||||
<tbody>
|
||||
{p.streams.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td>{s.streamType === 1 ? 'Video' : s.streamType === 2 ? 'Audio' : s.streamType === 3 ? 'Subtitle' : 'Other'}</td>
|
||||
<td>{streamLine(s)}</td>
|
||||
<td>{s.selected ? 'Selected' : s.default ? 'Default' : ''}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
<div className="info-grid footer">
|
||||
<div>
|
||||
<span>Library</span>
|
||||
<b>{item.librarySectionTitle || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Added</span>
|
||||
<b>{date(item.addedAt)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Updated</span>
|
||||
<b>{date(item.updatedAt)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Plex ID</span>
|
||||
<b>{item.id}</b>
|
||||
</div>
|
||||
{item.guids.length > 0 && (
|
||||
<div style={{ gridColumn: '1 / -1' }}>
|
||||
<span>External IDs</span>
|
||||
<b>{item.guids.join(' · ')}</b>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
81
src/screens/discover.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import * as api from '../plex/api';
|
||||
import type { Hub, Item } from '../plex/types';
|
||||
import type { Feature } from '../ui/Hero';
|
||||
import type { PlexServer } from '../plex/client';
|
||||
|
||||
/** One shuffle per app session keeps features stable while browsing. */
|
||||
const seed = Math.floor(Math.random() * 1e9);
|
||||
function shuffled<T>(list: T[], salt = 0): T[] {
|
||||
const out = [...list];
|
||||
let s = (seed + salt) % 2147483647 || 1;
|
||||
for (let i = out.length - 1; i > 0; i--) {
|
||||
s = (s * 48271) % 2147483647;
|
||||
const j = s % (i + 1);
|
||||
[out[i], out[j]] = [out[j], out[i]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const FEATURE_SOURCES: [RegExp, string][] = [
|
||||
[/recentlyreleased|recentlyaired/, 'Recently released'],
|
||||
[/topunwatched|toprated/, 'Highly rated'],
|
||||
[/recentlyadded/, 'Recently added'],
|
||||
[/startwatching/, 'Start watching'],
|
||||
[/curated|genre|by\.actor|moreingenre/, 'Recommended'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Features interleave recently released, highly rated unwatched and
|
||||
* Plex-recommended titles; they need artwork and skip in-progress titles.
|
||||
*/
|
||||
export function buildFeatures(hubs: Hub[], limit = 8, salt = 0): Feature[] {
|
||||
const pools: Feature[][] = FEATURE_SOURCES.map(([re, eyebrow]) =>
|
||||
shuffled(
|
||||
hubs
|
||||
.filter((h) => re.test(h.id))
|
||||
.flatMap((h) => h.items)
|
||||
.filter((i) => (i.type === 'movie' || i.type === 'show') && i.art && !i.viewOffset && i.summary)
|
||||
.map((item) => ({ item, eyebrow })),
|
||||
salt,
|
||||
),
|
||||
);
|
||||
const out: Feature[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (let round = 0; out.length < limit && round < 20; round++) {
|
||||
for (const pool of pools) {
|
||||
const f = pool[round];
|
||||
if (f && !seen.has(f.item.id) && out.length < limit) {
|
||||
seen.add(f.item.id);
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* New seasons, one card per show. Samples many seasons so a single series
|
||||
* import cannot fill the row.
|
||||
*/
|
||||
export async function recentSeasons(s: PlexServer, sectionId: string): Promise<Item[]> {
|
||||
const page = await api.libraryPage(s, sectionId, { type: 3, sort: 'addedAt:desc', start: 0, size: 100 });
|
||||
const byShow = new Map<string, Item[]>();
|
||||
for (const season of page.items) {
|
||||
if (!season.parentId) continue;
|
||||
const list = byShow.get(season.parentId) ?? [];
|
||||
list.push(season);
|
||||
byShow.set(season.parentId, list);
|
||||
}
|
||||
const out: Item[] = [];
|
||||
for (const [, seasons] of byShow) {
|
||||
if (out.length >= 18) break;
|
||||
// Several new seasons: show the series; one: the season itself.
|
||||
if (seasons.length > 1) {
|
||||
const first = seasons[0];
|
||||
out.push({ ...first, id: first.parentId, type: 'show', title: first.parentTitle, thumb: first.parentThumb || first.thumb, key: `/library/metadata/${first.parentId}/children` });
|
||||
} else out.push(seasons[0]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const HIDDEN_HUBS = /continue|ondeck|inprogress|playlists|music|photos|videos\.recent/;
|
||||
331
src/screens/settings/AppSettings.tsx
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSettings, QUALITY_LABEL, type Quality, type SkipMode, type SubtitleMode } from '../../app/settings';
|
||||
import { useSession } from '../../app/session';
|
||||
import { useSections } from '../../app/queries';
|
||||
import { useDownloads } from '../../downloads/store';
|
||||
import { appInfo, isNative, openExternal, pickFolder, revealPath, type AppInfo } from '../../platform/native';
|
||||
import { checkForUpdate, installUpdate, useUpdater } from '../../app/updater';
|
||||
import { Button, Select, Switch } from '../../ui/primitives';
|
||||
import { confirmDialog } from '../../ui/overlays';
|
||||
import { Pref, SettingsSection } from './parts';
|
||||
import { KaleidoMark } from '../../ui/primitives';
|
||||
|
||||
const LANGUAGES: [string, string][] = [
|
||||
['', 'Automatic'],
|
||||
['eng', 'English'],
|
||||
['spa', 'Spanish'],
|
||||
['fre', 'French'],
|
||||
['ger', 'German'],
|
||||
['ita', 'Italian'],
|
||||
['por', 'Portuguese'],
|
||||
['jpn', 'Japanese'],
|
||||
['kor', 'Korean'],
|
||||
['chi', 'Chinese'],
|
||||
['rus', 'Russian'],
|
||||
['hin', 'Hindi'],
|
||||
['ara', 'Arabic'],
|
||||
['dut', 'Dutch'],
|
||||
['swe', 'Swedish'],
|
||||
['nor', 'Norwegian'],
|
||||
['dan', 'Danish'],
|
||||
['fin', 'Finnish'],
|
||||
['pol', 'Polish'],
|
||||
['tur', 'Turkish'],
|
||||
];
|
||||
|
||||
const qualityOptions = (Object.keys(QUALITY_LABEL) as Quality[]).map((q) => ({ value: q, label: QUALITY_LABEL[q] }));
|
||||
const skipOptions: { value: SkipMode; label: string }[] = [
|
||||
{ value: 'button', label: 'Show a button' },
|
||||
{ value: 'auto', label: 'Skip automatically' },
|
||||
{ value: 'off', label: 'Off' },
|
||||
];
|
||||
|
||||
const SHORTCUTS: [string, string][][] = [
|
||||
[
|
||||
['Ctrl + K', 'Search'],
|
||||
['Alt + ← / Mouse back', 'Go back'],
|
||||
['Alt + → / Mouse forward', 'Go forward'],
|
||||
['Esc', 'Go back or close a dialog'],
|
||||
['F11', 'Full screen'],
|
||||
['Ctrl + ,', 'Settings'],
|
||||
['Right-click a title', 'Title actions'],
|
||||
],
|
||||
[
|
||||
['Space or K', 'Play / pause'],
|
||||
['← / →', 'Seek back / forward'],
|
||||
['Shift + ← / →', 'Seek one minute'],
|
||||
['J / L', 'Seek 10 seconds'],
|
||||
['↑ / ↓ or scroll', 'Volume'],
|
||||
['M', 'Mute'],
|
||||
['F or double-click', 'Full screen'],
|
||||
['C', 'Next subtitle track'],
|
||||
['Shift + N', 'Next episode'],
|
||||
['0–9', 'Jump to 0–90%'],
|
||||
['Esc', 'Exit full screen, then the player'],
|
||||
],
|
||||
];
|
||||
|
||||
export function AppSettings({ tab }: { tab: string }) {
|
||||
const s = useSettings();
|
||||
const set = s.set;
|
||||
const session = useSession();
|
||||
const sections = useSections();
|
||||
const downloads = useDownloads();
|
||||
const [info, setInfo] = useState<AppInfo | null>(null);
|
||||
const updater = useUpdater();
|
||||
useEffect(() => {
|
||||
appInfo().then(setInfo);
|
||||
}, []);
|
||||
const movieLibs = (sections.data ?? []).filter((x) => x.type === 'movie');
|
||||
const showLibs = (sections.data ?? []).filter((x) => x.type === 'show');
|
||||
|
||||
switch (tab) {
|
||||
case 'general':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Account" description="Your Plex account and the server Kaleido is browsing.">
|
||||
<Pref label={session.user?.title ?? 'Signed in with a server token'} description={session.user?.email || 'Manual connection'}>
|
||||
<Button variant="ghost" size="sm" icon="logout" onClick={() => confirmDialog({ title: 'Sign out of Plex?', message: 'Downloads stay on this computer. You can sign in again at any time.', confirm: 'Sign out' }).then((ok) => void (ok && session.signOut()))}>
|
||||
Sign out
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref
|
||||
label="Server"
|
||||
description={
|
||||
session.server
|
||||
? `${session.server.name} · ${session.connection?.relay ? 'Plex Relay' : session.connection?.local ? 'Local network' : 'Remote'} · ${session.server.uri.replace(/X-Plex-Token=[^&]+/, '')}`
|
||||
: ''
|
||||
}
|
||||
>
|
||||
<Button variant="ghost" size="sm" icon="swap" onClick={session.showServerPicker} disabled={!session.accountToken}>
|
||||
Change
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Browsing">
|
||||
<Pref label="Start on" description="The page Kaleido opens to.">
|
||||
<Select
|
||||
value={s.startPage}
|
||||
onChange={(v) => set('startPage', v)}
|
||||
options={[
|
||||
{ value: 'home', label: 'Home' },
|
||||
{ value: 'movies', label: 'Movies' },
|
||||
{ value: 'shows', label: 'TV Shows' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
{movieLibs.length > 1 && (
|
||||
<Pref label="Movies library" description="The library shown in Movies.">
|
||||
<Select value={s.movieSection || movieLibs[0].id} onChange={(v) => set('movieSection', v)} options={movieLibs.map((l) => ({ value: l.id, label: l.title }))} />
|
||||
</Pref>
|
||||
)}
|
||||
{showLibs.length > 1 && (
|
||||
<Pref label="TV Shows library" description="The library shown in TV Shows.">
|
||||
<Select value={s.showSection || showLibs[0].id} onChange={(v) => set('showSection', v)} options={showLibs.map((l) => ({ value: l.id, label: l.title }))} />
|
||||
</Pref>
|
||||
)}
|
||||
<Pref label="Mark as watched at" description="How far into a title playback counts as watched. This belongs to Kaleido and doesn’t change your server.">
|
||||
<Select value={s.watchedPercent} onChange={(v) => set('watchedPercent', v)} options={[70, 75, 80, 85, 90, 95].map((v) => ({ value: v, label: `${v}%` }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'playback':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Quality" description="Original quality plays the source file directly; Kaleido decodes nearly every format, so Plex rarely needs to convert.">
|
||||
<Pref label="On your local network">
|
||||
<Select value={s.quality} onChange={(v) => set('quality', v)} options={qualityOptions} />
|
||||
</Pref>
|
||||
<Pref label="Away from home" description="Used when the server is reached remotely or through Plex Relay.">
|
||||
<Select value={s.remoteQuality} onChange={(v) => set('remoteQuality', v)} options={qualityOptions} />
|
||||
</Pref>
|
||||
<Pref label="Hardware decoding" description="Uses your graphics card to decode video. Turn off only if you see artifacts. Applies after restarting Kaleido.">
|
||||
<Switch checked={s.hwdec} onChange={(v) => set('hwdec', v)} />
|
||||
</Pref>
|
||||
<Pref label="HDR passthrough" description="Sends HDR video to HDR-capable displays when Windows HDR is on. Applies after restarting Kaleido.">
|
||||
<Switch checked={s.hdrPassthrough} onChange={(v) => set('hdrPassthrough', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Episodes and markers" description="Intro and credits markers come from your Plex server’s analysis.">
|
||||
<Pref label="Skip intros">
|
||||
<Select value={s.skipIntro} onChange={(v) => set('skipIntro', v)} options={skipOptions} />
|
||||
</Pref>
|
||||
<Pref label="Skip credits">
|
||||
<Select value={s.skipCredits} onChange={(v) => set('skipCredits', v)} options={skipOptions} />
|
||||
</Pref>
|
||||
<Pref label="Play the next episode automatically">
|
||||
<Switch checked={s.autoplayNext} onChange={(v) => set('autoplayNext', v)} />
|
||||
</Pref>
|
||||
<Pref label="Countdown" description="Seconds before the next episode starts.">
|
||||
<Select value={s.countdownSeconds} disabled={!s.autoplayNext} onChange={(v) => set('countdownSeconds', v)} options={[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||
</Pref>
|
||||
<Pref label="Arrow-key seek">
|
||||
<Select value={s.seekStep} onChange={(v) => set('seekStep', v)} options={[5, 10, 15, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'subtitles':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Audio">
|
||||
<Pref label="Preferred audio language" description="Automatic follows the track Plex selects for each title.">
|
||||
<Select value={s.audioLanguage} onChange={(v) => set('audioLanguage', v)} options={LANGUAGES.map(([value, label]) => ({ value, label }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Subtitles">
|
||||
<Pref label="Show subtitles">
|
||||
<Select<SubtitleMode>
|
||||
value={s.subtitleMode}
|
||||
onChange={(v) => set('subtitleMode', v)}
|
||||
options={[
|
||||
{ value: 'auto', label: 'As chosen in Plex' },
|
||||
{ value: 'forced', label: 'Forced subtitles only' },
|
||||
{ value: 'always', label: 'Always' },
|
||||
{ value: 'off', label: 'Never' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Subtitle language" description="Automatic uses the language of the audio track.">
|
||||
<Select value={s.subtitleLanguage} onChange={(v) => set('subtitleLanguage', v)} options={LANGUAGES.map(([value, label]) => ({ value, label }))} />
|
||||
</Pref>
|
||||
<Pref label="Size">
|
||||
<Select
|
||||
value={s.subtitleScale}
|
||||
onChange={(v) => set('subtitleScale', v)}
|
||||
options={[
|
||||
{ value: 0.8, label: 'Small' },
|
||||
{ value: 1, label: 'Normal' },
|
||||
{ value: 1.25, label: 'Large' },
|
||||
{ value: 1.5, label: 'Extra large' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Background box" description="Draws text subtitles on a dark box for contrast.">
|
||||
<Switch checked={s.subtitleBackground} onChange={(v) => set('subtitleBackground', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'interface':
|
||||
return (
|
||||
<SettingsSection title="Interface" description="Kaleido keeps the same artwork-led look as its TV app.">
|
||||
<Pref label="Artwork colour wash" description="Tints pages with colors from the title’s artwork.">
|
||||
<Switch checked={s.colorWash} onChange={(v) => set('colorWash', v)} />
|
||||
</Pref>
|
||||
<Pref label="Rotate featured titles" description="Cycles the featured title on Home and Discover every 12 seconds.">
|
||||
<Switch checked={s.heroRotation} onChange={(v) => set('heroRotation', v)} />
|
||||
</Pref>
|
||||
<Pref label="Poster size" description="Card size in library grids.">
|
||||
<Select
|
||||
value={s.posterSize}
|
||||
onChange={(v) => set('posterSize', v)}
|
||||
options={[
|
||||
{ value: 'compact', label: 'Compact' },
|
||||
{ value: 'comfortable', label: 'Comfortable' },
|
||||
{ value: 'large', label: 'Large' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Theme music" description="Plays a show or movie’s theme on its page.">
|
||||
<Switch checked={s.themeMusic} onChange={(v) => set('themeMusic', v)} />
|
||||
</Pref>
|
||||
<Pref label="Theme music volume">
|
||||
<Select value={s.themeVolume} disabled={!s.themeMusic} onChange={(v) => set('themeVolume', v)} options={[15, 30, 50, 75, 100].map((v) => ({ value: v, label: `${v}%` }))} />
|
||||
</Pref>
|
||||
<Pref label="Reduce motion" description="Turns off transitions and animations.">
|
||||
<Switch checked={s.reducedMotion} onChange={(v) => set('reducedMotion', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
);
|
||||
case 'downloads':
|
||||
return (
|
||||
<SettingsSection title="Offline media" description="Downloads keep the original file, so they play exactly as on your server.">
|
||||
<Pref label="Download folder" description={downloads.dir || info?.defaultDownloadDir || 'Not set'}>
|
||||
<Button variant="ghost" size="sm" icon="folder" disabled={!isNative} onClick={async () => {
|
||||
const dir = await pickFolder(downloads.dir);
|
||||
if (dir) await downloads.setDir(dir);
|
||||
}}>
|
||||
Change
|
||||
</Button>
|
||||
{downloads.dir && (
|
||||
<Button variant="ghost" size="sm" onClick={() => revealPath(downloads.dir)}>
|
||||
Open
|
||||
</Button>
|
||||
)}
|
||||
</Pref>
|
||||
<Pref label="Resume interrupted downloads" description="Downloads in progress when Kaleido closed continue automatically when it reconnects.">
|
||||
<span className="muted">Always</span>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
);
|
||||
case 'shortcuts':
|
||||
return (
|
||||
<div className="shortcut-columns">
|
||||
{SHORTCUTS.map((group, i) => (
|
||||
<SettingsSection key={i} title={i === 0 ? 'Browsing' : 'Player'}>
|
||||
{group.map(([k, label]) => (
|
||||
<Pref key={label} label={label}>
|
||||
<span className="kbd">{k}</span>
|
||||
</Pref>
|
||||
))}
|
||||
</SettingsSection>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
case 'about':
|
||||
return (
|
||||
<>
|
||||
<div className="about-app">
|
||||
<KaleidoMark size={56} />
|
||||
<div>
|
||||
<h2>Kaleido</h2>
|
||||
<p className="muted">
|
||||
Version {info?.version ?? '—'} · {info?.platform === 'windows' ? 'Windows' : info?.platform}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<SettingsSection title="Updates" description="Kaleido checks for new versions when it starts and installs them with your permission.">
|
||||
<Pref
|
||||
label={updater.available ? `Kaleido ${updater.available.version} is available` : updater.checking ? 'Checking…' : 'You’re up to date'}
|
||||
description={updater.error || (updater.available?.notes ? updater.available.notes : updater.checkedAt ? `Last checked ${new Date(updater.checkedAt).toLocaleTimeString()}` : '')}
|
||||
>
|
||||
{updater.available ? (
|
||||
<Button variant="primary" size="sm" icon="download" busy={updater.installing} onClick={installUpdate}>
|
||||
{updater.installing ? `Installing ${Math.round(updater.progress * 100)}%` : 'Install and restart'}
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="ghost" size="sm" icon="refresh" busy={updater.checking} disabled={!isNative} onClick={() => checkForUpdate(true)}>
|
||||
Check now
|
||||
</Button>
|
||||
)}
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Information">
|
||||
<Pref label="Plex client identifier" description={localStorage.getItem('kaleido.clientId') ?? ''} />
|
||||
{info?.dataDir && (
|
||||
<Pref label="App data" description={info.dataDir}>
|
||||
<Button variant="ghost" size="sm" onClick={() => revealPath(info.dataDir)}>
|
||||
Open
|
||||
</Button>
|
||||
</Pref>
|
||||
)}
|
||||
<Pref label="Source code" description="git.elijahkuntz.com/Elijah/Kaleido-Desktop">
|
||||
<Button variant="ghost" size="sm" icon="external" onClick={() => openExternal('https://git.elijahkuntz.com/Elijah/Kaleido-Desktop')}>
|
||||
Open
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Reset preferences" description="Restores Kaleido’s settings. Your sign-in and downloads are kept.">
|
||||
<Button variant="ghost" size="sm" onClick={() => confirmDialog({ title: 'Reset preferences?', message: 'Playback, subtitle and interface settings return to their defaults.', confirm: 'Reset' }).then((ok) => ok && s.reset())}>
|
||||
Reset
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<p className="legal">Kaleido is an independent project and is not affiliated with Plex. Video playback uses mpv (libmpv), licensed under the LGPL.</p>
|
||||
</>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
255
src/screens/settings/ServerDashboard.tsx
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
import { useMemo } from 'react';
|
||||
import * as admin from '../../plex/admin';
|
||||
import * as api from '../../plex/api';
|
||||
import { useServerQuery } from '../../app/queries';
|
||||
import { useServer } from '../../app/session';
|
||||
import { bitrate, clock, episodeLabel, relativeTime } from '../../app/format';
|
||||
import { Artwork, Button, EmptyState, PageLoader } from '../../ui/primitives';
|
||||
import { promptDialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { Card, StatTile } from './parts';
|
||||
|
||||
function AreaChart({ series, height = 150, max, format }: { series: { values: number[]; color: string; label: string }[]; height?: number; max?: number; format: (v: number) => string }) {
|
||||
const n = Math.max(...series.map((s) => s.values.length), 2);
|
||||
const top = Math.max(max ?? 0, ...series.flatMap((s) => s.values), 1);
|
||||
const W = 920;
|
||||
const path = (values: number[]) => values.map((v, i) => `${i === 0 ? 'M' : 'L'}${((i / (n - 1)) * W).toFixed(1)} ${(height - 6 - (v / top) * (height - 16)).toFixed(1)}`).join(' ');
|
||||
return (
|
||||
<div className="chart">
|
||||
<svg viewBox={`0 0 ${W} ${height}`} preserveAspectRatio="none" className="chart-svg" role="img">
|
||||
<defs>
|
||||
{series.map((s, i) => (
|
||||
<linearGradient key={i} id={`g${i}${s.label}`} x1="0" x2="0" y1="0" y2="1">
|
||||
<stop stopColor={s.color} stopOpacity=".28" />
|
||||
<stop offset="1" stopColor={s.color} stopOpacity="0" />
|
||||
</linearGradient>
|
||||
))}
|
||||
</defs>
|
||||
{[0.25, 0.5, 0.75, 1].map((f) => (
|
||||
<path key={f} d={`M0 ${(height - 6 - f * (height - 16)).toFixed(1)} H${W}`} stroke="rgba(255,255,255,.08)" strokeWidth="1" vectorEffect="non-scaling-stroke" />
|
||||
))}
|
||||
{series.map((s, i) =>
|
||||
s.values.length > 1 ? (
|
||||
<g key={i}>
|
||||
<path d={`${path(s.values)} L${(((s.values.length - 1) / (n - 1)) * W).toFixed(1)} ${height} L0 ${height} Z`} fill={`url(#g${i}${s.label})`} />
|
||||
<path d={path(s.values)} stroke={s.color} strokeWidth="2" fill="none" vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
|
||||
</g>
|
||||
) : null,
|
||||
)}
|
||||
</svg>
|
||||
<div className="chart-footer">
|
||||
<div className="legend">
|
||||
{series.map((s) => (
|
||||
<span key={s.label}>
|
||||
<i style={{ background: s.color }} />
|
||||
{s.label} {s.values.length ? format(s.values[s.values.length - 1]) : ''}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<span>Peak {format(top)}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NowPlaying({ session, onStop }: { session: admin.Session; onStop: () => void }) {
|
||||
const server = useServer();
|
||||
const item = session.item;
|
||||
const poster = item.type === 'episode' ? item.grandparentThumb : item.thumb;
|
||||
const pct = item.duration ? (session.viewOffset / item.duration) * 100 : 0;
|
||||
const d = session.decision;
|
||||
const mode = !d ? 'Direct play' : d.video === 'transcode' ? 'Transcoding video' : d.audio === 'transcode' ? 'Transcoding audio' : 'Direct stream';
|
||||
return (
|
||||
<div className="now-playing">
|
||||
<div className="np-poster">
|
||||
<Artwork src={server.image(poster, 90, 135)} />
|
||||
</div>
|
||||
<div className="np-body">
|
||||
<h3>{item.type === 'episode' ? item.grandparentTitle : item.title}</h3>
|
||||
<p>{item.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : item.year || ''}</p>
|
||||
<p className="dim">
|
||||
{session.user.title} · {session.player.title || session.player.product} ({session.player.platform}) · {session.player.local ? 'Local' : 'Remote'} {session.player.address}
|
||||
</p>
|
||||
<div className="np-progress">
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
<span className="dim">
|
||||
{session.player.state === 'paused' ? 'Paused · ' : session.player.state === 'buffering' ? 'Buffering · ' : ''}
|
||||
{clock(session.viewOffset / 1000)} / {clock(item.duration / 1000)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="np-pills">
|
||||
<span className={`stream-pill${d?.video === 'transcode' ? ' warn' : ''}`}>
|
||||
<Icon name={d ? 'cpu' : 'check'} size={13} />
|
||||
{mode}
|
||||
{d?.transcodeHw ? ' (hw)' : ''}
|
||||
</span>
|
||||
{session.bandwidth > 0 && <span className="stream-pill neutral">{bitrate(session.bandwidth)}</span>}
|
||||
{d && d.speed > 0 && <span className="stream-pill neutral">{d.speed.toFixed(1)}× {d.throttled ? 'throttled' : ''}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" icon="x" onClick={onStop}>
|
||||
Stop
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Dashboard() {
|
||||
const server = useServer();
|
||||
const sessions = useServerQuery(['sessions'], (s) => admin.sessions(s), { refetchInterval: 5000, staleTime: 0 });
|
||||
const bw = useServerQuery(['bandwidth'], (s) => admin.bandwidth(s, 6), { refetchInterval: 6000, staleTime: 0 });
|
||||
const res = useServerQuery(['resources'], (s) => admin.resources(s, 6), { refetchInterval: 6000, staleTime: 0 });
|
||||
const info = useServerQuery(['serverInfo'], (s) => api.serverInfo(s), { staleTime: 60_000 });
|
||||
const sections = useServerQuery(['sections'], (s) => api.sections(s));
|
||||
const remote = useServerQuery(['remoteAccess'], (s) => admin.remoteAccess(s), { staleTime: 60_000 });
|
||||
|
||||
const list = sessions.data ?? [];
|
||||
const transcodes = list.filter((s) => s.decision?.video === 'transcode').length;
|
||||
const points = (bw.data?.points ?? []).slice(-40);
|
||||
const toMbps = (bytes: number) => (bytes * 8) / 6 / 1e6;
|
||||
const lan = points.map((p) => toMbps(p.lan));
|
||||
const wan = points.map((p) => toMbps(p.wan));
|
||||
const r = (res.data ?? []).slice(-40);
|
||||
const cpu = r[r.length - 1];
|
||||
const totalBandwidth = list.reduce((a, s) => a + s.bandwidth, 0);
|
||||
|
||||
const stop = async (s: admin.Session) => {
|
||||
const reason = await promptDialog({
|
||||
title: 'Stop this stream?',
|
||||
message: `${s.user.title} will see this message on ${s.player.title || s.player.product}.`,
|
||||
confirm: 'Stop stream',
|
||||
danger: true,
|
||||
input: { label: 'Message', value: 'The server owner has ended this stream.' },
|
||||
});
|
||||
if (reason === null) return;
|
||||
try {
|
||||
await admin.terminateSession(server, s.sessionId, reason);
|
||||
toast('Stream stopped', 'success');
|
||||
sessions.refetch();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
};
|
||||
|
||||
const mc = info.data ?? {};
|
||||
return (
|
||||
<>
|
||||
<div className="stats-grid">
|
||||
<StatTile label="Active streams" value={list.length} detail={list.length ? `${list.length - transcodes} direct · ${transcodes} transcoding` : 'Nothing playing'} />
|
||||
<StatTile label="Streaming bandwidth" value={totalBandwidth ? bitrate(totalBandwidth) : '0 Mbps'} detail={`${list.filter((s) => !s.player.local).length} remote`} />
|
||||
<StatTile label="Server CPU" value={cpu ? `${Math.round(cpu.hostCpu)}%` : '—'} detail={cpu ? `Plex ${cpu.processCpu.toFixed(1)}%` : ''} tone={cpu && cpu.hostCpu > 85 ? 'warn' : undefined} />
|
||||
<StatTile label="Remote access" value={remote.data?.mappingState === 'mapped' ? 'Online' : 'Limited'} detail={remote.data?.publicAddress ?? ''} tone={remote.data?.mappingState === 'mapped' ? 'good' : 'warn'} />
|
||||
</div>
|
||||
<Card title="Now playing" actions={<span className="status-tag"><i className="dot" />{list.length} active</span>}>
|
||||
{sessions.isLoading && <PageLoader />}
|
||||
{sessions.data && !list.length && <p className="muted np-empty">No one is watching right now.</p>}
|
||||
{list.map((s) => (
|
||||
<NowPlaying key={s.sessionKey} session={s} onStop={() => stop(s)} />
|
||||
))}
|
||||
</Card>
|
||||
<div className="admin-2-col">
|
||||
<Card title="Bandwidth" actions={<span className="note">Last few minutes · live</span>}>
|
||||
<AreaChart
|
||||
series={[
|
||||
{ values: wan, color: '#6797f5', label: 'Remote' },
|
||||
{ values: lan, color: '#e0ad5d', label: 'Local' },
|
||||
]}
|
||||
format={(v) => `${v.toFixed(1)} Mbps`}
|
||||
/>
|
||||
</Card>
|
||||
<Card title="Resources" actions={<span className="note">Host CPU and memory</span>}>
|
||||
<AreaChart
|
||||
series={[
|
||||
{ values: r.map((p) => p.hostCpu), color: '#8fc7a8', label: 'CPU' },
|
||||
{ values: r.map((p) => p.hostMemory), color: '#b49ae8', label: 'Memory' },
|
||||
]}
|
||||
max={100}
|
||||
format={(v) => `${Math.round(v)}%`}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
<Card title="Server">
|
||||
<div className="server-info">
|
||||
{[
|
||||
['Name', mc.friendlyName],
|
||||
['Version', String(mc.version ?? '').split('-')[0]],
|
||||
['Platform', [mc.platform, mc.platformVersion].filter(Boolean).join(' ')],
|
||||
['Libraries', (sections.data ?? []).map((s) => s.title).join(', ')],
|
||||
['Plex Pass', mc.myPlexSubscription ? 'Active' : 'Not active'],
|
||||
['Signed in as', mc.myPlexUsername],
|
||||
['Transcoder', mc.transcoderVideo ? 'Video, audio' : 'Available'],
|
||||
['Connection', server.uri.replace(/^https?:\/\//, '')],
|
||||
].map(([k, v]) => (
|
||||
<div key={k as string}>
|
||||
<span>{k}</span>
|
||||
<b>{(v as string) || '—'}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Activity() {
|
||||
const server = useServer();
|
||||
const activities = useServerQuery(['activities'], (s) => admin.activities(s), { refetchInterval: 3000, staleTime: 0 });
|
||||
const history = useServerQuery(['history'], (s) => admin.history(s, 40), { staleTime: 15_000 });
|
||||
const accounts = useServerQuery(['accounts'], (s) => admin.accounts(s), { staleTime: 10 * 60_000 });
|
||||
const devices = useServerQuery(['devices'], (s) => admin.devices(s), { staleTime: 10 * 60_000 });
|
||||
const deviceName = useMemo(() => Object.fromEntries((devices.data ?? []).map((d) => [d.id, d.name])), [devices.data]);
|
||||
return (
|
||||
<>
|
||||
<Card title="Running now" actions={<span className="note">Scans, analysis and maintenance</span>}>
|
||||
{activities.data && !activities.data.length && <p className="muted np-empty">The server is idle.</p>}
|
||||
{activities.data?.map((a) => (
|
||||
<div key={a.uuid} className="activity-row">
|
||||
<div className="lib-ico">
|
||||
<Icon name={a.type.includes('library') ? 'refresh' : a.type.includes('media') ? 'film' : 'activity'} size={17} />
|
||||
</div>
|
||||
<div className="activity-text">
|
||||
<strong>{a.title}</strong>
|
||||
<small>{a.subtitle}</small>
|
||||
{a.progress > 0 && (
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${a.progress}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{a.cancellable && (
|
||||
<Button variant="ghost" size="sm" onClick={() => admin.cancelActivity(server, a.uuid).then(() => activities.refetch(), toastError)}>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</Card>
|
||||
<Card title="Watch history">
|
||||
{history.isLoading && <PageLoader />}
|
||||
{history.data && !history.data.length && <EmptyState icon="clock" title="No history yet" />}
|
||||
<div className="history-list">
|
||||
{history.data?.map((h) => (
|
||||
<div key={h.id + h.viewedAt} className="history-row">
|
||||
<div className="history-thumb">
|
||||
<Artwork src={server.image(h.thumb, 60, 90)} />
|
||||
</div>
|
||||
<div>
|
||||
<strong>{h.title}</strong>
|
||||
<small>{h.subtitle}</small>
|
||||
</div>
|
||||
<span className="dim">{accounts.data?.[h.accountId] ?? 'Owner'}</span>
|
||||
<span className="dim">{deviceName[h.deviceId] ?? ''}</span>
|
||||
<span className="dim">{relativeTime(h.viewedAt)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerDashboard({ tab }: { tab: 'dashboard' | 'activity' }) {
|
||||
return tab === 'dashboard' ? <Dashboard /> : <Activity />;
|
||||
}
|
||||