Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa4a4fb5ef | ||
|
|
7ab4ae0c4b | ||
|
|
af4e21ee6f | ||
|
|
72d9412a85 |
@@ -1,41 +1,80 @@
|
||||
# On a tag (v1.2.3): build inside a SmartFox checkout (sf-ui lives there),
|
||||
# publish a release with the two store assets.
|
||||
# On a tag (v1.2.3): build the app and publish a release with the store
|
||||
# assets: app.toml, the x86-64 package and the aarch64 one (Raspberry Pi,
|
||||
# docs/store.md in Fennec OS). sf-ui and sf-pack come from the Fennec SDK (public).
|
||||
#
|
||||
# Secrets:
|
||||
# SMARTFOX_TOKEN read access to bluefox/fox-in-the-box (it is private)
|
||||
# Runner hygiene (shared host, little disk): runs in the runner image that is
|
||||
# already on the host (no image pull), uses no `uses:` actions (no action
|
||||
# cache), and deletes everything it made at the end. The image is Ubuntu
|
||||
# 24.04: its glibc is older than the TV's (Debian trixie), so the binary runs.
|
||||
name: release
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: build
|
||||
container:
|
||||
image: debian:trixie
|
||||
image: docker.gitea.com/runner-images:ubuntu-latest
|
||||
env:
|
||||
SMARTFOX_REPO: gitea.bluefox.support/bluefox/fox-in-the-box
|
||||
W: /tmp/fennec-netflex
|
||||
CARGO_HOME: /tmp/fennec-netflex/cargo
|
||||
RUSTUP_HOME: /tmp/fennec-netflex/rustup
|
||||
CARGO_TARGET_DIR: /tmp/fennec-netflex/target
|
||||
CARGO_INCREMENTAL: "0"
|
||||
SDK_GIT: https://gitea.bluefox.support/fennec/sdk
|
||||
SDK_TAG: v0.1.2
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends build-essential pkg-config curl ca-certificates git jq \
|
||||
libfontconfig1-dev libfreetype-dev libxkbcommon-dev \
|
||||
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev >/dev/null
|
||||
git clone --depth 1 "https://oauth2:${{ secrets.SMARTFOX_TOKEN }}@${SMARTFOX_REPO}.git" work
|
||||
mkdir -p "$W"
|
||||
git clone --depth 1 --branch "$GITHUB_REF_NAME" \
|
||||
"${GITHUB_SERVER_URL%%://*}://oauth2:${{ secrets.GITHUB_TOKEN }}@${GITHUB_SERVER_URL#*://}/${GITHUB_REPOSITORY}.git" work/apps/netflex-tv
|
||||
"${GITHUB_SERVER_URL%%://*}://oauth2:${{ secrets.GITHUB_TOKEN }}@${GITHUB_SERVER_URL#*://}/${GITHUB_REPOSITORY}.git" "$W/src"
|
||||
v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$W/src/app.toml" | head -1)
|
||||
[ "v$v" = "$GITHUB_REF_NAME" ] || { echo "tag $GITHUB_REF_NAME, but app.toml says $v" >&2; exit 1; }
|
||||
- name: Toolchain
|
||||
run: |
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
# arm64 libraries for the Raspberry Pi build (package.sh --arm):
|
||||
# Ubuntu serves them from ports.ubuntu.com, the main mirror is amd64 only.
|
||||
. /etc/os-release
|
||||
dpkg --add-architecture arm64
|
||||
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
|
||||
sed -i '/^Architectures:/d; /^Types:/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
|
||||
fi
|
||||
[ -f /etc/apt/sources.list ] && sed -i 's/^deb \(http\)/deb [arch=amd64] \1/' /etc/apt/sources.list
|
||||
printf 'Types: deb\nURIs: http://ports.ubuntu.com/ubuntu-ports/\nSuites: %s %s-updates %s-security\nComponents: main universe\nArchitectures: arm64\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n' \
|
||||
"$VERSION_CODENAME" "$VERSION_CODENAME" "$VERSION_CODENAME" >/etc/apt/sources.list.d/arm64-ports.sources
|
||||
apt-get update -qq
|
||||
# Multiarch dev packages for both architectures; for arm64 only the
|
||||
# GStreamer runtime libraries: its dev packages can't be installed for
|
||||
# two architectures at once (package.sh --arm links the libraries).
|
||||
libs="libfontconfig1-dev libfreetype-dev libxkbcommon-dev libglib2.0-dev"
|
||||
apt-get install -y -qq --no-install-recommends build-essential pkg-config \
|
||||
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross \
|
||||
$libs $(for l in $libs; do printf '%s:arm64 ' "$l"; done) \
|
||||
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
|
||||
libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path --target aarch64-unknown-linux-gnu
|
||||
"$CARGO_HOME/bin/cargo" install -q --locked --git "$SDK_GIT" --tag "$SDK_TAG" sf-pack
|
||||
- name: Build
|
||||
run: |
|
||||
curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal
|
||||
export PATH="$HOME/.cargo/bin:$PATH"
|
||||
cd work/apps/netflex-tv && ./package.sh
|
||||
export PATH="$CARGO_HOME/bin:$PATH"
|
||||
"$W/src/package.sh"
|
||||
"$W/src/package.sh" --arm
|
||||
- name: Release
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/releases"
|
||||
id=$(curl -fsS -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"$GITHUB_REF_NAME\",\"name\":\"$GITHUB_REF_NAME\"}" "$api" | jq -r .id)
|
||||
for f in work/apps/netflex-tv/dist/*; do
|
||||
-d "{\"tag_name\":\"$GITHUB_REF_NAME\",\"name\":\"$GITHUB_REF_NAME\"}" "$api" \
|
||||
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
|
||||
for f in "$W"/src/dist/*; do
|
||||
curl -fsS -H "Authorization: token $TOKEN" -F "attachment=@$f" "$api/$id/assets?name=$(basename "$f")" >/dev/null
|
||||
done
|
||||
- name: Clean up
|
||||
if: always()
|
||||
run: |
|
||||
rm -rf "$W"
|
||||
df -h / | tail -1
|
||||
|
||||
29
AGENTS.md
29
AGENTS.md
@@ -9,15 +9,26 @@ Read first:
|
||||
```
|
||||
app.toml store manifest (id support.bluefox.netflex; permissions network, gpu, audio)
|
||||
src/main.rs window, glass layer (lists every exported [GlassRect]), images, controller
|
||||
src/app.rs Controller: screens (message, signin, home, detail, player), Back stack, start-up, sign-in
|
||||
src/home.rs tabs (Kezdőlap, Filmek, Sorozatok, Listám, Keresés): rows, focus, lazy images, backdrop, search
|
||||
src/detail.rs title page: Play/Continue/Next target, My List, seasons, episodes
|
||||
src/player.rs sources -> /api/play/start -> probe -> sf_ui::video::Player; tracks, seek, OSD, progress
|
||||
src/app.rs Controller: screen stack, keys, input/picker/toast overlays, backdrop, start-up, sign-in
|
||||
src/page.rs the line-based page engine: lines (L) and chips (Ch) -> layout, focus, scroll, lazy images
|
||||
src/screens/mod.rs sections of the top nav, shared cards, Load<T>, opening a card
|
||||
src/screens/home.rs Kezdőlap: admin setup checklist, spotlight, Folytatás, the server's rows
|
||||
src/screens/source.rs Filmek / Sorozatok: Ajánlott, Könyvtáram, Böngészés (genre, year, rating, sort)
|
||||
src/screens/detail.rs film / series page: Play/Continue, My List, season cards, episodes, nCore versions
|
||||
src/screens/anime_hub.rs Anime: Ajánlott, Könyvtáram, Böngészés (AniList filters)
|
||||
src/screens/anime_detail.rs anime page: franchise seasons, release group, episodes, nyaa versions
|
||||
src/screens/mylist.rs Listám: saved and history
|
||||
src/screens/search.rs Keresés: embedded keyboard, results
|
||||
src/screens/settings.rs Beállítások: account, users, server; admin: VPN, nCore, seeding, sources, anime, TMDB; player; look
|
||||
src/player.rs source -> torrent -> probe -> sf_ui::video::Player; tracks, quality, prev/next, up next, skip intro
|
||||
src/api.rs Netflex HTTP API (mirrors netflex/packages/client/src/api.ts)
|
||||
src/config.rs server + token (config.toml), per-TV settings (device.toml: glass look, anime release groups)
|
||||
src/format.rs Hungarian texts: times, dates, languages, genres
|
||||
src/task.rs blocking work on a thread, result on the UI thread
|
||||
ui/app.slint root: screen fades, one FocusScope -> Rust `key`, glass exports
|
||||
ui/{home,detail,player,signin}.slint, ui/types.slint
|
||||
tools/mock_server.py stand-in server (real Cinemeta data, password "netflex", --video file streamed)
|
||||
ui/page.slint LinePage: draws the lines Rust lays out (nav, side list, keyboard)
|
||||
ui/{player,signin,overlays,types}.slint
|
||||
tools/mock_server.py stand-in server: Cinemeta + AniList data, admin pages, password "netflex", --video file
|
||||
```
|
||||
|
||||
## Rules of this codebase
|
||||
@@ -25,7 +36,11 @@ tools/mock_server.py stand-in server (real Cinemeta data, password "netflex", -
|
||||
- **Rust owns state and focus.** Slint only draws. Every key goes to `Controller::key`, except while an on-screen keyboard has the focus (signin, search).
|
||||
- **Short borrows:** never hold `state.borrow_mut()` while calling `images.load*`; a cached picture calls back at once. Use the `Then` enum pattern: decide under the borrow, act after it.
|
||||
- **Glass:** new glass elements need their `glass` listed in a root `out property <[GlassRect]>`, and that array added in `main.rs`. Nothing Slint draws may sit under a glass pane.
|
||||
- **Texts are Hungarian.** Follow the Netflex web app's behaviour (resume rules, track picking: `player.rs` tests).
|
||||
- **A new page** is a `Screen` (src/app.rs): `spec` returns lines, `activate` gets (line id, chip id). Never draw focus in Slint; the page engine does it.
|
||||
- **Feature parity:** every screen follows a page of the web app (`netflex/apps/web/src`); the module docs name it. Check there first.
|
||||
- **Texts are Hungarian.** Follow the Netflex web app's behaviour (resume rules, track picking, skip segments: `player.rs` tests).
|
||||
- **Free-standing `GlassButton`** (outside a layout) needs `width: self.preferred-width`, else it fills its parent.
|
||||
- **`match state.borrow().x { ... }` keeps the borrow for the whole match:** copy the value out first.
|
||||
|
||||
## Check your change
|
||||
|
||||
|
||||
5
Cargo.lock
generated
5
Cargo.lock
generated
@@ -3402,7 +3402,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "netflex-tv"
|
||||
version = "0.1.1"
|
||||
version = "0.1.4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"env_logger",
|
||||
@@ -4864,7 +4864,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sf-ui"
|
||||
version = "0.2.1"
|
||||
version = "0.1.2"
|
||||
source = "git+https://gitea.bluefox.support/fennec/sdk?tag=v0.1.2#cb37d872ed7195e57268e0c3a1a76367039bf959"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"glow 0.16.0",
|
||||
|
||||
14
Cargo.toml
14
Cargo.toml
@@ -1,18 +1,16 @@
|
||||
[package]
|
||||
name = "netflex-tv"
|
||||
description = "Netflex for SmartFox: native TV client with Liquid Glass and hardware video playback"
|
||||
version = "0.1.1"
|
||||
version = "0.1.4"
|
||||
edition = "2024"
|
||||
# sf-ui (and Slint) are GPL-3.0 on a TV box.
|
||||
license = "GPL-3.0-only"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
# The SmartFox UI kit: Liquid Glass, TV components, images. This repository
|
||||
# is built inside a SmartFox checkout, at apps/netflex-tv (the release CI
|
||||
# clones SmartFox and puts it there). With a public sf-ui this can become
|
||||
# a git dependency: sf-ui = { git = "<SmartFox repo URL>" }.
|
||||
sf-ui = { path = "../../crates/sf-ui" }
|
||||
# The Fennec OS UI kit (Fennec SDK): Liquid Glass, TV components, images.
|
||||
# Working on sf-ui next to this app: see README.md.
|
||||
sf-ui = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.2" }
|
||||
slint = "1.18"
|
||||
anyhow = "1"
|
||||
log = "0.4"
|
||||
@@ -24,7 +22,7 @@ ureq = { version = "3", features = ["json"] }
|
||||
|
||||
# Video playback (GStreamer) only on Linux, the TV.
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
sf-ui = { path = "../../crates/sf-ui", features = ["video"] }
|
||||
sf-ui = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.2", features = ["video"] }
|
||||
|
||||
[build-dependencies]
|
||||
slint-build = "1.18"
|
||||
@@ -33,5 +31,5 @@ slint-build = "1.18"
|
||||
lto = "thin"
|
||||
strip = true
|
||||
|
||||
# Not part of the SmartFox workspace: this is its own repository.
|
||||
# Its own workspace (not part of any checkout around it).
|
||||
[workspace]
|
||||
|
||||
22
README.md
22
README.md
@@ -3,33 +3,35 @@
|
||||
Natív Netflex kliens Fennec OS-re (store app, `support.bluefox.netflex`).
|
||||
|
||||
- **Felület:** Rust + Slint az sf-ui Liquid Glass-ával, ugyanazzal, mint a launcher.
|
||||
- **Képernyők:** kezdőlap (Folytatás és a szerver sorai), Filmek és Sorozatok műfaji sorokkal, Listám, Keresés képernyő-billentyűzettel, adatlap évadokkal és epizódokkal, lejátszás.
|
||||
- **Lejátszás:** GStreamer, hardveres dekódolással (VA-API). A szerver nyers fájlját streameli (`/api/stream`, Range-kérésekkel), miközben a torrent töltődik. Az MKV minden hang- és feliratsávja választható; a hangkésés állítható és a szerveren megmarad. A haladás 15 másodpercenként mentődik, a sorozatoknál jön a következő rész.
|
||||
- **Képernyők:** ugyanaz, mint a webes felületen. Kezdőlap (az admin beállítási listája, kiemelt tartalom, Folytatás, a szerver sorai), Filmek és Sorozatok (Ajánlott, Könyvtáram, Böngészés műfajjal, évvel, értékeléssel), Anime (AniList: ajánlott, könyvtár, szűrők; adatlap évadokkal, kiadócsoport-választással), Listám (mentett és előzmények), Keresés képernyő-billentyűzettel, adatlap évadkártyákkal és epizódokkal, nCore verziók hangsávokkal.
|
||||
- **Beállítások:** Fiók (eszközök, kijelentkezés), Szerver, Lejátszás, Megjelenés mindenkinek; az adminnak még Felhasználók, VPN (WireGuard, port forwarding, ellenőrzések), nCore, Visszatöltés (szabályok, torrentek), Források, Anime és Magyar szövegek (TMDB).
|
||||
- **Lejátszás:** GStreamer, hardveres dekódolással (VA-API). A szerver nyers fájlját streameli (`/api/stream`, Range-kérésekkel), miközben a torrent töltődik. Minden hang- és feliratsáv választható, a hangkésés állítható és a szerveren megmarad, a minőség (HD / FHD / 4K) lejátszás közben váltható. Előző / következő rész, „Következik” visszaszámlálással, animénél intro- és összefoglaló-átugrás (AniSkip). A haladás 15 másodpercenként mentődik.
|
||||
- **Bejelentkezés:** a szerver címe, felhasználónév, jelszó; a token a `$HOME/.config/netflex/config.toml`-ban marad.
|
||||
|
||||
## Fejlesztés
|
||||
|
||||
A repó a Fennec OS checkout `apps/netflex-tv` mappájában él (az sf-ui path-függőség: `../../crates/sf-ui`).
|
||||
Az sf-ui a [Fennec SDK](https://gitea.bluefox.support/fennec/sdk)-ból jön, git-függőségként (tag). A repó bárhol élhet, a Fennec OS forráskódja nem kell hozzá. Ha az sf-ui-t is fejleszted mellette, tedd a `.cargo/config.toml` fájlba (ne commitold):
|
||||
```toml
|
||||
[patch."https://gitea.bluefox.support/fennec/sdk"]
|
||||
sf-ui = { path = "../sdk/sf-ui" }
|
||||
```
|
||||
|
||||
```sh
|
||||
# Mock szerver: valódi Cinemeta katalógus, jelszó: netflex
|
||||
# Mock szerver: valódi Cinemeta és AniList adatok, admin oldalak, jelszó: netflex
|
||||
python3 tools/mock_server.py --port 7880 --video teszt.mkv
|
||||
NETFLEX_SERVER=http://127.0.0.1:7880 NETFLEX_WINDOWED=1 cargo run
|
||||
```
|
||||
|
||||
- **Windowson:** a felület fejleszthető, de videó nincs (a GStreamer csak Linuxon van bekötve).
|
||||
- **Linuxon** (Debian trixie / WSL) kell még: `libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev gstreamer1.0-plugins-bad gstreamer1.0-libav gstreamer1.0-pipewire`.
|
||||
- **Pillanatkép ember nélkül:** `SF_UI_SIZE=1920x1080 SF_UI_KEYS="wait wait down enter" SF_UI_SNAPSHOT=out.png cargo run` (lásd `../../docs/sf-ui.md`, 11. fejezet).
|
||||
- **Pillanatkép ember nélkül:** `SF_UI_SIZE=1920x1080 SF_UI_KEYS="wait wait down enter" SF_UI_SNAPSHOT=out.png cargo run` (lásd az SDK `docs/sf-ui.md` fájljának 11. fejezetét).
|
||||
|
||||
## Kiadás
|
||||
|
||||
1. Emeld a `version` értékét az `app.toml`-ban és a `Cargo.toml`-ban.
|
||||
2. `git tag v0.1.1 && git push --tags`.
|
||||
3. A Gitea CI (`.gitea/workflows/release.yml`) a Fennec OS checkouton belül épít, és release-t csinál a két store-fájllal.
|
||||
3. A Gitea CI (`.gitea/workflows/release.yml`) megépíti, és release-t csinál a két store-fájllal. Secret nem kell hozzá.
|
||||
|
||||
CI secret:
|
||||
- `SMARTFOX_TOKEN`: olvasási jog a `bluefox/fox-in-the-box` repóhoz.
|
||||
|
||||
Helyben: `./package.sh`.
|
||||
Helyben: `./package.sh` (kell hozzá az `sf-pack`, lásd a script fejlécét).
|
||||
|
||||
A TV-n: Store → Források → a repó címe.
|
||||
|
||||
2
app.toml
2
app.toml
@@ -2,7 +2,7 @@
|
||||
id = "support.bluefox.netflex"
|
||||
name = "Netflex"
|
||||
# Release versions only (1.2.3). Bump it (and Cargo.toml) for every release.
|
||||
version = "0.1.1"
|
||||
version = "0.1.4"
|
||||
kind = "exec"
|
||||
category = "Saját streaming"
|
||||
description = "Filmek és sorozatok a saját Netflex szerveredről, natívan: azonnal indul, miközben töltődik, hardveres videódekódolással."
|
||||
|
||||
73
package.sh
73
package.sh
@@ -1,25 +1,70 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds the two store release assets into dist/: app.toml and
|
||||
# support.bluefox.netflex-<version>.tar.zst.
|
||||
# Builds the store release assets into dist/:
|
||||
#
|
||||
# Runs inside a SmartFox checkout (this repo at apps/netflex-tv), on Debian
|
||||
# trixie or older (the TV's glibc), with the GStreamer dev packages:
|
||||
# libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
|
||||
# ./package.sh app.toml and support.bluefox.netflex-<version>.tar.zst
|
||||
# (x86-64; dist/ is emptied first)
|
||||
# ./package.sh --arm adds support.bluefox.netflex-<version>-aarch64.tar.zst
|
||||
# (Raspberry Pi, cross-compiled)
|
||||
#
|
||||
# Build on Debian trixie or older (the TV's glibc), with the GStreamer dev
|
||||
# packages (libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev) and
|
||||
# sf-pack from the Fennec SDK:
|
||||
# cargo install --locked --git https://gitea.bluefox.support/fennec/sdk --tag v0.1.2 sf-pack
|
||||
# --arm also needs gcc-aarch64-linux-gnu, the arm64 (multiarch) dev packages
|
||||
# of fontconfig, freetype, xkbcommon and glib, and the arm64 GStreamer
|
||||
# runtime libraries (libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64).
|
||||
# Not the GStreamer dev packages: they can't be installed for two
|
||||
# architectures at once, so the build links the runtime libraries directly.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
cargo build --release --locked
|
||||
target="${CARGO_TARGET_DIR:-target}"
|
||||
rm -rf pkg dist
|
||||
id=$(sed -n 's/^id *= *"\(.*\)".*/\1/p' app.toml | head -1)
|
||||
version=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' app.toml | head -1)
|
||||
|
||||
# pack <binary> <out dir>: the package with this binary.
|
||||
pack() {
|
||||
rm -rf pkg
|
||||
mkdir -p pkg/bin
|
||||
cp app.toml icon.png pkg/
|
||||
install -m755 "$target/release/netflex-tv" pkg/bin/netflex-tv
|
||||
install -m755 "$1" pkg/bin/netflex-tv
|
||||
sf-pack build pkg "$2"
|
||||
sf-pack verify "$2"
|
||||
rm -rf pkg
|
||||
}
|
||||
|
||||
# sf-pack from PATH, else the one in the SmartFox checkout around us.
|
||||
if command -v sf-pack >/dev/null; then
|
||||
pack=(sf-pack)
|
||||
if [ "${1:-}" != --arm ]; then
|
||||
cargo build --release --locked
|
||||
rm -rf dist
|
||||
pack "$target/release/netflex-tv" dist
|
||||
else
|
||||
pack=(cargo run -q --release --manifest-path ../../Cargo.toml -p sf-pack --)
|
||||
t=aarch64-unknown-linux-gnu
|
||||
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
|
||||
export CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++
|
||||
export PKG_CONFIG_ALLOW_CROSS=1 PKG_CONFIG_SYSROOT_DIR=/
|
||||
export PKG_CONFIG_PATH=/usr/lib/aarch64-linux-gnu/pkgconfig:/usr/share/pkgconfig
|
||||
rustup target list --installed | grep -qx "$t" || rustup target add "$t"
|
||||
# GStreamer without pkg-config (system-deps): link the runtime libraries
|
||||
# through a folder of unversioned names.
|
||||
mkdir -p "$target"
|
||||
gst="$(cd "$target" && pwd)/arm-gstreamer"
|
||||
rm -rf "$gst" && mkdir -p "$gst"
|
||||
# system-deps key (the pkg-config name) and the library it stands for.
|
||||
for pair in GSTREAMER_1_0:gstreamer-1.0 GSTREAMER_BASE_1_0:gstbase-1.0 \
|
||||
GSTREAMER_APP_1_0:gstapp-1.0 GSTREAMER_VIDEO_1_0:gstvideo-1.0; do
|
||||
key=${pair%%:*} lib=${pair#*:}
|
||||
so=/usr/lib/aarch64-linux-gnu/lib$lib.so.0
|
||||
[ -e "$so" ] || { echo "missing $so (install the arm64 GStreamer runtime libraries)" >&2; exit 1; }
|
||||
ln -s "$so" "$gst/lib$lib.so"
|
||||
export "SYSTEM_DEPS_${key}_NO_PKG_CONFIG=1" "SYSTEM_DEPS_${key}_LIB=$lib" "SYSTEM_DEPS_${key}_SEARCH_NATIVE=$gst"
|
||||
done
|
||||
cargo build --release --locked --target "$t"
|
||||
rm -rf dist-arm
|
||||
pack "$target/$t/release/netflex-tv" dist-arm
|
||||
# Fennec OS on ARM looks for <id>-<version>-aarch64.tar.zst (docs/store.md).
|
||||
mkdir -p dist
|
||||
mv "dist-arm/$id-$version.tar.zst" "dist/$id-$version-aarch64.tar.zst"
|
||||
[ -f dist/app.toml ] || mv dist-arm/app.toml dist/
|
||||
rm -rf dist-arm
|
||||
fi
|
||||
"${pack[@]}" build pkg dist
|
||||
"${pack[@]}" verify dist
|
||||
ls -l dist
|
||||
|
||||
25
src/app.rs
25
src/app.rs
@@ -115,9 +115,7 @@ type SelectDone = Box<dyn FnOnce(&Controller, usize)>;
|
||||
|
||||
enum Effect {
|
||||
Push(Box<dyn Screen>),
|
||||
Pop,
|
||||
Refresh,
|
||||
Section(usize),
|
||||
Play(player::Request),
|
||||
}
|
||||
|
||||
@@ -190,9 +188,6 @@ impl<'a> Cx<'a> {
|
||||
pub fn api(&self) -> Api {
|
||||
self.c.api()
|
||||
}
|
||||
pub fn api_base_image(&self, url: Option<&str>) -> String {
|
||||
self.c.state.borrow().api.image(url, false)
|
||||
}
|
||||
pub fn user(&self) -> User {
|
||||
self.c.state.borrow().user.clone()
|
||||
}
|
||||
@@ -235,15 +230,9 @@ impl<'a> Cx<'a> {
|
||||
pub fn push(&self, s: Box<dyn Screen>) {
|
||||
self.c.effects.borrow_mut().push(Effect::Push(s));
|
||||
}
|
||||
pub fn pop(&self) {
|
||||
self.c.effects.borrow_mut().push(Effect::Pop);
|
||||
}
|
||||
pub fn refresh(&self) {
|
||||
self.c.effects.borrow_mut().push(Effect::Refresh);
|
||||
}
|
||||
pub fn section(&self, n: usize) {
|
||||
self.c.effects.borrow_mut().push(Effect::Section(n));
|
||||
}
|
||||
pub fn play(&self, r: player::Request) {
|
||||
self.c.effects.borrow_mut().push(Effect::Play(r));
|
||||
}
|
||||
@@ -282,10 +271,6 @@ impl<'a> Cx<'a> {
|
||||
e.view.focus_on(line, col);
|
||||
}
|
||||
}
|
||||
/// Physical pixels per design pixel.
|
||||
pub fn px(&self) -> f32 {
|
||||
self.c.px()
|
||||
}
|
||||
}
|
||||
|
||||
impl Controller {
|
||||
@@ -370,11 +355,8 @@ impl Controller {
|
||||
self.state.borrow().api.clone()
|
||||
}
|
||||
|
||||
pub fn is_admin(&self) -> bool {
|
||||
self.state.borrow().user.is_admin
|
||||
}
|
||||
|
||||
fn show(&self, screen: &'static str) {
|
||||
pub fn show(&self, screen: &'static str) {
|
||||
self.state.borrow_mut().screen = screen;
|
||||
if let Some(ui) = self.ui() {
|
||||
ui.set_screen(screen.into());
|
||||
@@ -886,9 +868,7 @@ impl Controller {
|
||||
for e in effects {
|
||||
match e {
|
||||
Effect::Push(s) => self.push_now(s),
|
||||
Effect::Pop => self.pop_now(),
|
||||
Effect::Refresh => refresh = true,
|
||||
Effect::Section(n) => self.section_now(n),
|
||||
Effect::Play(r) => player::play(self, r),
|
||||
}
|
||||
}
|
||||
@@ -1050,7 +1030,8 @@ impl Controller {
|
||||
if self.state.borrow().select.is_some() {
|
||||
return self.select_key(a);
|
||||
}
|
||||
match self.state.borrow().screen {
|
||||
let screen = self.state.borrow().screen;
|
||||
match screen {
|
||||
"message" => return self.message_key(a),
|
||||
"player" => return player::key(self, a, repeat),
|
||||
_ => {}
|
||||
|
||||
@@ -55,9 +55,12 @@ impl Config {
|
||||
/// per-device look: `$HOME/.config/netflex/device.toml`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Local {
|
||||
/// "auto" | "full" | "light" | "off"
|
||||
/// "auto" | "full" | "light" | "off" (Material)
|
||||
#[serde(default = "auto")]
|
||||
pub glass: String,
|
||||
/// The release group picked per anime (AniList id -> "SubsPlease|1080").
|
||||
#[serde(default)]
|
||||
pub anime_groups: std::collections::HashMap<String, String>,
|
||||
}
|
||||
|
||||
fn auto() -> String {
|
||||
@@ -66,7 +69,7 @@ fn auto() -> String {
|
||||
|
||||
impl Default for Local {
|
||||
fn default() -> Self {
|
||||
Local { glass: auto() }
|
||||
Local { glass: auto(), anime_groups: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,11 +91,13 @@ impl Local {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the glass look ("auto" = full: the TV's GPU handles it).
|
||||
/// Applies the glass look. "auto": sf-ui measures the GPU and picks full,
|
||||
/// light or the matte Material style; "off" (shown as "Matt") is Material.
|
||||
pub fn apply_look(glass: &sf_ui::Glass, look: &str) {
|
||||
glass.set_quality(match look {
|
||||
"light" => sf_ui::Quality::Light,
|
||||
"off" => sf_ui::Quality::Flat,
|
||||
_ => sf_ui::Quality::Full,
|
||||
});
|
||||
match look {
|
||||
"full" => glass.set_quality(sf_ui::Quality::Full),
|
||||
"light" => glass.set_quality(sf_ui::Quality::Light),
|
||||
"off" => glass.set_quality(sf_ui::Quality::Material),
|
||||
_ => glass.set_auto_quality(),
|
||||
}
|
||||
}
|
||||
|
||||
572
src/detail.rs
572
src/detail.rs
@@ -1,572 +0,0 @@
|
||||
//! A title's page: facts, Play / Continue / Next, My List, seasons and
|
||||
//! episodes. The title's artwork is the glass backdrop.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use slint::{Model, ModelRc, VecModel};
|
||||
|
||||
use crate::api::{self, EpisodeInfo, MediaType, ProgressRow, SeasonSummary, TitleDetail};
|
||||
use crate::app::{Action, Controller, Screen};
|
||||
use crate::home::Item;
|
||||
use crate::{Episode, MenuItem, format, player, task};
|
||||
|
||||
pub struct Detail {
|
||||
item: Item,
|
||||
data: Option<TitleDetail>,
|
||||
progress: Vec<ProgressRow>,
|
||||
listed: bool,
|
||||
/// The season whose episodes are shown.
|
||||
season: i32,
|
||||
episodes: Vec<EpisodeInfo>,
|
||||
ep_model: Rc<VecModel<Episode>>,
|
||||
/// 0 = buttons, 1 = episodes, 2 = season menu.
|
||||
area: i32,
|
||||
button: i32,
|
||||
episode: usize,
|
||||
season_focus: usize,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
fn seasons_of(d: &Detail) -> &[SeasonSummary] {
|
||||
d.data.as_ref().map(|t| t.seasons.as_slice()).unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// Where Play goes, its label and the resume position (web: resumeTarget).
|
||||
fn target(d: &Detail) -> (Option<(i32, i32)>, String, f64) {
|
||||
let resume = |p: &ProgressRow| (p.position - 3.0).max(0.0);
|
||||
let unfinished = |p: &ProgressRow| !p.completed && p.position > 60.0 && p.duration.is_none_or(|dur| p.position / dur < 0.95);
|
||||
if d.item.kind == MediaType::Movie {
|
||||
return match d.progress.iter().find(|p| p.season == 0 && p.episode == 0) {
|
||||
Some(p) if unfinished(p) => (None, "Folytatás".into(), resume(p)),
|
||||
_ => (None, "Lejátszás".into(), 0.0),
|
||||
};
|
||||
}
|
||||
let seasons = seasons_of(d);
|
||||
let first = seasons.iter().map(|s| s.number).find(|n| *n > 0).unwrap_or(1);
|
||||
let latest = d.progress.iter().filter(|p| p.season > 0).max_by_key(|p| (p.season, p.episode));
|
||||
let Some(latest) = latest else { return (Some((first, 1)), "Lejátszás".into(), 0.0) };
|
||||
let (s, e) = (latest.season, latest.episode);
|
||||
if !latest.completed {
|
||||
return (Some((s, e)), format!("Folytatás · {}", format::episode_code(s, e)), if unfinished(latest) { resume(latest) } else { 0.0 });
|
||||
}
|
||||
match next_episode(seasons, &d.episodes, d.season, s, e) {
|
||||
Some((ns, ne)) => (Some((ns, ne)), format!("Következő · {}", format::episode_code(ns, ne)), 0.0),
|
||||
None => (Some((s, e)), "Újra".into(), 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The episode after `s`/`e`: the next aired one in the season, or the
|
||||
/// first of the next season. `episodes` are those of season `shown`.
|
||||
fn next_episode(seasons: &[SeasonSummary], episodes: &[EpisodeInfo], shown: i32, s: i32, e: i32) -> Option<(i32, i32)> {
|
||||
let today = chrono_today();
|
||||
let aired = |ep: &EpisodeInfo| ep.air_date.as_deref().is_none_or(|d| d <= today.as_str());
|
||||
let in_season = if shown == s && !episodes.is_empty() {
|
||||
episodes.iter().any(|ep| ep.episode == e + 1 && aired(ep))
|
||||
} else {
|
||||
seasons.iter().find(|x| x.number == s).is_some_and(|x| e < x.aired_count.unwrap_or(x.episode_count))
|
||||
};
|
||||
if in_season {
|
||||
return Some((s, e + 1));
|
||||
}
|
||||
seasons.iter().find(|x| x.number == s + 1 && x.aired_count.unwrap_or(x.episode_count) > 0).map(|x| (x.number, 1))
|
||||
}
|
||||
|
||||
fn chrono_today() -> String {
|
||||
// YYYY-MM-DD without a date crate: days since the epoch -> civil date.
|
||||
let days = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() / 86400).unwrap_or(0) as i64;
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
|
||||
format!("{y:04}-{m:02}-{d:02}")
|
||||
}
|
||||
|
||||
/// The season to show first: where the viewer is, else the first one.
|
||||
fn current_season(d: &Detail) -> i32 {
|
||||
let seasons = seasons_of(d);
|
||||
let first = seasons.iter().map(|s| s.number).find(|n| *n > 0).or_else(|| seasons.first().map(|s| s.number)).unwrap_or(1);
|
||||
let last = d.progress.iter().filter(|p| p.season > 0).map(|p| p.season).max();
|
||||
let Some(last) = last else { return first };
|
||||
let Some(s) = seasons.iter().find(|x| x.number == last) else { return first };
|
||||
let watched = d.progress.iter().filter(|p| p.season == last && p.completed).count() as i32;
|
||||
if watched < s.aired_count.unwrap_or(s.episode_count) {
|
||||
return last;
|
||||
}
|
||||
seasons.iter().find(|x| x.number > last && x.aired_count.unwrap_or(x.episode_count) > 0).map(|x| x.number).unwrap_or(last)
|
||||
}
|
||||
|
||||
pub fn open(c: &Controller, item: &Item) {
|
||||
let generation = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let generation = st.detail.as_ref().map(|d| d.generation + 1).unwrap_or(1);
|
||||
st.detail = Some(Detail {
|
||||
item: item.clone(),
|
||||
data: None,
|
||||
progress: Vec::new(),
|
||||
listed: false,
|
||||
season: 1,
|
||||
episodes: Vec::new(),
|
||||
ep_model: Rc::new(VecModel::default()),
|
||||
area: 0,
|
||||
button: 0,
|
||||
episode: 0,
|
||||
season_focus: 0,
|
||||
generation,
|
||||
});
|
||||
generation
|
||||
};
|
||||
if let Some(ui) = c.ui() {
|
||||
ui.set_detail_title(item.title.clone().into());
|
||||
ui.set_detail_meta(item.meta.clone().into());
|
||||
ui.set_detail_overview(item.overview.clone().into());
|
||||
ui.set_detail_logo(Default::default());
|
||||
ui.set_detail_is_series(item.kind == MediaType::Tv);
|
||||
ui.set_detail_play_label("Lejátszás".into());
|
||||
ui.set_detail_listed(false);
|
||||
ui.set_detail_season_label("".into());
|
||||
ui.set_detail_episodes(ModelRc::from(c.state.borrow().detail.as_ref().unwrap().ep_model.clone()));
|
||||
ui.set_detail_seasons(ModelRc::default());
|
||||
ui.set_detail_status("".into());
|
||||
ui.set_detail_busy(true);
|
||||
}
|
||||
sync(c);
|
||||
show_backdrop(c, item);
|
||||
let px = c.px();
|
||||
if !item.logo.is_empty() {
|
||||
let k = c.clone();
|
||||
c.images.load(&item.logo, ((620.0 * px) as u32, (190.0 * px) as u32), move |img| {
|
||||
if k.state.borrow().detail.as_ref().is_some_and(|d| d.generation == generation) {
|
||||
if let Some(ui) = k.ui() {
|
||||
ui.set_detail_logo(img);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
c.push(Screen::Detail);
|
||||
load(c, generation);
|
||||
}
|
||||
|
||||
fn show_backdrop(c: &Controller, item: &Item) {
|
||||
if item.backdrop.is_empty() {
|
||||
c.glass.set_backdrop(None);
|
||||
return;
|
||||
}
|
||||
let k = c.clone();
|
||||
let key = item.key();
|
||||
let px = c.px();
|
||||
c.images.load_pixels(&item.backdrop, ((1920.0 * px) as u32, (1080.0 * px) as u32), move |pixels| {
|
||||
let st = k.state.borrow();
|
||||
if st.screen == Screen::Detail && st.detail.as_ref().is_some_and(|d| d.item.key() == key) {
|
||||
k.glass.set_backdrop(Some(sf_ui::Backdrop::new(pixels.clone()).dim(0.25).fade_left(1.0).fade_bottom(0.9).align(0.6, 0.2)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn load(c: &Controller, generation: u64) {
|
||||
let Some((kind, id)) = c.state.borrow().detail.as_ref().map(|d| (d.item.kind, d.item.id.clone())) else { return };
|
||||
let api = c.api();
|
||||
let k = c.clone();
|
||||
task::spawn(
|
||||
move || -> anyhow::Result<_> {
|
||||
let data = api.title(kind, &id)?;
|
||||
let progress = api.progress(kind, &id).unwrap_or_default();
|
||||
let listed = api.list_status().ok().and_then(|m| m.get(&format!("{}:{}", kind.key(), id)).map(|s| s.listed)).unwrap_or(false);
|
||||
Ok((data, progress, listed))
|
||||
},
|
||||
move |r| {
|
||||
let ok = {
|
||||
let mut st = k.state.borrow_mut();
|
||||
let Some(d) = st.detail.as_mut().filter(|d| d.generation == generation) else { return };
|
||||
match r {
|
||||
Ok((data, progress, listed)) => {
|
||||
d.data = Some(data);
|
||||
d.progress = progress;
|
||||
d.listed = listed;
|
||||
d.season = current_season(d);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
};
|
||||
match ok {
|
||||
Ok(()) => {
|
||||
refresh(&k);
|
||||
let series = k.state.borrow().detail.as_ref().is_some_and(|d| d.item.kind == MediaType::Tv);
|
||||
if series {
|
||||
load_season(&k, generation);
|
||||
} else if let Some(ui) = k.ui() {
|
||||
ui.set_detail_busy(false);
|
||||
}
|
||||
}
|
||||
Err(e) if api::is_unauthenticated(&e) => k.signed_out(),
|
||||
Err(e) => {
|
||||
if let Some(ui) = k.ui() {
|
||||
ui.set_detail_busy(false);
|
||||
ui.set_detail_status(api::describe(&e).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn load_season(c: &Controller, generation: u64) {
|
||||
let Some((id, season)) = c.state.borrow().detail.as_ref().map(|d| (d.item.id.clone(), d.season)) else { return };
|
||||
if let Some(ui) = c.ui() {
|
||||
ui.set_detail_busy(true);
|
||||
ui.set_detail_status("".into());
|
||||
}
|
||||
let api = c.api();
|
||||
let k = c.clone();
|
||||
task::spawn(
|
||||
move || api.season(&id, season),
|
||||
move |r| {
|
||||
let Some(ui) = k.ui() else { return };
|
||||
ui.set_detail_busy(false);
|
||||
match r {
|
||||
Ok(s) => {
|
||||
{
|
||||
let mut st = k.state.borrow_mut();
|
||||
let Some(d) = st.detail.as_mut().filter(|d| d.generation == generation && d.season == season) else { return };
|
||||
d.episodes = s.episodes;
|
||||
d.episode = first_unwatched(d);
|
||||
}
|
||||
refresh(&k);
|
||||
load_stills(&k);
|
||||
}
|
||||
Err(e) => ui.set_detail_status(api::describe(&e).into()),
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn first_unwatched(d: &Detail) -> usize {
|
||||
d.episodes
|
||||
.iter()
|
||||
.position(|e| !d.progress.iter().any(|p| p.season == e.season && p.episode == e.episode && p.completed))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Labels, the episodes model and focus, from the state.
|
||||
fn refresh(c: &Controller) {
|
||||
let Some(ui) = c.ui() else { return };
|
||||
let st = c.state.borrow();
|
||||
let Some(d) = st.detail.as_ref() else { return };
|
||||
let (_, label, _) = target(d);
|
||||
ui.set_detail_play_label(label.into());
|
||||
ui.set_detail_listed(d.listed);
|
||||
if let Some(data) = &d.data {
|
||||
let extra = if d.item.kind == MediaType::Tv {
|
||||
let n = data.seasons.iter().filter(|s| s.number > 0).count();
|
||||
if n > 0 { format!("{n} évad") } else { String::new() }
|
||||
} else {
|
||||
format::runtime(data.runtime)
|
||||
};
|
||||
ui.set_detail_meta(format::meta(&data.summary, &extra).into());
|
||||
let season = data.seasons.iter().find(|s| s.number == d.season);
|
||||
ui.set_detail_season_label(season.map(|s| if s.name.is_empty() { format!("{}. évad", s.number) } else { s.name.clone() }).unwrap_or_default().into());
|
||||
let items: Vec<MenuItem> = data
|
||||
.seasons
|
||||
.iter()
|
||||
.map(|s| MenuItem {
|
||||
text: if s.name.is_empty() { format!("{}. évad", s.number) } else { s.name.clone() }.into(),
|
||||
detail: format!("{} rész", s.aired_count.unwrap_or(s.episode_count)).into(),
|
||||
checked: s.number == d.season,
|
||||
})
|
||||
.collect();
|
||||
ui.set_detail_seasons(ModelRc::new(VecModel::from(items)));
|
||||
}
|
||||
// Episodes: keep pictures already loaded.
|
||||
let old: Vec<Episode> = d.ep_model.iter().collect();
|
||||
let eps: Vec<Episode> = d
|
||||
.episodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, e)| {
|
||||
let p = d.progress.iter().find(|p| p.season == e.season && p.episode == e.episode);
|
||||
let watched = p.is_some_and(|p| p.completed);
|
||||
let progress = match p {
|
||||
Some(p) if !p.completed => p.duration.filter(|x| *x > 0.0).map(|x| (p.position / x) as f32).unwrap_or(-1.0),
|
||||
_ => -1.0,
|
||||
};
|
||||
let mut detail = format::runtime(e.runtime);
|
||||
if let Some(date) = e.air_date.as_deref().filter(|d| d.len() >= 10) {
|
||||
if !detail.is_empty() {
|
||||
detail.push_str(" · ");
|
||||
}
|
||||
detail.push_str(&date[..10].replace('-', ". "));
|
||||
detail.push('.');
|
||||
}
|
||||
Episode {
|
||||
number: e.episode,
|
||||
title: e.name.clone().unwrap_or_else(|| format!("{}. rész", e.episode)).into(),
|
||||
detail: detail.into(),
|
||||
image: old.get(i).filter(|o| o.number == e.episode).map(|o| o.image.clone()).unwrap_or_default(),
|
||||
progress,
|
||||
watched,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
d.ep_model.set_vec(eps);
|
||||
drop(st);
|
||||
sync(c);
|
||||
}
|
||||
|
||||
fn load_stills(c: &Controller) {
|
||||
let px = c.px();
|
||||
let (wants, model) = {
|
||||
let st = c.state.borrow();
|
||||
let Some(d) = st.detail.as_ref() else { return };
|
||||
let api = &st.api;
|
||||
let wants: Vec<(usize, i32, String)> = d
|
||||
.episodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, e)| e.still.as_deref().map(|s| (i, e.episode, api.image(Some(s), false))))
|
||||
.collect();
|
||||
(wants, d.ep_model.clone())
|
||||
};
|
||||
for (i, number, url) in wants {
|
||||
let model = model.clone();
|
||||
c.images.load(&url, ((384.0 * px * 1.1) as u32, (216.0 * px * 1.1) as u32), move |img| {
|
||||
if let Some(mut e) = model.row_data(i) {
|
||||
if e.number == number {
|
||||
e.image = img;
|
||||
model.set_row_data(i, e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Focus state to Slint; the overview follows the focused episode.
|
||||
fn sync(c: &Controller) {
|
||||
let Some(ui) = c.ui() else { return };
|
||||
let st = c.state.borrow();
|
||||
let Some(d) = st.detail.as_ref() else { return };
|
||||
ui.set_detail_area(d.area);
|
||||
ui.set_detail_button(d.button);
|
||||
ui.set_detail_episode(d.episode as i32);
|
||||
ui.set_detail_season_focus(d.season_focus as i32);
|
||||
let overview = d.data.as_ref().and_then(|t| t.summary.overview.clone()).unwrap_or_else(|| d.item.overview.clone());
|
||||
match (d.area, d.episodes.get(d.episode)) {
|
||||
(1, Some(e)) => {
|
||||
let name = e.name.clone().unwrap_or_default();
|
||||
ui.set_detail_overview(format!("{} {}\n{}", format::episode_code(e.season, e.episode), name, e.overview.clone().unwrap_or_default()).into());
|
||||
}
|
||||
_ => ui.set_detail_overview(overview.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Back from the player: progress changed.
|
||||
pub fn returned(c: &Controller) {
|
||||
let Some((kind, id, generation, item)) =
|
||||
c.state.borrow().detail.as_ref().map(|d| (d.item.kind, d.item.id.clone(), d.generation, d.item.clone()))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
show_backdrop(c, &item);
|
||||
let api = c.api();
|
||||
let k = c.clone();
|
||||
task::spawn(
|
||||
move || api.progress(kind, &id),
|
||||
move |r| {
|
||||
if let Ok(p) = r {
|
||||
if let Some(d) = k.state.borrow_mut().detail.as_mut().filter(|d| d.generation == generation) {
|
||||
d.progress = p;
|
||||
}
|
||||
refresh(&k);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// The episode after `ep` of the open series, if any (for the player).
|
||||
pub fn next_after(c: &Controller, ep: (i32, i32)) -> Option<(i32, i32)> {
|
||||
let st = c.state.borrow();
|
||||
let d = st.detail.as_ref()?;
|
||||
next_episode(seasons_of(d), &d.episodes, d.season, ep.0, ep.1)
|
||||
}
|
||||
|
||||
/// The name of an episode of the shown season, if known.
|
||||
pub fn episode_name(c: &Controller, ep: (i32, i32)) -> String {
|
||||
let st = c.state.borrow();
|
||||
st.detail
|
||||
.as_ref()
|
||||
.and_then(|d| d.episodes.iter().find(|e| e.season == ep.0 && e.episode == ep.1))
|
||||
.and_then(|e| e.name.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn play(c: &Controller, ep: Option<(i32, i32)>, resume: f64) {
|
||||
let req = {
|
||||
let st = c.state.borrow();
|
||||
let Some(d) = st.detail.as_ref() else { return };
|
||||
let next = ep.and_then(|e| next_episode(seasons_of(d), &d.episodes, d.season, e.0, e.1));
|
||||
player::Request {
|
||||
kind: d.item.kind,
|
||||
id: d.item.id.clone(),
|
||||
title: d.item.title.clone(),
|
||||
ep,
|
||||
episode_name: String::new(),
|
||||
resume,
|
||||
backdrop: d.item.backdrop.clone(),
|
||||
next,
|
||||
}
|
||||
};
|
||||
let req = player::Request { episode_name: ep.map(|e| episode_name(c, e)).unwrap_or_default(), ..req };
|
||||
player::play(c, req);
|
||||
}
|
||||
|
||||
pub fn key(c: &Controller, a: Action, _repeat: bool) {
|
||||
enum Then {
|
||||
Sync,
|
||||
Pop,
|
||||
Play(Option<(i32, i32)>, f64),
|
||||
ToggleList,
|
||||
Season(i32),
|
||||
}
|
||||
let then = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let Some(d) = st.detail.as_mut() else { return };
|
||||
let series = d.item.kind == MediaType::Tv;
|
||||
let buttons = if series && d.data.is_some() { 3 } else { 2 };
|
||||
match (d.area, a) {
|
||||
(0, Action::Left) => {
|
||||
d.button = (d.button - 1).max(0);
|
||||
Then::Sync
|
||||
}
|
||||
(0, Action::Right) => {
|
||||
d.button = (d.button + 1).min(buttons - 1);
|
||||
Then::Sync
|
||||
}
|
||||
(0, Action::Down) if series && !d.episodes.is_empty() => {
|
||||
d.area = 1;
|
||||
Then::Sync
|
||||
}
|
||||
(0, Action::Ok | Action::PlayPause) => match d.button {
|
||||
0 if d.data.is_some() || d.item.kind == MediaType::Movie => {
|
||||
let (ep, _, resume) = target(d);
|
||||
Then::Play(ep, resume)
|
||||
}
|
||||
1 => Then::ToggleList,
|
||||
2 => {
|
||||
let seasons = seasons_of(d);
|
||||
d.season_focus = seasons.iter().position(|s| s.number == d.season).unwrap_or(0);
|
||||
d.area = 2;
|
||||
Then::Sync
|
||||
}
|
||||
_ => Then::Sync,
|
||||
},
|
||||
(0, Action::Back) => Then::Pop,
|
||||
(1, Action::Left) => {
|
||||
d.episode = d.episode.saturating_sub(1);
|
||||
Then::Sync
|
||||
}
|
||||
(1, Action::Right) => {
|
||||
d.episode = (d.episode + 1).min(d.episodes.len().saturating_sub(1));
|
||||
Then::Sync
|
||||
}
|
||||
(1, Action::Up | Action::Back) => {
|
||||
d.area = 0;
|
||||
Then::Sync
|
||||
}
|
||||
(1, Action::Ok | Action::PlayPause) => match d.episodes.get(d.episode) {
|
||||
Some(e) => {
|
||||
let p = d.progress.iter().find(|p| p.season == e.season && p.episode == e.episode);
|
||||
let resume = p.filter(|p| !p.completed && p.position > 60.0).map(|p| (p.position - 3.0).max(0.0)).unwrap_or(0.0);
|
||||
Then::Play(Some((e.season, e.episode)), resume)
|
||||
}
|
||||
None => Then::Sync,
|
||||
},
|
||||
(2, Action::Up) => {
|
||||
d.season_focus = d.season_focus.saturating_sub(1);
|
||||
Then::Sync
|
||||
}
|
||||
(2, Action::Down) => {
|
||||
d.season_focus = (d.season_focus + 1).min(seasons_of(d).len().saturating_sub(1));
|
||||
Then::Sync
|
||||
}
|
||||
(2, Action::Ok) => match seasons_of(d).get(d.season_focus).map(|s| s.number) {
|
||||
Some(n) => {
|
||||
d.area = 0;
|
||||
Then::Season(n)
|
||||
}
|
||||
None => Then::Sync,
|
||||
},
|
||||
(2, Action::Back | Action::Left | Action::Right) => {
|
||||
d.area = 0;
|
||||
Then::Sync
|
||||
}
|
||||
_ => Then::Sync,
|
||||
}
|
||||
};
|
||||
match then {
|
||||
Then::Sync => sync(c),
|
||||
Then::Pop => {
|
||||
c.pop();
|
||||
}
|
||||
Then::Play(ep, resume) => play(c, ep, resume),
|
||||
Then::ToggleList => {
|
||||
let (kind, id, on) = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let Some(d) = st.detail.as_mut() else { return };
|
||||
d.listed = !d.listed;
|
||||
(d.item.kind, d.item.id.clone(), d.listed)
|
||||
};
|
||||
if let Some(ui) = c.ui() {
|
||||
ui.set_detail_listed(on);
|
||||
}
|
||||
let api = c.api();
|
||||
task::background("my list", move || api.set_listed(kind, &id, on));
|
||||
}
|
||||
Then::Season(n) => {
|
||||
let generation = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let Some(d) = st.detail.as_mut() else { return };
|
||||
if d.season == n {
|
||||
0
|
||||
} else {
|
||||
d.season = n;
|
||||
d.episodes.clear();
|
||||
d.episode = 0;
|
||||
d.ep_model.set_vec(Vec::new());
|
||||
d.generation
|
||||
}
|
||||
};
|
||||
refresh(c);
|
||||
if generation > 0 {
|
||||
load_season(c, generation);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn season(n: i32, count: i32) -> SeasonSummary {
|
||||
SeasonSummary { number: n, name: String::new(), episode_count: count, aired_count: Some(count) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_episodes() {
|
||||
let seasons = [season(1, 3), season(2, 2)];
|
||||
assert_eq!(next_episode(&seasons, &[], 1, 1, 2), Some((1, 3)));
|
||||
assert_eq!(next_episode(&seasons, &[], 1, 1, 3), Some((2, 1)));
|
||||
assert_eq!(next_episode(&seasons, &[], 1, 2, 2), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn today_looks_like_a_date() {
|
||||
let t = chrono_today();
|
||||
assert_eq!(t.len(), 10);
|
||||
assert!(t.starts_with("20"));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Texts for the screen (Hungarian), as in the Netflex web app.
|
||||
|
||||
use crate::api::TitleSummary;
|
||||
|
||||
/// 3725 -> "1:02:05", 65 -> "1:05".
|
||||
pub fn time(sec: f64) -> String {
|
||||
let s = if sec.is_finite() && sec > 0.0 { sec as u64 } else { 0 };
|
||||
@@ -28,23 +26,6 @@ pub fn episode_code(season: i32, episode: i32) -> String {
|
||||
format!("S{season:02}E{episode:02}")
|
||||
}
|
||||
|
||||
/// "Film · 2024 · IMDb 7.8 · Dráma, Krimi"
|
||||
pub fn meta(t: &TitleSummary, extra: &str) -> String {
|
||||
let mut parts: Vec<String> = vec![t.kind.label().to_string()];
|
||||
if let Some(y) = t.year_label.clone().or_else(|| t.year.map(|y| y.to_string())) {
|
||||
parts.push(y);
|
||||
}
|
||||
if !extra.is_empty() {
|
||||
parts.push(extra.to_string());
|
||||
}
|
||||
if let Some(r) = t.rating.filter(|r| *r > 0.0) {
|
||||
parts.push(format!("IMDb {r:.1}"));
|
||||
}
|
||||
if !t.genres.is_empty() {
|
||||
parts.push(t.genres.iter().take(3).map(|g| genre(g)).collect::<Vec<_>>().join(", "));
|
||||
}
|
||||
parts.join(" · ")
|
||||
}
|
||||
|
||||
/// Cinemeta's English genre names in Hungarian.
|
||||
pub fn genre(g: &str) -> String {
|
||||
|
||||
823
src/home.rs
823
src/home.rs
@@ -1,823 +0,0 @@
|
||||
//! Home and its tabs: Kezdőlap, Filmek, Sorozatok, Listám, Keresés.
|
||||
//!
|
||||
//! Every tab is rows of cards under a hero that shows the focused title; its
|
||||
//! artwork becomes the glass backdrop shortly after the focus settles.
|
||||
//! Pictures load only around the focus.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{ComponentHandle, Model, ModelRc, VecModel};
|
||||
|
||||
use crate::api::{self, Api, MediaType, TitleSummary};
|
||||
use crate::app::{Action, Controller, Screen};
|
||||
use crate::{App, Card, Row, detail, format, player, task};
|
||||
|
||||
pub const TABS: usize = 5;
|
||||
const SEARCH: usize = 4;
|
||||
/// Cards per row in grids (Listám, Keresés).
|
||||
const GRID: usize = 8;
|
||||
/// Genre rows fetched at a time (Filmek, Sorozatok).
|
||||
const GENRE_BATCH: usize = 3;
|
||||
|
||||
/// Where a "continue watching" card starts.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Resume {
|
||||
pub ep: Option<(i32, i32)>,
|
||||
pub position: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Item {
|
||||
pub kind: MediaType,
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub meta: String,
|
||||
pub overview: String,
|
||||
pub poster: String,
|
||||
pub backdrop: String,
|
||||
pub logo: String,
|
||||
pub resume: Option<Resume>,
|
||||
/// 0..1 watched (Folytatás), negative = no bar.
|
||||
pub progress: f32,
|
||||
}
|
||||
|
||||
impl Item {
|
||||
pub fn key(&self) -> String {
|
||||
format!("{}:{}", self.kind.key(), self.id)
|
||||
}
|
||||
|
||||
fn from_summary(api: &Api, t: TitleSummary) -> Item {
|
||||
Item {
|
||||
kind: t.kind,
|
||||
id: t.id.clone(),
|
||||
title: t.title.clone(),
|
||||
meta: format::meta(&t, ""),
|
||||
overview: t.overview.clone().unwrap_or_default(),
|
||||
poster: api.image(t.poster.as_deref(), false),
|
||||
backdrop: api.image(t.backdrop.as_deref(), false),
|
||||
logo: api.image(t.logo.as_deref(), false),
|
||||
resume: None,
|
||||
progress: -1.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn card(&self) -> Card {
|
||||
Card { key: self.key().into(), title: self.title.clone().into(), image: Default::default(), progress: self.progress, badge: "".into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Continuation of a row (more pages on scroll).
|
||||
#[derive(Debug, Clone)]
|
||||
enum More {
|
||||
No,
|
||||
Browse { kind: MediaType, genre: Option<String>, cursor: Option<String>, page: u32 },
|
||||
}
|
||||
|
||||
struct RowData {
|
||||
title: String,
|
||||
landscape: bool,
|
||||
items: Vec<Item>,
|
||||
model: Rc<VecModel<Card>>,
|
||||
col: usize,
|
||||
requested: HashSet<usize>,
|
||||
more: More,
|
||||
loading_more: bool,
|
||||
}
|
||||
|
||||
impl RowData {
|
||||
fn new(title: &str, landscape: bool, items: Vec<Item>, more: More) -> RowData {
|
||||
let model = Rc::new(VecModel::from(items.iter().map(Item::card).collect::<Vec<_>>()));
|
||||
RowData { title: title.into(), landscape, items, model, col: 0, requested: HashSet::new(), more, loading_more: false }
|
||||
}
|
||||
|
||||
fn slint(&self) -> Row {
|
||||
Row { title: self.title.clone().into(), landscape: self.landscape, col: self.col as i32, cards: ModelRc::from(self.model.clone()) }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Home {
|
||||
tab: usize,
|
||||
nav: bool,
|
||||
rows: Vec<RowData>,
|
||||
row: usize,
|
||||
model: Rc<VecModel<Row>>,
|
||||
/// Bumped on every tab load: late answers for an old tab are dropped.
|
||||
generation: u64,
|
||||
genres: Vec<api::Genre>,
|
||||
next_genre: usize,
|
||||
loading_genres: bool,
|
||||
/// Search tab: the keyboard has the focus.
|
||||
kb: bool,
|
||||
query: String,
|
||||
searched: String,
|
||||
search_timer: slint::Timer,
|
||||
hero_timer: slint::Timer,
|
||||
/// Poster colours (for the backdrop palette when a title has no artwork).
|
||||
colours: Rc<RefCell<HashMap<String, slint::Color>>>,
|
||||
/// The title whose artwork is the backdrop now.
|
||||
backdrop_key: String,
|
||||
/// Focus to put back when the reloaded rows arrive (row, column).
|
||||
restore: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl Default for Home {
|
||||
fn default() -> Self {
|
||||
Home {
|
||||
tab: 0,
|
||||
nav: false,
|
||||
rows: Vec::new(),
|
||||
row: 0,
|
||||
model: Rc::new(VecModel::default()),
|
||||
generation: 0,
|
||||
genres: Vec::new(),
|
||||
next_genre: 0,
|
||||
loading_genres: false,
|
||||
kb: true,
|
||||
query: String::new(),
|
||||
searched: String::new(),
|
||||
search_timer: slint::Timer::default(),
|
||||
hero_timer: slint::Timer::default(),
|
||||
colours: Rc::default(),
|
||||
backdrop_key: String::new(),
|
||||
restore: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wire(c: &Controller, ui: &App) {
|
||||
ui.set_home_rows(ModelRc::from(c.state.borrow().home.model.clone()));
|
||||
let k = c.clone();
|
||||
ui.on_search_submitted(move |q| search_now(&k, q.to_string()));
|
||||
let k = c.clone();
|
||||
ui.on_search_changed(move |q| search_soon(&k, q.to_string()));
|
||||
let k = c.clone();
|
||||
ui.on_search_exit_down(move || {
|
||||
let has = !k.state.borrow().home.rows.is_empty();
|
||||
if has {
|
||||
set_kb(&k, false);
|
||||
}
|
||||
});
|
||||
let k = c.clone();
|
||||
ui.on_search_exit_up(move || {
|
||||
set_kb(&k, false);
|
||||
let mut st = k.state.borrow_mut();
|
||||
st.home.nav = true;
|
||||
drop(st);
|
||||
sync(&k);
|
||||
});
|
||||
let k = c.clone();
|
||||
ui.on_search_cancelled(move || {
|
||||
k.state.borrow_mut().home.nav = true;
|
||||
set_kb(&k, false);
|
||||
sync(&k);
|
||||
});
|
||||
}
|
||||
|
||||
/// Shows home with `tab` (clears the Back stack: home is the root).
|
||||
pub fn open(c: &Controller, tab: usize) {
|
||||
c.state.borrow_mut().back.clear();
|
||||
c.show(Screen::Home);
|
||||
load_tab(c, tab);
|
||||
}
|
||||
|
||||
/// Back from a details page or the player: refresh what may have changed.
|
||||
pub fn returned(c: &Controller) {
|
||||
let tab = c.state.borrow().home.tab;
|
||||
{
|
||||
c.state.borrow_mut().home.backdrop_key.clear();
|
||||
}
|
||||
if tab == 0 || tab == 3 {
|
||||
reload_keeping_focus(c);
|
||||
} else {
|
||||
focus_changed(c, true);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_kb(c: &Controller, on: bool) {
|
||||
c.state.borrow_mut().home.kb = on;
|
||||
if let Some(ui) = c.ui() {
|
||||
ui.set_home_kb_focused(on);
|
||||
}
|
||||
focus_changed(c, false);
|
||||
}
|
||||
|
||||
fn load_tab(c: &Controller, tab: usize) {
|
||||
let (api, generation) = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let h = &mut st.home;
|
||||
h.tab = tab;
|
||||
h.generation += 1;
|
||||
h.rows.clear();
|
||||
h.row = 0;
|
||||
h.model.set_vec(Vec::new());
|
||||
h.genres.clear();
|
||||
h.next_genre = 0;
|
||||
h.loading_genres = false;
|
||||
h.backdrop_key.clear();
|
||||
if tab == SEARCH {
|
||||
h.kb = true;
|
||||
h.nav = false;
|
||||
}
|
||||
let generation = h.generation;
|
||||
(st.api.clone(), generation)
|
||||
};
|
||||
c.images.cancel_pending();
|
||||
if let Some(ui) = c.ui() {
|
||||
ui.set_home_tab(tab as i32);
|
||||
ui.set_home_row(0);
|
||||
ui.set_home_kb_focused(tab == SEARCH);
|
||||
ui.set_home_status("".into());
|
||||
ui.set_home_busy(tab != SEARCH);
|
||||
ui.set_home_hero_title("".into());
|
||||
ui.set_home_hero_meta("".into());
|
||||
ui.set_home_hero_overview("".into());
|
||||
ui.set_home_hero_logo(Default::default());
|
||||
if tab == SEARCH {
|
||||
ui.invoke_home_kb_reset();
|
||||
ui.set_home_query("".into());
|
||||
}
|
||||
}
|
||||
if tab == SEARCH {
|
||||
let mut st = c.state.borrow_mut();
|
||||
st.home.query.clear();
|
||||
st.home.searched.clear();
|
||||
drop(st);
|
||||
c.glass.set_backdrop(None);
|
||||
sync(c);
|
||||
return;
|
||||
}
|
||||
let c2 = c.clone();
|
||||
match tab {
|
||||
0 => task::spawn(
|
||||
move || api.home().map(|h| (api.clone(), h)),
|
||||
move |r| match r {
|
||||
Ok((api, h)) => {
|
||||
let mut rows = Vec::new();
|
||||
if !h.continue_watching.is_empty() {
|
||||
let items: Vec<Item> = h
|
||||
.continue_watching
|
||||
.into_iter()
|
||||
.map(|ci| {
|
||||
let mut it = Item::from_summary(&api, ci.title);
|
||||
let ep = ci.season.zip(ci.episode).filter(|(s, _)| *s > 0);
|
||||
if let Some((s, e)) = ep {
|
||||
it.meta = format!("{} · {}", format::episode_code(s, e), it.meta);
|
||||
}
|
||||
// Landscape artwork: the backdrop.
|
||||
it.poster = if it.backdrop.is_empty() { it.poster.clone() } else { it.backdrop.clone() };
|
||||
it.resume = Some(Resume { ep, position: ci.position });
|
||||
it.progress = ci.duration.filter(|d| *d > 0.0).map(|d| (ci.position / d) as f32).unwrap_or(-1.0);
|
||||
it
|
||||
})
|
||||
.collect();
|
||||
rows.push(RowData::new("Folytatás", true, items, More::No));
|
||||
}
|
||||
for r in h.rows {
|
||||
let items = r.items.into_iter().map(|t| Item::from_summary(&api, t)).collect();
|
||||
rows.push(RowData::new(&r.title, false, items, More::No));
|
||||
}
|
||||
set_rows(&c2, generation, rows, "");
|
||||
}
|
||||
Err(e) => failed(&c2, generation, e),
|
||||
},
|
||||
),
|
||||
1 | 2 => {
|
||||
let kind = if tab == 1 { MediaType::Movie } else { MediaType::Tv };
|
||||
task::spawn(
|
||||
move || -> anyhow::Result<_> {
|
||||
let genres = api.genres(kind).unwrap_or_default();
|
||||
let popular = api.browse(kind, None, None, 1)?;
|
||||
let first: Vec<_> = genres.iter().take(GENRE_BATCH).map(|g| (g.clone(), api.browse(kind, Some(&g.id), None, 1))).collect();
|
||||
Ok((api, genres, popular, first))
|
||||
},
|
||||
move |r| match r {
|
||||
Ok((api, genres, popular, first)) => {
|
||||
let mut rows = vec![RowData::new(
|
||||
"Népszerű",
|
||||
false,
|
||||
popular.items.into_iter().map(|t| Item::from_summary(&api, t)).collect(),
|
||||
More::Browse { kind, genre: None, cursor: popular.cursor, page: if popular.has_more { 2 } else { 0 } },
|
||||
)];
|
||||
for (g, page) in first {
|
||||
if let Ok(p) = page {
|
||||
if p.items.is_empty() {
|
||||
continue;
|
||||
}
|
||||
rows.push(RowData::new(
|
||||
&g.name,
|
||||
false,
|
||||
p.items.into_iter().map(|t| Item::from_summary(&api, t)).collect(),
|
||||
More::Browse { kind, genre: Some(g.id.clone()), cursor: p.cursor, page: if p.has_more { 2 } else { 0 } },
|
||||
));
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut st = c2.state.borrow_mut();
|
||||
if st.home.generation == generation {
|
||||
st.home.next_genre = GENRE_BATCH.min(genres.len());
|
||||
st.home.genres = genres;
|
||||
}
|
||||
}
|
||||
set_rows(&c2, generation, rows, "");
|
||||
}
|
||||
Err(e) => failed(&c2, generation, e),
|
||||
},
|
||||
);
|
||||
}
|
||||
_ => task::spawn(
|
||||
move || api.my_list().map(|l| (api.clone(), l)),
|
||||
move |r| match r {
|
||||
Ok((api, list)) => {
|
||||
let items: Vec<Item> = list.into_iter().map(|l| Item::from_summary(&api, l.title)).collect();
|
||||
let rows = grid_rows("Listám", items);
|
||||
set_rows(&c2, generation, rows, "A listád üres. Egy film vagy sorozat adatlapján a Listám gombbal adhatsz hozzá.");
|
||||
}
|
||||
Err(e) => failed(&c2, generation, e),
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn grid_rows(title: &str, items: Vec<Item>) -> Vec<RowData> {
|
||||
let mut rows = Vec::new();
|
||||
let mut it = items.into_iter().peekable();
|
||||
while it.peek().is_some() {
|
||||
let chunk: Vec<Item> = it.by_ref().take(GRID).collect();
|
||||
rows.push(RowData::new(if rows.is_empty() { title } else { "" }, false, chunk, More::No));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn failed(c: &Controller, generation: u64, e: anyhow::Error) {
|
||||
if api::is_unauthenticated(&e) {
|
||||
return c.signed_out();
|
||||
}
|
||||
if c.state.borrow().home.generation != generation {
|
||||
return;
|
||||
}
|
||||
log::warn!("home: {e:#}");
|
||||
if let Some(ui) = c.ui() {
|
||||
ui.set_home_busy(false);
|
||||
ui.set_home_status(format!("{}\nOK: újra", api::describe(&e)).into());
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the tab's rows (when the answer is for the current tab).
|
||||
fn set_rows(c: &Controller, generation: u64, rows: Vec<RowData>, empty: &str) {
|
||||
{
|
||||
let mut st = c.state.borrow_mut();
|
||||
let h = &mut st.home;
|
||||
if h.generation != generation {
|
||||
return;
|
||||
}
|
||||
let mut rows = rows;
|
||||
if let Some((row, col)) = h.restore.take() {
|
||||
if !rows.is_empty() {
|
||||
h.row = row.min(rows.len() - 1);
|
||||
let r = &mut rows[h.row];
|
||||
r.col = col.min(r.items.len().saturating_sub(1));
|
||||
}
|
||||
}
|
||||
h.model.set_vec(rows.iter().map(RowData::slint).collect::<Vec<_>>());
|
||||
h.rows = rows;
|
||||
h.row = h.row.min(h.rows.len().saturating_sub(1));
|
||||
}
|
||||
let n = c.state.borrow().home.rows.len();
|
||||
if let Some(ui) = c.ui() {
|
||||
ui.set_home_busy(false);
|
||||
ui.set_home_status(if n == 0 { empty.into() } else { "".into() });
|
||||
}
|
||||
focus_changed(c, true);
|
||||
}
|
||||
|
||||
fn reload_keeping_focus(c: &Controller) {
|
||||
let (tab, pos) = {
|
||||
let st = c.state.borrow();
|
||||
let h = &st.home;
|
||||
(h.tab, (h.row, h.rows.get(h.row).map(|r| r.col).unwrap_or(0)))
|
||||
};
|
||||
load_tab(c, tab);
|
||||
c.state.borrow_mut().home.restore = Some(pos);
|
||||
}
|
||||
|
||||
// ---- search ----
|
||||
|
||||
fn search_soon(c: &Controller, q: String) {
|
||||
let k = c.clone();
|
||||
let mut st = c.state.borrow_mut();
|
||||
st.home.query = q.clone();
|
||||
st.home.search_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(650), move || search_now(&k, q.clone()));
|
||||
}
|
||||
|
||||
fn search_now(c: &Controller, q: String) {
|
||||
let q = q.trim().to_string();
|
||||
let (api, generation) = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
if st.home.tab != SEARCH || q.chars().count() < 2 || q == st.home.searched {
|
||||
return;
|
||||
}
|
||||
st.home.searched = q.clone();
|
||||
(st.api.clone(), st.home.generation)
|
||||
};
|
||||
if let Some(ui) = c.ui() {
|
||||
ui.set_home_busy(true);
|
||||
ui.set_home_status("".into());
|
||||
}
|
||||
let c2 = c.clone();
|
||||
task::spawn(
|
||||
move || api.search(&q).map(|p| (api.clone(), p, q)),
|
||||
move |r| match r {
|
||||
Ok((api, page, q)) => {
|
||||
if c2.state.borrow().home.searched != q {
|
||||
return;
|
||||
}
|
||||
let items = page.items.into_iter().map(|t| Item::from_summary(&api, t)).collect();
|
||||
let rows = grid_rows("Találatok", items);
|
||||
c2.state.borrow_mut().home.row = 0;
|
||||
set_rows(&c2, generation, rows, "Nincs találat.");
|
||||
}
|
||||
Err(e) => failed(&c2, generation, e),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ---- keys ----
|
||||
|
||||
pub fn key(c: &Controller, a: Action, _repeat: bool) {
|
||||
enum Then {
|
||||
Nothing,
|
||||
Tab(usize),
|
||||
Open(Item),
|
||||
Quit,
|
||||
Keyboard,
|
||||
Retry,
|
||||
}
|
||||
let then = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let h = &mut st.home;
|
||||
let n_rows = h.rows.len();
|
||||
if h.nav {
|
||||
match a {
|
||||
Action::Left if h.tab > 0 => Then::Tab(h.tab - 1),
|
||||
Action::Right if h.tab + 1 < TABS => Then::Tab(h.tab + 1),
|
||||
Action::Down | Action::Ok => {
|
||||
if h.tab == SEARCH {
|
||||
h.nav = false;
|
||||
Then::Keyboard
|
||||
} else if n_rows > 0 {
|
||||
h.nav = false;
|
||||
Then::Nothing
|
||||
} else if a == Action::Ok {
|
||||
Then::Retry
|
||||
} else {
|
||||
Then::Nothing
|
||||
}
|
||||
}
|
||||
Action::Back if h.tab != 0 => Then::Tab(0),
|
||||
Action::Back => Then::Quit,
|
||||
_ => Then::Nothing,
|
||||
}
|
||||
} else if n_rows == 0 {
|
||||
match a {
|
||||
Action::Up | Action::Back => {
|
||||
h.nav = true;
|
||||
Then::Nothing
|
||||
}
|
||||
Action::Ok => Then::Retry,
|
||||
_ => Then::Nothing,
|
||||
}
|
||||
} else {
|
||||
let row = &mut h.rows[h.row];
|
||||
match a {
|
||||
Action::Left => {
|
||||
row.col = row.col.saturating_sub(1);
|
||||
Then::Nothing
|
||||
}
|
||||
Action::Right => {
|
||||
if row.col + 1 < row.items.len() {
|
||||
row.col += 1;
|
||||
}
|
||||
Then::Nothing
|
||||
}
|
||||
Action::Up if h.row > 0 => {
|
||||
h.row -= 1;
|
||||
Then::Nothing
|
||||
}
|
||||
Action::Up if h.tab == SEARCH => Then::Keyboard,
|
||||
Action::Up => {
|
||||
h.nav = true;
|
||||
Then::Nothing
|
||||
}
|
||||
Action::Down => {
|
||||
if h.row + 1 < n_rows {
|
||||
h.row += 1;
|
||||
// Grids keep the column; other rows remember their own.
|
||||
if h.tab >= 3 {
|
||||
let col = h.rows[h.row - 1].col;
|
||||
let next = &mut h.rows[h.row];
|
||||
next.col = col.min(next.items.len().saturating_sub(1));
|
||||
}
|
||||
}
|
||||
Then::Nothing
|
||||
}
|
||||
Action::Ok | Action::PlayPause => match row.items.get(row.col) {
|
||||
Some(it) => Then::Open(it.clone()),
|
||||
None => Then::Nothing,
|
||||
},
|
||||
Action::Back => {
|
||||
if h.tab == SEARCH {
|
||||
Then::Keyboard
|
||||
} else {
|
||||
h.nav = true;
|
||||
Then::Nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
match then {
|
||||
Then::Nothing => focus_changed(c, false),
|
||||
Then::Tab(t) => {
|
||||
c.state.borrow_mut().home.nav = true;
|
||||
load_tab(c, t);
|
||||
}
|
||||
Then::Keyboard => set_kb(c, true),
|
||||
Then::Retry => {
|
||||
let tab = c.state.borrow().home.tab;
|
||||
load_tab(c, tab);
|
||||
}
|
||||
Then::Quit => {
|
||||
let _ = slint::quit_event_loop();
|
||||
}
|
||||
Then::Open(it) => match it.resume {
|
||||
// "Folytatás" plays right away, where it stopped.
|
||||
Some(r) => player::play(
|
||||
c,
|
||||
player::Request {
|
||||
kind: it.kind,
|
||||
id: it.id.clone(),
|
||||
title: it.title.clone(),
|
||||
ep: r.ep,
|
||||
episode_name: String::new(),
|
||||
resume: (r.position - 3.0).max(0.0),
|
||||
backdrop: it.backdrop.clone(),
|
||||
next: None,
|
||||
},
|
||||
),
|
||||
None => detail::open(c, &it),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ---- focus, hero, pictures ----
|
||||
|
||||
/// After any focus change: Slint state, hero texts, the backdrop (soon),
|
||||
/// pictures around the focus, more rows / pages when near the end.
|
||||
pub fn focus_changed(c: &Controller, now: bool) {
|
||||
let Some(ui) = c.ui() else { return };
|
||||
let (focused, nav, kb, tab) = {
|
||||
let st = c.state.borrow();
|
||||
let h = &st.home;
|
||||
if h.row < h.rows.len() {
|
||||
// The remembered column is part of the row struct.
|
||||
let r = &h.rows[h.row];
|
||||
if let Some(mut row) = h.model.row_data(h.row) {
|
||||
if row.col != r.col as i32 {
|
||||
row.col = r.col as i32;
|
||||
h.model.set_row_data(h.row, row);
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.set_home_row(h.row as i32);
|
||||
ui.set_home_nav_focused(h.nav);
|
||||
let focused = h.rows.get(h.row).and_then(|r| r.items.get(r.col)).cloned();
|
||||
(focused, h.nav, h.kb, h.tab)
|
||||
};
|
||||
let _ = (nav, kb);
|
||||
|
||||
match &focused {
|
||||
Some(it) if tab != SEARCH => {
|
||||
ui.set_home_hero_title(it.title.clone().into());
|
||||
ui.set_home_hero_meta(it.meta.clone().into());
|
||||
ui.set_home_hero_overview(it.overview.clone().into());
|
||||
ui.set_home_hero_logo(Default::default());
|
||||
if !it.logo.is_empty() {
|
||||
let w = ui.as_weak();
|
||||
let key = it.key();
|
||||
let k = c.clone();
|
||||
let px = c.px();
|
||||
c.images.load(&it.logo, ((620.0 * px) as u32, (190.0 * px) as u32), move |img| {
|
||||
let still = {
|
||||
let st = k.state.borrow();
|
||||
let h = &st.home;
|
||||
h.rows.get(h.row).and_then(|r| r.items.get(r.col)).is_some_and(|f| f.key() == key)
|
||||
};
|
||||
if let (true, Some(ui)) = (still, w.upgrade()) {
|
||||
ui.set_home_hero_logo(img);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
schedule_backdrop(c, if now { 60 } else { 320 });
|
||||
ensure_images(c);
|
||||
maybe_load_more(c);
|
||||
}
|
||||
|
||||
fn schedule_backdrop(c: &Controller, ms: u64) {
|
||||
let k = c.clone();
|
||||
let st = c.state.borrow();
|
||||
st.home.hero_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(ms), move || apply_backdrop(&k));
|
||||
}
|
||||
|
||||
fn apply_backdrop(c: &Controller) {
|
||||
let (it, tab, colours) = {
|
||||
let st = c.state.borrow();
|
||||
if st.screen != Screen::Home {
|
||||
return;
|
||||
}
|
||||
let h = &st.home;
|
||||
(h.rows.get(h.row).and_then(|r| r.items.get(r.col)).cloned(), h.tab, h.colours.clone())
|
||||
};
|
||||
let Some(it) = it.filter(|_| tab != SEARCH) else {
|
||||
c.glass.set_backdrop(None);
|
||||
return;
|
||||
};
|
||||
let key = it.key();
|
||||
{
|
||||
let mut st = c.state.borrow_mut();
|
||||
if st.home.backdrop_key == key {
|
||||
return;
|
||||
}
|
||||
st.home.backdrop_key = key.clone();
|
||||
}
|
||||
if let Some(col) = colours.borrow().get(&key).copied() {
|
||||
c.glass.set_palette(sf_ui::Palette::from_color(col));
|
||||
}
|
||||
if it.backdrop.is_empty() {
|
||||
c.glass.set_backdrop(None);
|
||||
return;
|
||||
}
|
||||
let k = c.clone();
|
||||
let px = c.px();
|
||||
c.images.load_pixels(&it.backdrop, ((1920.0 * px) as u32, (1080.0 * px) as u32), move |pixels| {
|
||||
let still = k.state.borrow().home.backdrop_key == key && k.state.borrow().screen == Screen::Home;
|
||||
if still {
|
||||
k.glass.set_backdrop(Some(sf_ui::Backdrop::new(pixels.clone()).dim(0.3).fade_left(1.0).fade_bottom(1.0).align(0.6, 0.2)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn ensure_images(c: &Controller) {
|
||||
let px = c.px();
|
||||
struct Want {
|
||||
url: String,
|
||||
size: (u32, u32),
|
||||
model: Rc<VecModel<Card>>,
|
||||
index: usize,
|
||||
key: String,
|
||||
}
|
||||
let (wants, colours) = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let h = &mut st.home;
|
||||
let mut wants = Vec::new();
|
||||
let lo = h.row.saturating_sub(1);
|
||||
let hi = (h.row + 3).min(h.rows.len());
|
||||
for row in &mut h.rows[lo..hi] {
|
||||
let (cw, ch) = if row.landscape { (400.0, 225.0) } else { (196.0, 294.0) };
|
||||
let size = ((cw * px * 1.1) as u32, (ch * px * 1.1) as u32);
|
||||
let start = row.col.saturating_sub(3);
|
||||
let end = (row.col + 11).min(row.items.len());
|
||||
for i in start..end {
|
||||
if row.requested.insert(i) {
|
||||
let it = &row.items[i];
|
||||
if !it.poster.is_empty() {
|
||||
wants.push(Want { url: it.poster.clone(), size, model: row.model.clone(), index: i, key: it.key() });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(wants, h.colours.clone())
|
||||
};
|
||||
// No state borrow here: a cached picture calls back at once.
|
||||
for w in wants {
|
||||
let model = w.model;
|
||||
let colours = colours.clone();
|
||||
let (index, key) = (w.index, w.key);
|
||||
c.images.load_pixels(&w.url, w.size, move |pixels| {
|
||||
if let Some(mut card) = model.row_data(index) {
|
||||
if card.key.as_str() == key {
|
||||
card.image = slint::Image::from_rgba8(pixels.clone());
|
||||
model.set_row_data(index, card);
|
||||
}
|
||||
}
|
||||
colours.borrow_mut().entry(key).or_insert_with(|| sf_ui::images::average_color(pixels));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// More genre rows near the bottom, the next page near the end of a row.
|
||||
fn maybe_load_more(c: &Controller) {
|
||||
let (api, generation) = (c.api(), c.state.borrow().home.generation);
|
||||
// Genre rows.
|
||||
let next = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let h = &mut st.home;
|
||||
if (h.tab == 1 || h.tab == 2) && !h.loading_genres && h.row + 3 >= h.rows.len() && h.next_genre < h.genres.len() {
|
||||
h.loading_genres = true;
|
||||
let batch: Vec<api::Genre> = h.genres[h.next_genre..(h.next_genre + GENRE_BATCH).min(h.genres.len())].to_vec();
|
||||
h.next_genre += batch.len();
|
||||
Some((if h.tab == 1 { MediaType::Movie } else { MediaType::Tv }, batch))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some((kind, batch)) = next {
|
||||
let c2 = c.clone();
|
||||
let api2 = api.clone();
|
||||
task::spawn(
|
||||
move || batch.into_iter().map(|g| { let p = api2.browse(kind, Some(&g.id), None, 1); (g, p) }).collect::<Vec<_>>(),
|
||||
move |pages| {
|
||||
let mut st = c2.state.borrow_mut();
|
||||
let h = &mut st.home;
|
||||
if h.generation != generation {
|
||||
return;
|
||||
}
|
||||
h.loading_genres = false;
|
||||
for (g, p) in pages {
|
||||
let Ok(p) = p else { continue };
|
||||
if p.items.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let items = p.items.into_iter().map(|t| Item::from_summary(&api, t)).collect();
|
||||
let row = RowData::new(&g.name, false, items, More::Browse { kind, genre: Some(g.id), cursor: p.cursor, page: if p.has_more { 2 } else { 0 } });
|
||||
h.model.push(row.slint());
|
||||
h.rows.push(row);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Next page of the focused row.
|
||||
let page = {
|
||||
let mut st = c.state.borrow_mut();
|
||||
let h = &mut st.home;
|
||||
let ri = h.row;
|
||||
match h.rows.get_mut(ri) {
|
||||
Some(r) if !r.loading_more && r.col + 6 >= r.items.len() => match &r.more {
|
||||
More::Browse { kind, genre, cursor, page } if *page > 0 || cursor.is_some() => {
|
||||
r.loading_more = true;
|
||||
Some((ri, *kind, genre.clone(), cursor.clone(), *page))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if let Some((ri, kind, genre, cursor, page)) = page {
|
||||
let c2 = c.clone();
|
||||
let api2 = c.api();
|
||||
let g = genre.clone();
|
||||
task::spawn(
|
||||
move || api2.browse(kind, g.as_deref(), cursor.as_deref(), page).map(|p| (api2, p)),
|
||||
move |r| {
|
||||
let mut st = c2.state.borrow_mut();
|
||||
let h = &mut st.home;
|
||||
if h.generation != generation {
|
||||
return;
|
||||
}
|
||||
let Some(row) = h.rows.get_mut(ri) else { return };
|
||||
row.loading_more = false;
|
||||
match r {
|
||||
Ok((api, p)) => {
|
||||
let seen: HashSet<String> = row.items.iter().map(Item::key).collect();
|
||||
for t in p.items {
|
||||
let it = Item::from_summary(&api, t);
|
||||
if seen.contains(&it.key()) {
|
||||
continue;
|
||||
}
|
||||
row.model.push(it.card());
|
||||
row.items.push(it);
|
||||
}
|
||||
let next_page = if p.has_more { page + 1 } else { 0 };
|
||||
row.more = More::Browse { kind, genre: genre.clone(), cursor: p.cursor, page: next_page };
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("more: {e:#}");
|
||||
row.more = More::No;
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-sends the focus state to Slint (after nav changes).
|
||||
fn sync(c: &Controller) {
|
||||
focus_changed(c, false);
|
||||
}
|
||||
17
src/main.rs
17
src/main.rs
@@ -12,10 +12,10 @@
|
||||
mod api;
|
||||
mod app;
|
||||
mod config;
|
||||
mod detail;
|
||||
mod format;
|
||||
mod home;
|
||||
mod page;
|
||||
mod player;
|
||||
mod screens;
|
||||
mod task;
|
||||
|
||||
use slint::{ComponentHandle, Model};
|
||||
@@ -39,16 +39,17 @@ fn main() -> anyhow::Result<()> {
|
||||
|
||||
let glass = sf_ui::Glass::install(&ui, |ui, p| {
|
||||
p.extend(ui.get_glass_message().iter());
|
||||
p.extend(ui.get_glass_signin().iter());
|
||||
p.extend(ui.get_glass_signin_keyboard().iter());
|
||||
p.extend(ui.get_glass_home().iter());
|
||||
p.extend(ui.get_glass_home_keyboard().iter());
|
||||
p.extend(ui.get_glass_detail().iter());
|
||||
p.extend(ui.get_glass_detail_menu().iter());
|
||||
p.extend(ui.get_glass_page().iter());
|
||||
p.extend(ui.get_glass_page_keyboard().iter());
|
||||
p.extend(ui.get_glass_player().iter());
|
||||
p.extend(ui.get_glass_player_audio().iter());
|
||||
p.extend(ui.get_glass_player_subs().iter());
|
||||
p.extend(ui.get_glass_player_sync().iter());
|
||||
p.extend(ui.get_glass_player_quality().iter());
|
||||
p.extend(ui.get_glass_input().iter());
|
||||
p.extend(ui.get_glass_input_keyboard().iter());
|
||||
p.extend(ui.get_glass_select().iter());
|
||||
p.extend(ui.get_glass_toast().iter());
|
||||
})?;
|
||||
glass.set_palette(sf_ui::Palette::from_hex(["#ff4a3d", "#8c0b14", "#120305"]));
|
||||
|
||||
|
||||
44
src/page.rs
44
src/page.rs
@@ -17,8 +17,6 @@ use crate::{Card, Check, Chip, Line};
|
||||
|
||||
/// Width of the content on a page without the side list (design px).
|
||||
pub const CONTENT_W: f32 = 1728.0;
|
||||
/// Content left edge and width with the settings side list.
|
||||
pub const SIDE_X: f32 = 600.0;
|
||||
pub const SIDE_W: f32 = 1224.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -32,7 +30,6 @@ pub enum Kind {
|
||||
Item,
|
||||
Checks,
|
||||
Keyboard,
|
||||
Gap,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
@@ -47,7 +44,6 @@ impl Kind {
|
||||
Kind::Item => "item",
|
||||
Kind::Checks => "checks",
|
||||
Kind::Keyboard => "keyboard",
|
||||
Kind::Gap => "gap",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,8 +95,19 @@ impl Ch {
|
||||
if let Some(w) = self.w {
|
||||
return w;
|
||||
}
|
||||
// Onest 23/600: about 12.4 px per character; capitals are wider.
|
||||
let chars: f32 = self.text.chars().map(|c| if c.is_uppercase() { 15.5 } else { 12.4 }).sum();
|
||||
// Onest 23/600: about 13.4 px per character (measured on the TV
|
||||
// screenshots); capitals and wide letters more, narrow ones less.
|
||||
let chars: f32 = self
|
||||
.text
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'i' | 'l' | 'í' | 'j' | '.' | ',' | ':' | '·' | '(' | ')' | ' ' => 7.5,
|
||||
'm' | 'w' | 'M' | 'W' => 20.0,
|
||||
c if c.is_uppercase() || c.is_ascii_digit() => 16.0,
|
||||
_ => 13.4,
|
||||
})
|
||||
.sum::<f32>()
|
||||
+ 6.0;
|
||||
if self.text.is_empty() {
|
||||
return 64.0;
|
||||
}
|
||||
@@ -240,11 +247,6 @@ impl L {
|
||||
l.checks = checks;
|
||||
l
|
||||
}
|
||||
pub fn gap(h: f32) -> L {
|
||||
let mut l = L::new(format!("gap{h}"), Kind::Gap);
|
||||
l.h = Some(h);
|
||||
l
|
||||
}
|
||||
pub fn sub(mut self, s: impl Into<String>) -> L {
|
||||
self.subtitle = s.into();
|
||||
self
|
||||
@@ -254,14 +256,6 @@ impl L {
|
||||
self.style = "image".into();
|
||||
self
|
||||
}
|
||||
pub fn progress(mut self, p: f32) -> L {
|
||||
self.progress = p;
|
||||
self
|
||||
}
|
||||
pub fn tone(mut self, t: &str) -> L {
|
||||
self.tone = t.into();
|
||||
self
|
||||
}
|
||||
pub fn captions(mut self) -> L {
|
||||
self.captions = true;
|
||||
self
|
||||
@@ -456,13 +450,11 @@ fn layout(lines: &[L], side: bool) -> (Vec<Laid>, f32) {
|
||||
h
|
||||
}
|
||||
Kind::Keyboard => 540.0,
|
||||
Kind::Gap => 0.0,
|
||||
};
|
||||
let h = l.h.unwrap_or(h);
|
||||
out.push(Laid { y, h, x: x0 + l.indent, w: lw, chips });
|
||||
let next = lines.get(i + 1).map(|n| n.kind);
|
||||
let gap = match (l.kind, next) {
|
||||
(Kind::Gap, _) => 0.0,
|
||||
(Kind::Heading, _) => 14.0,
|
||||
(Kind::Cards, Some(Kind::Cards)) if l.grid => 18.0,
|
||||
(Kind::Item, Some(Kind::Item)) => 14.0,
|
||||
@@ -573,12 +565,6 @@ impl View {
|
||||
(l.id.clone(), item.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn focused_kind(&self) -> Option<Kind> {
|
||||
if self.focus != Focus::Line {
|
||||
return None;
|
||||
}
|
||||
self.lines.get(self.line).map(|l| l.kind)
|
||||
}
|
||||
|
||||
/// Center x of the focused element (for spatial up/down).
|
||||
fn focus_x(&self) -> f32 {
|
||||
@@ -887,10 +873,6 @@ impl View {
|
||||
None
|
||||
}
|
||||
|
||||
/// Replaces one card's picture (a backdrop loaded elsewhere...).
|
||||
pub fn line_index(&self, id: &str) -> Option<usize> {
|
||||
self.lines.iter().position(|l| l.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn card_size(style: &str) -> (f32, f32) {
|
||||
|
||||
1195
src/player.rs
1195
src/player.rs
File diff suppressed because it is too large
Load Diff
519
src/screens/anime_detail.rs
Normal file
519
src/screens/anime_detail.rs
Normal file
@@ -0,0 +1,519 @@
|
||||
//! An anime's page (the web app's pages/anime/AnimeDetail.tsx): hero,
|
||||
//! the franchise (seasons, movies, extras), episodes in pages of 50 with
|
||||
//! the nyaa releases, the release group chosen for this anime.
|
||||
|
||||
use std::any::Any;
|
||||
|
||||
use crate::api::{AnimeDetail as Detail, AnimeEpisodeMeta, AnimeEpisodes, AnimeProgressRow, AnimeSource, FranchiseEntry, ReleaseResolution};
|
||||
use crate::app::{Cx, Look, Screen};
|
||||
use crate::config;
|
||||
use crate::page::{C, Ch, Frame, Kind, L, Spec};
|
||||
use crate::screens::Load;
|
||||
use crate::{format, player};
|
||||
|
||||
const EPISODE_PAGE: i32 = 50;
|
||||
|
||||
pub struct AnimeDetail {
|
||||
id: i64,
|
||||
data: Load<Detail>,
|
||||
episodes: Load<AnimeEpisodes>,
|
||||
progress: Vec<AnimeProgressRow>,
|
||||
releases: Load<ReleaseResolution>,
|
||||
franchise: Vec<FranchiseEntry>,
|
||||
listed: bool,
|
||||
page: Option<i32>,
|
||||
open: Option<i32>,
|
||||
started: bool,
|
||||
}
|
||||
|
||||
/// The episode list from the detail when the episode endpoint has none.
|
||||
fn from_detail(d: &Detail) -> AnimeEpisodes {
|
||||
let movie = d.summary.format.as_deref() == Some("MOVIE");
|
||||
let total = if movie { Some(1) } else { d.summary.episodes };
|
||||
let aired = if movie {
|
||||
1
|
||||
} else if d.summary.status.as_deref() == Some("NOT_YET_RELEASED") {
|
||||
0
|
||||
} else if let Some(n) = &d.next_airing_episode {
|
||||
(n.episode - 1).max(0)
|
||||
} else if d.summary.status.as_deref() == Some("FINISHED") {
|
||||
total.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
AnimeEpisodes {
|
||||
aired,
|
||||
total,
|
||||
episodes: (1..=total.unwrap_or(aired)).map(|n| AnimeEpisodeMeta { number: n, title: None, overview: None, air_date: None, runtime: d.duration, image: None }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// "SubsPlease|1080" -> "SubsPlease 1080p"
|
||||
fn group_name(key: &str) -> String {
|
||||
let (g, r) = key.split_once('|').unwrap_or((key, "?"));
|
||||
if r == "?" { g.to_string() } else { format!("{g} {r}p") }
|
||||
}
|
||||
|
||||
impl AnimeDetail {
|
||||
pub fn new(id: i64) -> AnimeDetail {
|
||||
AnimeDetail {
|
||||
id,
|
||||
data: Load::Loading,
|
||||
episodes: Load::Loading,
|
||||
progress: Vec::new(),
|
||||
releases: Load::Loading,
|
||||
franchise: Vec::new(),
|
||||
listed: false,
|
||||
page: None,
|
||||
open: None,
|
||||
started: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn load(&mut self, cx: &Cx) {
|
||||
let (api, id) = (cx.api(), self.id);
|
||||
cx.spawn::<AnimeDetail, _>(
|
||||
move || {
|
||||
let d = api.anime_detail(id);
|
||||
let eps = api.anime_episodes(id);
|
||||
let p = api.anime_progress(id).unwrap_or_default();
|
||||
let lib = api.anime_library().unwrap_or_default();
|
||||
let fr = api.anime_franchise(id).unwrap_or_default();
|
||||
(d, eps, p, lib.iter().any(|i| i.anime.id == id && i.listed), fr)
|
||||
},
|
||||
|s, cx, (d, eps, p, listed, fr)| {
|
||||
s.data = Load::from(d, cx);
|
||||
s.episodes = match eps {
|
||||
Ok(e) if !e.episodes.is_empty() => Load::Ready(e),
|
||||
other => match s.data.ready() {
|
||||
Some(d) => Load::Ready(from_detail(d)),
|
||||
None => Load::from(other, cx),
|
||||
},
|
||||
};
|
||||
s.progress = p;
|
||||
s.listed = listed;
|
||||
s.franchise = fr;
|
||||
},
|
||||
);
|
||||
self.load_releases(cx, false);
|
||||
}
|
||||
|
||||
fn load_releases(&mut self, cx: &Cx, refresh: bool) {
|
||||
self.releases = Load::Loading;
|
||||
let (api, id) = (cx.api(), self.id);
|
||||
cx.spawn::<AnimeDetail, _>(move || api.anime_releases(id, refresh), |s, _cx, r| {
|
||||
s.releases = match r {
|
||||
Ok(r) => Load::Ready(r),
|
||||
Err(e) => Load::Failed(crate::api::describe(&e)),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
fn reload_progress(&mut self, cx: &Cx) {
|
||||
let (api, id) = (cx.api(), self.id);
|
||||
cx.spawn::<AnimeDetail, _>(move || api.anime_progress(id).unwrap_or_default(), |s, _cx, p| s.progress = p);
|
||||
}
|
||||
|
||||
fn movie(&self) -> bool {
|
||||
self.data.ready().is_some_and(|d| d.summary.format.as_deref() == Some("MOVIE"))
|
||||
}
|
||||
|
||||
fn aired(&self) -> i32 {
|
||||
self.episodes.ready().map(|e| e.aired).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Where Play goes (web: resumeTarget).
|
||||
fn target(&self) -> (i32, String) {
|
||||
let movie = self.movie();
|
||||
let latest = self.progress.iter().max_by_key(|p| p.episode);
|
||||
match latest {
|
||||
None => (1, "Lejátszás".into()),
|
||||
Some(l) if !l.completed => (l.episode, if movie { "Folytatás".into() } else { format!("Folytatás · {}. rész", l.episode) }),
|
||||
Some(l) if !movie && l.episode < self.aired() => (l.episode + 1, format!("Következő · {}. rész", l.episode + 1)),
|
||||
Some(l) => (if movie { 1 } else { l.episode }, "Újra".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn group(&self) -> Option<String> {
|
||||
let g = config::Local::load().anime_groups.get(&self.id.to_string()).cloned()?;
|
||||
let ok = self.releases.ready().is_none_or(|r| r.groups.iter().any(|x| x.key == g));
|
||||
ok.then_some(g)
|
||||
}
|
||||
|
||||
fn sources(&self, n: i32) -> Option<Vec<AnimeSource>> {
|
||||
self.releases.ready().map(|r| r.episodes.iter().find(|e| e.number == n).map(|e| e.sources.clone()).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn play(&self, cx: &Cx, episode: i32, nyaa: Option<i64>) {
|
||||
let name = self.data.ready().map(|d| d.summary.title.name()).unwrap_or_default();
|
||||
let banner = self.data.ready().and_then(|d| d.summary.banner_image.clone().or(d.summary.cover_image.clone()));
|
||||
let mut r = player::Request::anime(self.id, name, episode, banner);
|
||||
r.pinned = nyaa;
|
||||
cx.play(r);
|
||||
}
|
||||
}
|
||||
|
||||
fn entry_label(e: &FranchiseEntry) -> String {
|
||||
match e.season_number {
|
||||
Some(n) => {
|
||||
let part = match (e.part, e.part_end) {
|
||||
(Some(p), Some(end)) => format!(" · {p}–{end}. rész"),
|
||||
(Some(p), None) => format!(" · {p}. rész"),
|
||||
_ => String::new(),
|
||||
};
|
||||
format!("{n}. évad{part}")
|
||||
}
|
||||
None => {
|
||||
let f = format::anime_format(e.format.as_deref());
|
||||
if f.is_empty() { "Extra".into() } else { f }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Screen for AnimeDetail {
|
||||
fn spec(&mut self, cx: &Cx) -> Spec {
|
||||
if !self.started {
|
||||
self.started = true;
|
||||
self.load(cx);
|
||||
}
|
||||
let api = cx.api();
|
||||
let mut lines = Vec::new();
|
||||
let movie = self.movie();
|
||||
let aired = self.aired();
|
||||
|
||||
let mut hero = L::new("hero", Kind::Hero);
|
||||
if let Some(d) = self.data.ready() {
|
||||
let a = &d.summary;
|
||||
hero.title = a.title.name();
|
||||
let genres = a.genres.iter().map(|g| format::anime_genre(g)).collect::<Vec<_>>().join(" · ");
|
||||
hero.subtitle = [a.title.alt().unwrap_or_default(), genres].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
let mut meta: Vec<String> = Vec::new();
|
||||
if let Some(s) = a.average_score.filter(|s| *s > 0.0) {
|
||||
meta.push(format!("★ {}", format::anime_score(s)));
|
||||
}
|
||||
if let Some(m) = d.mal.as_ref().and_then(|m| m.score) {
|
||||
meta.push(format!("MAL {}", format!("{m:.2}").replace('.', ",")));
|
||||
}
|
||||
meta.push(format::anime_season(a.season.as_deref(), a.season_year));
|
||||
meta.push(format::anime_format(a.format.as_deref()));
|
||||
if !movie {
|
||||
if let Some(n) = a.episodes {
|
||||
meta.push(format!("{n} rész"));
|
||||
}
|
||||
}
|
||||
meta.push(format::runtime(d.duration));
|
||||
meta.push(format::anime_status(a.status.as_deref()));
|
||||
meta.extend(d.studios.first().cloned());
|
||||
hero.meta = meta.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
if let Some(n) = &d.next_airing_episode {
|
||||
let when = chrono_like(n.airing_at);
|
||||
hero.extra = format!("Új rész érkezik: {}. rész · {when}", n.episode);
|
||||
}
|
||||
hero.text = format::plain_text(d.description.as_deref().unwrap_or(""));
|
||||
let (_, label) = self.target();
|
||||
let none = !movie && aired == 0;
|
||||
hero.chips.push(Ch::new("play", if none { "Még nem jelent meg".to_string() } else { label }).icon("play").tone("primary").enabled(!none));
|
||||
hero.chips.push(Ch::new("list", if self.listed { "Listámon" } else { "Listám" }).icon(if self.listed { "check" } else { "plus" }).active(self.listed));
|
||||
} else {
|
||||
hero.chips.push(Ch::new("play", "Lejátszás").icon("play").tone("primary").enabled(false));
|
||||
}
|
||||
lines.push(hero);
|
||||
if let Some(st) = self.data.status("status") {
|
||||
lines.push(st);
|
||||
}
|
||||
if self.data.ready().is_some_and(|d| d.source.as_deref() == Some("kitsu")) {
|
||||
lines.push(L::text("kitsu", "Az AniList most nem érhető el, ezért a Kitsu adatait látod.", "warn"));
|
||||
}
|
||||
|
||||
// Franchise.
|
||||
if self.franchise.len() >= 2 {
|
||||
lines.push(L::heading("fr-h", "Évadok és kapcsolódó részek").sub(format!("{} rész a sorozatból", self.franchise.len())));
|
||||
let cards = self
|
||||
.franchise
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let mut c = C::new(format!("a:{}", e.id), e.title.name(), api.image(e.cover_image.as_deref(), false));
|
||||
c.caption = entry_label(e);
|
||||
c.detail = [e.season_year.map(|y| y.to_string()), e.episodes.filter(|_| e.format.as_deref() != Some("MOVIE")).map(|n| format!("{n} rész"))]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · ");
|
||||
if c.detail.is_empty() {
|
||||
c.detail = e.title.name();
|
||||
}
|
||||
c.current = e.id == self.id;
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
lines.push(L::cards("franchise", "", "season", cards).captions());
|
||||
}
|
||||
|
||||
// Episodes.
|
||||
let done: Vec<i32> = self.progress.iter().filter(|p| p.completed).map(|p| p.episode).collect();
|
||||
let eps: Vec<AnimeEpisodeMeta> = self.episodes.ready().map(|e| e.episodes.clone()).unwrap_or_default();
|
||||
let aired_list: Vec<i32> = eps.iter().filter(|e| movie || e.number <= aired).map(|e| e.number).collect();
|
||||
let all_done = !aired_list.is_empty() && aired_list.iter().all(|n| done.contains(n));
|
||||
let mut h = L::heading("eps-h", if movie { "Verziók" } else { "Epizódok" });
|
||||
if !movie && !aired_list.is_empty() {
|
||||
h.subtitle = format!("{} / {} rész megnézve", done.iter().filter(|n| aired_list.contains(n)).count(), aired_list.len());
|
||||
}
|
||||
lines.push(h);
|
||||
let group = self.group();
|
||||
let mut tools = Vec::new();
|
||||
if let Some(r) = self.releases.ready() {
|
||||
if !r.groups.is_empty() {
|
||||
let label = match &group {
|
||||
Some(g) => format!("Kiadás: {}", group_name(g)),
|
||||
None => format!("Kiadás: automatikus ({})", group_name(&r.groups[0].key)),
|
||||
};
|
||||
tools.push(Ch::new("group", label).icon("list").active(group.is_some()));
|
||||
}
|
||||
}
|
||||
if !matches!(self.releases, Load::Loading) {
|
||||
tools.push(Ch::new("refresh", "Kiadások újrakeresése").icon("refresh"));
|
||||
}
|
||||
if !movie && !aired_list.is_empty() {
|
||||
tools.push(Ch::new("all", if all_done { "Megnézettség törlése" } else { "Mind megnézve" }).icon("check").active(all_done));
|
||||
}
|
||||
if !tools.is_empty() {
|
||||
lines.push(L::chips("tools", "", tools));
|
||||
}
|
||||
match &self.releases {
|
||||
Load::Loading => lines.push(L::text("rel-loading", "Kiadások keresése a nyaa-n…", "caption")),
|
||||
Load::Failed(e) => lines.push(L::text("rel-error", format!("A nyaa most nem érhető el: {e}"), "bad")),
|
||||
Load::Ready(_) => {}
|
||||
}
|
||||
match &self.episodes {
|
||||
Load::Loading => lines.push(L::text("eps-loading", "Epizódok betöltése…", "caption")),
|
||||
Load::Failed(e) => lines.push(L::text("eps-error", format!("Az epizódadatok most nem érhetők el: {e}"), "warn")),
|
||||
Load::Ready(_) if eps.is_empty() => lines.push(L::text("eps-none", "Ehhez az animéhez még nincs epizód.", "label")),
|
||||
Load::Ready(_) => {
|
||||
let pages = (eps.len() as i32 + EPISODE_PAGE - 1) / EPISODE_PAGE;
|
||||
let next = self.target().0;
|
||||
let page = self.page.unwrap_or(((next - 1).max(0) / EPISODE_PAGE).min(pages - 1)).clamp(0, (pages - 1).max(0));
|
||||
if pages > 1 {
|
||||
let chips = (0..pages).map(|i| Ch::new(format!("p{i}"), format!("{}–{}", i * EPISODE_PAGE + 1, ((i + 1) * EPISODE_PAGE).min(eps.len() as i32))).active(i == page)).collect();
|
||||
lines.push(L::chips("pages", "", chips));
|
||||
}
|
||||
let shown = if pages > 1 { eps.iter().skip((page * EPISODE_PAGE) as usize).take(EPISODE_PAGE as usize).cloned().collect() } else { eps.clone() };
|
||||
let banner = self.data.ready().and_then(|d| d.summary.banner_image.clone());
|
||||
let name = self.data.ready().map(|d| d.summary.title.name()).unwrap_or_default();
|
||||
for e in shown {
|
||||
let is_aired = movie || e.number <= aired;
|
||||
let p = self.progress.iter().find(|p| p.episode == e.number);
|
||||
let completed = p.is_some_and(|p| p.completed);
|
||||
let mut meta = vec![if movie { "Film".into() } else { format::anime_episode(e.number) }];
|
||||
let rt = format::runtime(e.runtime);
|
||||
if !rt.is_empty() {
|
||||
meta.push(rt);
|
||||
}
|
||||
if is_aired {
|
||||
if let Some(a) = &e.air_date {
|
||||
meta.push(format::date(Some(a)));
|
||||
}
|
||||
} else {
|
||||
meta.push(match &e.air_date {
|
||||
Some(a) => format!("érkezik: {}", format::date(Some(a))),
|
||||
None => "még nem jelent meg".into(),
|
||||
});
|
||||
}
|
||||
if completed {
|
||||
meta.push("megnézted".into());
|
||||
}
|
||||
let sources = self.sources(e.number);
|
||||
let missing = is_aired && sources.as_ref().is_some_and(|s| s.is_empty());
|
||||
let in_group = match (&group, &sources) {
|
||||
(Some(g), Some(s)) => s.iter().any(|x| &x.group_key() == g),
|
||||
_ => true,
|
||||
};
|
||||
let text = if missing {
|
||||
"Nincs hozzá kiadás a nyaa-n.".to_string()
|
||||
} else if !in_group {
|
||||
"A választott csoportnál nincs meg: másik kiadásból indul.".to_string()
|
||||
} else {
|
||||
e.overview.clone().unwrap_or_default()
|
||||
};
|
||||
let open = self.open == Some(e.number);
|
||||
let chips = if is_aired {
|
||||
vec![
|
||||
Ch::new("play", "Lejátszás").icon("play"),
|
||||
Ch::new("versions", "Verziók").icon("list").active(open),
|
||||
Ch::new("watched", if completed { "Megnézve" } else { "Megnéztem" }).icon("check").active(completed),
|
||||
]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let title = e.title.clone().unwrap_or_else(|| if movie { name.clone() } else { format::anime_episode(e.number) });
|
||||
let mut l = L::item(format!("ep:{}", e.number), title, meta.join(" · "), text, chips).image(api.image(e.image.as_deref().or(if movie { banner.as_deref() } else { None }), false));
|
||||
if missing {
|
||||
l.tone = "warn".into();
|
||||
}
|
||||
if !is_aired {
|
||||
l.tone = "dim".into();
|
||||
}
|
||||
l.progress = match p {
|
||||
Some(p) if p.completed => 1.0,
|
||||
Some(p) => p.duration.filter(|d| *d > 0.0).map(|d| (p.position / d).min(1.0) as f32).unwrap_or(-1.0),
|
||||
None => -1.0,
|
||||
};
|
||||
lines.push(l);
|
||||
if open {
|
||||
match &sources {
|
||||
None => lines.push(L::text(format!("src:{}:loading", e.number), "Kiadások keresése a nyaa-n…", "caption")),
|
||||
Some(s) if s.is_empty() => lines.push(L::text(format!("src:{}:none", e.number), "Ehhez a részhez most nincs kiadás a nyaa-n.", "label")),
|
||||
Some(s) => {
|
||||
for (i, src) in s.iter().take(20).enumerate() {
|
||||
let mut meta = Vec::new();
|
||||
if i == 0 {
|
||||
meta.push("Ajánlott".to_string());
|
||||
}
|
||||
meta.extend(src.group.clone());
|
||||
if let Some(r) = src.resolution {
|
||||
meta.push(if r >= 2160 { "4K".into() } else { format!("{r}p") });
|
||||
}
|
||||
meta.push(format!("{} seeder", src.seeders));
|
||||
let mut text = vec![src.size_bytes.map(crate::api::format_bytes).unwrap_or_default()];
|
||||
if src.is_batch {
|
||||
text.push("csomag (több rész egyben)".into());
|
||||
}
|
||||
let mut l = L::item(
|
||||
format!("src:{}:{}", e.number, src.nyaa_id),
|
||||
src.torrent_title.clone(),
|
||||
meta.join(" · "),
|
||||
text.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · "),
|
||||
vec![Ch::new("play", "Lejátszás ezzel").icon("play")],
|
||||
);
|
||||
l.indent = 40.0;
|
||||
lines.push(l);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(r) = self.releases.ready() {
|
||||
if r.groups.is_empty() {
|
||||
lines.push(L::text(
|
||||
"rel-none",
|
||||
format!("A nyaa-n nem találtunk ehhez illő kiadást (keresve: {}).", r.queries.iter().map(|q| format!("„{q}”")).collect::<Vec<_>>().join(", ")),
|
||||
"label",
|
||||
));
|
||||
}
|
||||
}
|
||||
Spec { lines, frame: Frame::default() }
|
||||
}
|
||||
|
||||
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
|
||||
match (line, item) {
|
||||
("hero", "play") => {
|
||||
let (ep, _) = self.target();
|
||||
self.play(cx, ep, None);
|
||||
}
|
||||
("hero", "list") => {
|
||||
let on = !self.listed;
|
||||
self.listed = on;
|
||||
let (api, id) = (cx.api(), self.id);
|
||||
cx.call::<AnimeDetail>("Listám", move || api.anime_set_listed(id, on), |_, _| {});
|
||||
cx.toast(if on { "Mentve a könyvtáradba" } else { "Eltávolítva a könyvtáradból" });
|
||||
}
|
||||
("franchise", key) => {
|
||||
if let Some(id) = crate::screens::parse_anime_key(key).filter(|id| *id != self.id) {
|
||||
cx.push(Box::new(AnimeDetail::new(id)));
|
||||
}
|
||||
}
|
||||
("tools", "group") => {
|
||||
let Some(r) = self.releases.ready() else { return };
|
||||
let current = self.group();
|
||||
let mut items = vec![(format!("Automatikus ({})", r.groups.first().map(|g| group_name(&g.key)).unwrap_or_default()), String::new(), current.is_none())];
|
||||
let keys: Vec<String> = r.groups.iter().map(|g| g.key.clone()).collect();
|
||||
items.extend(r.groups.iter().map(|g| {
|
||||
(group_name(&g.key), format!("{} rész{}", g.episodes.len(), if g.lang.english_dub { " · angol szinkron" } else { "" }), current.as_deref() == Some(g.key.as_str()))
|
||||
}));
|
||||
let id = self.id;
|
||||
cx.select::<AnimeDetail>("Kiadás (fansub csoport)", items, move |_s, _cx, i| {
|
||||
let mut local = config::Local::load();
|
||||
match keys.get(i.wrapping_sub(1)).filter(|_| i > 0) {
|
||||
Some(k) => {
|
||||
local.anime_groups.insert(id.to_string(), k.clone());
|
||||
}
|
||||
None => {
|
||||
local.anime_groups.remove(&id.to_string());
|
||||
}
|
||||
}
|
||||
local.save();
|
||||
});
|
||||
}
|
||||
("tools", "refresh") => self.load_releases(cx, true),
|
||||
("tools", "all") => {
|
||||
let movie = self.movie();
|
||||
let aired = self.aired();
|
||||
let eps: Vec<i32> = self.episodes.ready().map(|e| e.episodes.iter().filter(|x| movie || x.number <= aired).map(|x| x.number).collect()).unwrap_or_default();
|
||||
let all = eps.iter().all(|n| self.progress.iter().any(|p| p.episode == *n && p.completed));
|
||||
let (api, id) = (cx.api(), self.id);
|
||||
cx.call::<AnimeDetail>("Megnézve", move || api.anime_mark_watched(id, &eps, !all), |s, cx| s.reload_progress(cx));
|
||||
}
|
||||
("pages", p) => self.page = p.trim_start_matches('p').parse().ok(),
|
||||
(l, act) if l.starts_with("ep:") => {
|
||||
let Ok(n) = l[3..].parse::<i32>() else { return };
|
||||
match act {
|
||||
"play" => self.play(cx, n, None),
|
||||
"versions" => self.open = if self.open == Some(n) { None } else { Some(n) },
|
||||
"watched" => {
|
||||
let done = self.progress.iter().any(|p| p.episode == n && p.completed);
|
||||
let (api, id) = (cx.api(), self.id);
|
||||
cx.call::<AnimeDetail>("Megnézve", move || api.anime_mark_watched(id, &[n], !done), |s, cx| s.reload_progress(cx));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(l, "play") if l.starts_with("src:") => {
|
||||
let mut p = l[4..].split(':');
|
||||
let (Some(n), Some(nyaa)) = (p.next().and_then(|v| v.parse::<i32>().ok()), p.next().and_then(|v| v.parse::<i64>().ok())) else { return };
|
||||
if let Some(src) = self.sources(n).and_then(|s| s.into_iter().find(|s| s.nyaa_id == nyaa)) {
|
||||
let mut local = config::Local::load();
|
||||
local.anime_groups.insert(self.id.to_string(), src.group_key());
|
||||
local.save();
|
||||
}
|
||||
self.play(cx, n, Some(nyaa));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn focus(&mut self, cx: &Cx, _line: &str, _item: &str) {
|
||||
let url = self.data.ready().map(|d| cx.api().image(d.summary.banner_image.as_deref().or(d.summary.cover_image.as_deref()), false)).unwrap_or_default();
|
||||
cx.backdrop(&url, Look::Sharp, &format!("anime:{}", self.id));
|
||||
if let Some(c) = self.data.ready().and_then(|d| d.summary.cover_color.clone()).and_then(|c| sf_ui::parse_hex(&c)) {
|
||||
cx.c.glass.set_palette(sf_ui::Palette::from_color(c));
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(&mut self, cx: &Cx) {
|
||||
self.reload_progress(cx);
|
||||
}
|
||||
|
||||
fn as_any(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Unix time -> "november 3. 18:30" (local time is not known in the
|
||||
/// sandbox; the TV's TZ is passed through, but we show UTC+1 as a fallback).
|
||||
fn chrono_like(t: i64) -> String {
|
||||
let offset = std::env::var("TZ_OFFSET_MIN").ok().and_then(|v| v.parse::<i64>().ok()).unwrap_or(60);
|
||||
let t = t + offset * 60;
|
||||
let days = t.div_euclid(86400);
|
||||
let secs = t.rem_euclid(86400);
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let date = format!("0000-{m:02}-{d:02}");
|
||||
format!("{} {:02}:{:02}", format::date_long(Some(&date)), secs / 3600, (secs % 3600) / 60)
|
||||
}
|
||||
544
src/screens/anime_hub.rs
Normal file
544
src/screens/anime_hub.rs
Normal file
@@ -0,0 +1,544 @@
|
||||
//! Anime (the web app's pages/anime/AnimeHub.tsx): Ajánlott, Könyvtáram,
|
||||
//! Böngészés with the AniList filters (formats, status, season, years,
|
||||
//! score, genres and tags included / excluded).
|
||||
|
||||
use std::any::Any;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::api::{AnimeFilters, AnimeHome, AnimeLibraryItem, AnimeSummary, Taxonomy};
|
||||
use crate::app::{Cx, Input, Look, Screen};
|
||||
use crate::format;
|
||||
use crate::page::{C, Ch, Frame, GRID, L, Spec, grid_lines};
|
||||
use crate::screens::{self, Load, anime_card};
|
||||
|
||||
const SORTS: [(&str, &str); 5] = [("popularity", "Népszerű"), ("trending", "Felkapott"), ("score", "Legjobbra értékelt"), ("newest", "Legújabb"), ("title", "Cím")];
|
||||
const FORMATS: [&str; 6] = ["TV", "TV_SHORT", "MOVIE", "OVA", "ONA", "SPECIAL"];
|
||||
const STATUSES: [&str; 3] = ["RELEASING", "FINISHED", "NOT_YET_RELEASED"];
|
||||
const SEASONS: [&str; 4] = ["WINTER", "SPRING", "SUMMER", "FALL"];
|
||||
const SCORES: [i64; 5] = [60, 70, 75, 80, 85];
|
||||
const TAG_RANKS: [i64; 4] = [20, 40, 60, 80];
|
||||
const TAG_LIST_MAX: usize = 36;
|
||||
const KITSU: &str = "Az AniList most nem érhető el, ezért a Kitsu adatait látod.";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Tab {
|
||||
Recommended,
|
||||
Mine,
|
||||
All,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Catalog {
|
||||
items: Vec<AnimeSummary>,
|
||||
page: u32,
|
||||
has_more: bool,
|
||||
loading: bool,
|
||||
total: Option<i64>,
|
||||
fallback: Option<Vec<String>>,
|
||||
error: Option<String>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
pub struct AnimeHub {
|
||||
tab: Tab,
|
||||
started: bool,
|
||||
home: Load<AnimeHome>,
|
||||
library: Load<Vec<AnimeLibraryItem>>,
|
||||
show: &'static str,
|
||||
taxonomy: Option<Taxonomy>,
|
||||
f: AnimeFilters,
|
||||
open: bool,
|
||||
tag_query: String,
|
||||
cat: Catalog,
|
||||
}
|
||||
|
||||
fn this_year() -> i64 {
|
||||
format::today()[0..4].parse().unwrap_or(2026)
|
||||
}
|
||||
|
||||
/// Off → included → excluded → off.
|
||||
fn cycle(inc: &mut Vec<String>, exc: &mut Vec<String>, v: &str) {
|
||||
if let Some(i) = inc.iter().position(|x| x == v) {
|
||||
inc.remove(i);
|
||||
exc.push(v.to_string());
|
||||
} else if let Some(i) = exc.iter().position(|x| x == v) {
|
||||
exc.remove(i);
|
||||
} else {
|
||||
inc.push(v.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn tone(inc: &[String], exc: &[String], v: &str) -> &'static str {
|
||||
if inc.iter().any(|x| x == v) {
|
||||
"include"
|
||||
} else if exc.iter().any(|x| x == v) {
|
||||
"exclude"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimeHub {
|
||||
pub fn new() -> AnimeHub {
|
||||
AnimeHub {
|
||||
tab: Tab::Recommended,
|
||||
started: false,
|
||||
home: Load::Loading,
|
||||
library: Load::Loading,
|
||||
show: "all",
|
||||
taxonomy: None,
|
||||
f: AnimeFilters::default(),
|
||||
open: false,
|
||||
tag_query: String::new(),
|
||||
cat: Catalog::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&mut self, cx: &Cx) {
|
||||
let api = cx.api();
|
||||
cx.spawn::<AnimeHub, _>(move || (api.anime_home(), api.anime_library()), |s, cx, (home, lib)| {
|
||||
s.home = Load::from(home, cx);
|
||||
s.library = Load::from(lib, cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn active(&self) -> usize {
|
||||
let f = &self.f;
|
||||
[
|
||||
!f.genres.is_empty() || !f.exclude_genres.is_empty(),
|
||||
!f.tags.is_empty() || !f.exclude_tags.is_empty(),
|
||||
!f.formats.is_empty(),
|
||||
f.status.is_some(),
|
||||
f.season.is_some() || f.season_year.is_some(),
|
||||
f.year_from.is_some() || f.year_to.is_some(),
|
||||
f.min_score.is_some(),
|
||||
]
|
||||
.iter()
|
||||
.filter(|b| **b)
|
||||
.count()
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
let (search, sort) = (self.f.search.clone(), self.f.sort.clone());
|
||||
self.f = AnimeFilters { search, sort, ..AnimeFilters::default() };
|
||||
}
|
||||
|
||||
fn reload(&mut self, cx: &Cx) {
|
||||
self.cat = Catalog { generation: self.cat.generation + 1, has_more: true, ..Catalog::default() };
|
||||
self.next_page(cx);
|
||||
}
|
||||
|
||||
fn next_page(&mut self, cx: &Cx) {
|
||||
if self.cat.loading || !self.cat.has_more {
|
||||
return;
|
||||
}
|
||||
self.cat.loading = true;
|
||||
let (api, f, page, generation) = (cx.api(), self.f.clone(), self.cat.page + 1, self.cat.generation);
|
||||
cx.spawn::<AnimeHub, _>(move || api.anime_browse(&f, page), move |s, _cx, r| {
|
||||
if s.cat.generation != generation {
|
||||
return;
|
||||
}
|
||||
s.cat.loading = false;
|
||||
match r {
|
||||
Ok(p) => {
|
||||
let seen: HashSet<i64> = s.cat.items.iter().map(|a| a.id).collect();
|
||||
s.cat.items.extend(p.items.into_iter().filter(|a| !seen.contains(&a.id)));
|
||||
s.cat.page = page;
|
||||
s.cat.has_more = p.has_next_page;
|
||||
if page == 1 {
|
||||
s.cat.total = p.total;
|
||||
s.cat.fallback = p.fallback.map(|f| f.ignored);
|
||||
}
|
||||
s.cat.error = None;
|
||||
}
|
||||
Err(e) => s.cat.error = Some(crate::api::describe(&e)),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn load_taxonomy(&mut self, cx: &Cx) {
|
||||
if self.taxonomy.is_some() {
|
||||
return;
|
||||
}
|
||||
self.taxonomy = Some(Taxonomy::default());
|
||||
let api = cx.api();
|
||||
cx.spawn::<AnimeHub, _>(move || api.anime_taxonomy(), |s, _cx, r| {
|
||||
if let Ok(t) = r {
|
||||
s.taxonomy = Some(t);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn find(&self, id: i64) -> Option<AnimeSummary> {
|
||||
let home = self.home.ready().into_iter().flat_map(|h| h.rows.iter().flat_map(|r| r.items.iter()).chain(h.continue_watching.iter().map(|c| &c.anime)));
|
||||
let lib = self.library.ready().into_iter().flatten().map(|i| &i.anime);
|
||||
self.cat.items.iter().chain(home).chain(lib).find(|a| a.id == id).cloned()
|
||||
}
|
||||
|
||||
fn cards(&self, cx: &Cx, items: &[AnimeSummary]) -> Vec<C> {
|
||||
let api = cx.api();
|
||||
items.iter().map(|a| anime_card(&api, a)).collect()
|
||||
}
|
||||
|
||||
fn pick_year(&mut self, cx: &Cx, which: &'static str) {
|
||||
let cur = match which {
|
||||
"sy" => self.f.season_year,
|
||||
"yf" => self.f.year_from,
|
||||
_ => self.f.year_to,
|
||||
};
|
||||
let empty = match which {
|
||||
"sy" => "Bármelyik év",
|
||||
"yf" => "Kezdettől",
|
||||
_ => "Máig",
|
||||
};
|
||||
let years: Vec<i64> = (1960..=this_year() + 1).rev().collect();
|
||||
let mut items = vec![(empty.to_string(), String::new(), cur.is_none())];
|
||||
items.extend(years.iter().map(|y| (y.to_string(), String::new(), cur == Some(*y))));
|
||||
cx.select::<AnimeHub>("Év", items, move |s, cx, i| {
|
||||
let v = if i == 0 { None } else { years.get(i - 1).copied() };
|
||||
match which {
|
||||
"sy" => s.f.season_year = v,
|
||||
"yf" => s.f.year_from = v,
|
||||
_ => s.f.year_to = v,
|
||||
}
|
||||
if let (Some(a), Some(b)) = (s.f.year_from, s.f.year_to) {
|
||||
if a > b {
|
||||
if which == "yf" {
|
||||
s.f.year_to = Some(a);
|
||||
} else {
|
||||
s.f.year_from = Some(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.reload(cx);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Screen for AnimeHub {
|
||||
fn spec(&mut self, cx: &Cx) -> Spec {
|
||||
if !self.started {
|
||||
self.started = true;
|
||||
self.start(cx);
|
||||
}
|
||||
let api = cx.api();
|
||||
let lib_n = self.library.ready().map(|l| l.len()).unwrap_or(0);
|
||||
let mut lines = vec![
|
||||
L::page_title("title", "Anime", ""),
|
||||
L::chips(
|
||||
"tabs",
|
||||
"",
|
||||
vec![
|
||||
Ch::new("rec", "Ajánlott").active(self.tab == Tab::Recommended),
|
||||
Ch::new("mine", format!("Könyvtáram ({lib_n})")).active(self.tab == Tab::Mine),
|
||||
Ch::new("all", "Böngészés").active(self.tab == Tab::All),
|
||||
],
|
||||
),
|
||||
];
|
||||
match self.tab {
|
||||
Tab::Recommended => {
|
||||
if let Some(st) = self.home.status("status") {
|
||||
lines.push(st);
|
||||
}
|
||||
if let Some(h) = self.home.ready() {
|
||||
if h.source.as_deref() == Some("kitsu") {
|
||||
lines.push(L::text("kitsu", KITSU, "warn"));
|
||||
}
|
||||
if !h.continue_watching.is_empty() {
|
||||
let cards = h
|
||||
.continue_watching
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let a = &c.anime;
|
||||
let mut card = C::new(format!("ac:{}:{}", a.id, c.episode), a.title.name(), api.image(a.banner_image.as_deref().or(a.cover_image.as_deref()), false));
|
||||
card.caption = a.title.name();
|
||||
let left = c.duration.map(|d| ((d - c.position) / 60.0).round().max(0.0) as i64).filter(|l| *l > 0);
|
||||
card.detail = match left {
|
||||
Some(l) => format!("{} · még {l} perc", format::anime_episode(c.episode)),
|
||||
None => format::anime_episode(c.episode),
|
||||
};
|
||||
card.progress = c.duration.filter(|d| *d > 0.0).map(|d| (c.position / d).min(1.0) as f32).unwrap_or(-1.0);
|
||||
card
|
||||
})
|
||||
.collect();
|
||||
lines.push(L::cards("continue", "Folytasd, ahol abbahagytad", "landscape", cards).captions());
|
||||
}
|
||||
}
|
||||
if let Some(lib) = self.library.ready() {
|
||||
let saved: Vec<AnimeSummary> = lib.iter().filter(|i| i.listed).take(30).map(|i| i.anime.clone()).collect();
|
||||
if !saved.is_empty() {
|
||||
let n = lib.iter().filter(|i| i.listed).count();
|
||||
lines.push(L::cards("saved", "A könyvtáradból", "poster", self.cards(cx, &saved)).sub(format!("{n} mentett anime")));
|
||||
}
|
||||
}
|
||||
if let Some(h) = self.home.ready() {
|
||||
for r in &h.rows {
|
||||
lines.push(L::cards(format!("row:{}", r.id), r.title.clone(), "poster", self.cards(cx, &r.items)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Tab::Mine => {
|
||||
let filters = [("all", "Minden"), ("saved", "Mentett"), ("started", "Elkezdett")];
|
||||
lines.push(L::chips("show", "", filters.iter().map(|(id, l)| Ch::new(*id, *l).active(self.show == *id)).collect()));
|
||||
match &self.library {
|
||||
Load::Ready(lib) if lib.is_empty() => lines.push(L::notice("empty", "info", "Még egy animét sem mentettél", "Egy anime oldalán a + gombbal mentheted el. Amit elkezdesz, magától is ide kerül.")),
|
||||
Load::Ready(lib) => {
|
||||
let items: Vec<AnimeSummary> = lib
|
||||
.iter()
|
||||
.filter(|i| match self.show {
|
||||
"saved" => i.listed,
|
||||
"started" => i.last_watched_at.is_some(),
|
||||
_ => true,
|
||||
})
|
||||
.map(|i| i.anime.clone())
|
||||
.collect();
|
||||
if items.is_empty() {
|
||||
lines.push(L::notice("empty", "info", "Ehhez a szűréshez nincs anime", "Válts a „Minden” nézetre."));
|
||||
} else {
|
||||
lines.extend(grid_lines("lib", "", "poster", self.cards(cx, &items), GRID));
|
||||
}
|
||||
}
|
||||
other => lines.extend(other.status("status")),
|
||||
}
|
||||
}
|
||||
Tab::All => {
|
||||
lines.push(L::chips("search", "", vec![Ch::field("q", &self.f.search, "Anime keresése (angol vagy japán cím)", "search")]));
|
||||
let searching = !self.f.search.is_empty();
|
||||
let mut chips = Vec::new();
|
||||
if searching {
|
||||
chips.push(Ch::new("sort:", "Legjobb találat").active(self.f.sort.is_none()));
|
||||
}
|
||||
for (id, l) in SORTS {
|
||||
let on = self.f.sort.as_deref() == Some(id) || (self.f.sort.is_none() && !searching && id == "popularity");
|
||||
chips.push(Ch::new(format!("sort:{id}"), l).active(on));
|
||||
}
|
||||
let active = self.active();
|
||||
chips.push(Ch::new("filters", if active > 0 { format!("Szűrők ({active})") } else { "Szűrők".into() }).icon("settings").active(self.open || active > 0));
|
||||
if active > 0 {
|
||||
chips.push(Ch::new("reset", "Törlés").icon("close"));
|
||||
}
|
||||
lines.push(L::chips("sort", "", chips));
|
||||
if self.open {
|
||||
let f = &self.f;
|
||||
lines.push(L::chips("fmt", "FORMÁTUM", FORMATS.iter().map(|id| Ch::new(*id, format::anime_format(Some(id))).active(f.formats.iter().any(|x| x == id))).collect()));
|
||||
lines.push(L::chips("st", "ÁLLAPOT", STATUSES.iter().map(|id| Ch::new(*id, format::anime_status(Some(id))).active(f.status.as_deref() == Some(id))).collect()));
|
||||
let mut sc: Vec<Ch> = SEASONS.iter().map(|id| Ch::new(*id, format::anime_season_name(id)).active(f.season.as_deref() == Some(id))).collect();
|
||||
sc.push(Ch::new("sy", format!("Év: {}", f.season_year.map(|y| y.to_string()).unwrap_or_else(|| "bármelyik".into()))).active(f.season_year.is_some()));
|
||||
lines.push(L::chips("sn", "SZEZON", sc));
|
||||
lines.push(L::chips(
|
||||
"yr",
|
||||
"KEZDÉS ÉVE",
|
||||
vec![
|
||||
Ch::new("yf", format!("Ettől: {}", f.year_from.map(|y| y.to_string()).unwrap_or_else(|| "kezdettől".into()))).active(f.year_from.is_some()),
|
||||
Ch::new("yt", format!("Eddig: {}", f.year_to.map(|y| y.to_string()).unwrap_or_else(|| "máig".into()))).active(f.year_to.is_some()),
|
||||
],
|
||||
));
|
||||
lines.push(L::chips("ms", "ÉRTÉKELÉS", SCORES.iter().map(|s| Ch::new(s.to_string(), format!("★ {}+", format::anime_score(*s as f64))).active(f.min_score == Some(*s))).collect()));
|
||||
if let Some(t) = &self.taxonomy {
|
||||
lines.push(L::chips("g", "MŰFAJ", t.genres.iter().map(|g| Ch::new(g.clone(), format::anime_genre(g)).tone(tone(&f.genres, &f.exclude_genres, g))).collect()));
|
||||
let mut tc = vec![Ch::field("tq", &self.tag_query, "Tag keresése, pl. Isekai, Time Travel", "search").width(620.0)];
|
||||
if !f.tags.is_empty() {
|
||||
tc.push(Ch::new("tr", format!("Relevancia: {}%", f.min_tag_rank.unwrap_or(50))).active(f.min_tag_rank.is_some()));
|
||||
}
|
||||
lines.push(L::chips("tq", "TAGEK", tc));
|
||||
let chosen: Vec<String> = f.tags.iter().chain(f.exclude_tags.iter()).cloned().collect();
|
||||
if !chosen.is_empty() {
|
||||
lines.push(L::chips("tchosen", "", chosen.iter().map(|n| Ch::new(n.clone(), n.clone()).tone(tone(&f.tags, &f.exclude_tags, n))).collect()));
|
||||
}
|
||||
let needle = self.tag_query.trim().to_lowercase();
|
||||
let matches: Vec<Ch> = t
|
||||
.tags
|
||||
.iter()
|
||||
.filter(|tg| !chosen.contains(&tg.name) && (needle.is_empty() || tg.name.to_lowercase().contains(&needle) || tg.category.to_lowercase().contains(&needle)))
|
||||
.take(TAG_LIST_MAX)
|
||||
.map(|tg| Ch::new(tg.name.clone(), tg.name.clone()))
|
||||
.collect();
|
||||
if matches.is_empty() {
|
||||
lines.push(L::text("tnone", if t.tags.is_empty() { "Tagek betöltése…" } else { "Nincs ilyen tag." }, "caption"));
|
||||
} else {
|
||||
lines.push(L::chips("tlist", "", matches));
|
||||
}
|
||||
lines.push(L::text("thint", "Műfajnál és tagnál: egy nyomás = legyen benne (zöld), még egy = ne legyen benne (piros), harmadik = mindegy.", "caption"));
|
||||
}
|
||||
} else if active > 0 {
|
||||
let f = &self.f;
|
||||
let mut parts: Vec<String> = f.formats.iter().map(|x| format::anime_format(Some(x))).collect();
|
||||
parts.extend(f.status.iter().map(|s| format::anime_status(Some(s))));
|
||||
if f.season.is_some() || f.season_year.is_some() {
|
||||
parts.push(format::anime_season(f.season.as_deref(), f.season_year.map(|y| y as i32)));
|
||||
}
|
||||
if f.year_from.is_some() || f.year_to.is_some() {
|
||||
parts.push(format!("{}–{}", f.year_from.map(|y| y.to_string()).unwrap_or("…".into()), f.year_to.map(|y| y.to_string()).unwrap_or("…".into())));
|
||||
}
|
||||
parts.extend(f.min_score.map(|s| format!("{}+", format::anime_score(s as f64))));
|
||||
parts.extend(f.genres.iter().map(|g| format::anime_genre(g)));
|
||||
parts.extend(f.exclude_genres.iter().map(|g| format!("nem {}", format::anime_genre(g))));
|
||||
parts.extend(f.tags.iter().cloned());
|
||||
parts.extend(f.exclude_tags.iter().map(|t| format!("nem {t}")));
|
||||
lines.push(L::text("summary", parts.join(" · "), "caption"));
|
||||
}
|
||||
if let Some(ignored) = &self.cat.fallback {
|
||||
lines.push(L::text("kitsu", if ignored.is_empty() { KITSU.to_string() } else { format!("{KITSU} Ezeket a szűrőket a Kitsu nem ismeri, kimaradtak: {}.", ignored.join(", ")) }, "warn"));
|
||||
}
|
||||
if self.cat.items.is_empty() {
|
||||
if let Some(e) = &self.cat.error {
|
||||
lines.push(L::notice("err", "bad", "Nem sikerült betölteni", e.clone()));
|
||||
lines.push(L::chips("retry", "", vec![Ch::new("retry", "Újrapróbálom").icon("refresh")]));
|
||||
} else if self.cat.loading || self.cat.has_more {
|
||||
lines.push(L::text("loading", "Betöltés…", "caption"));
|
||||
} else {
|
||||
lines.push(L::notice("none", "info", "Ehhez a szűréshez nincs találat", "Tágítsd a szűrést, vagy vegyél ki egy műfajt vagy taget."));
|
||||
if active > 0 {
|
||||
lines.push(L::chips("reset2", "", vec![Ch::new("reset", "Szűrők törlése").icon("close")]));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if let Some(t) = self.cat.total {
|
||||
lines.push(L::text("total", format!("{t} találat"), "caption"));
|
||||
}
|
||||
lines.extend(grid_lines("cat", "", "poster", self.cards(cx, &self.cat.items.clone()), GRID));
|
||||
if self.cat.error.is_some() {
|
||||
lines.push(L::chips("retry", "", vec![Ch::new("retry", "Újrapróbálom").icon("refresh")]));
|
||||
} else if self.cat.loading {
|
||||
lines.push(L::text("loading2", "Betöltés…", "caption"));
|
||||
} else if !self.cat.has_more {
|
||||
lines.push(L::text("end", format!("A lista végére értél · {} anime", self.cat.items.len()), "caption"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Spec { lines, frame: Frame { nav: Some(3), ..Frame::default() } }
|
||||
}
|
||||
|
||||
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
|
||||
match (line, item) {
|
||||
("tabs", t) => {
|
||||
self.tab = match t {
|
||||
"mine" => Tab::Mine,
|
||||
"all" => Tab::All,
|
||||
_ => Tab::Recommended,
|
||||
};
|
||||
if self.tab == Tab::All && self.cat.page == 0 && !self.cat.loading {
|
||||
self.reload(cx);
|
||||
self.load_taxonomy(cx);
|
||||
}
|
||||
}
|
||||
("show", v) => {
|
||||
self.show = match v {
|
||||
"saved" => "saved",
|
||||
"started" => "started",
|
||||
_ => "all",
|
||||
}
|
||||
}
|
||||
("search", _) => {
|
||||
let mut req = Input::new("Anime keresése", "Angol vagy japán cím", &self.f.search);
|
||||
req.submit = "Keresés".into();
|
||||
cx.input::<AnimeHub>(req, |s, cx, text| {
|
||||
s.f.search = text.trim().to_string();
|
||||
if !s.f.search.is_empty() && s.f.sort.as_deref() == Some("popularity") {
|
||||
s.f.sort = None;
|
||||
}
|
||||
s.reload(cx);
|
||||
});
|
||||
}
|
||||
("sort", "filters") => {
|
||||
self.open = !self.open;
|
||||
self.load_taxonomy(cx);
|
||||
}
|
||||
("sort", "reset") | ("reset2", _) => {
|
||||
self.reset();
|
||||
self.reload(cx);
|
||||
}
|
||||
("sort", s) => {
|
||||
let id = s.trim_start_matches("sort:");
|
||||
let searching = !self.f.search.is_empty();
|
||||
self.f.sort = if id.is_empty() || (id == "popularity" && !searching) { None } else { Some(id.to_string()) };
|
||||
self.reload(cx);
|
||||
}
|
||||
("fmt", v) => {
|
||||
if let Some(i) = self.f.formats.iter().position(|x| x == v) {
|
||||
self.f.formats.remove(i);
|
||||
} else {
|
||||
self.f.formats.push(v.to_string());
|
||||
}
|
||||
self.reload(cx);
|
||||
}
|
||||
("st", v) => {
|
||||
self.f.status = if self.f.status.as_deref() == Some(v) { None } else { Some(v.to_string()) };
|
||||
self.reload(cx);
|
||||
}
|
||||
("sn", "sy") => self.pick_year(cx, "sy"),
|
||||
("sn", v) => {
|
||||
if self.f.season.as_deref() == Some(v) {
|
||||
self.f.season = None;
|
||||
} else {
|
||||
self.f.season = Some(v.to_string());
|
||||
self.f.season_year = self.f.season_year.or(Some(this_year()));
|
||||
}
|
||||
self.reload(cx);
|
||||
}
|
||||
("yr", w) => self.pick_year(cx, if w == "yf" { "yf" } else { "yt" }),
|
||||
("ms", v) => {
|
||||
let v: Option<i64> = v.parse().ok();
|
||||
self.f.min_score = if self.f.min_score == v { None } else { v };
|
||||
self.reload(cx);
|
||||
}
|
||||
("g", g) => {
|
||||
let (mut inc, mut exc) = (std::mem::take(&mut self.f.genres), std::mem::take(&mut self.f.exclude_genres));
|
||||
cycle(&mut inc, &mut exc, g);
|
||||
(self.f.genres, self.f.exclude_genres) = (inc, exc);
|
||||
self.reload(cx);
|
||||
}
|
||||
("tq", "tq") => {
|
||||
cx.input::<AnimeHub>(Input::new("Tag keresése", "pl. Isekai, Time Travel", &self.tag_query), |s, _cx, text| s.tag_query = text);
|
||||
}
|
||||
("tq", "tr") => {
|
||||
let cur = self.f.min_tag_rank;
|
||||
let mut items = vec![("Relevancia: 50%".to_string(), String::new(), cur.is_none())];
|
||||
items.extend(TAG_RANKS.iter().map(|r| (format!("Relevancia: {r}%"), String::new(), cur == Some(*r))));
|
||||
cx.select::<AnimeHub>("Tag relevancia legalább", items, |s, cx, i| {
|
||||
s.f.min_tag_rank = if i == 0 { None } else { TAG_RANKS.get(i - 1).copied() };
|
||||
s.reload(cx);
|
||||
});
|
||||
}
|
||||
("tchosen", t) | ("tlist", t) => {
|
||||
let (mut inc, mut exc) = (std::mem::take(&mut self.f.tags), std::mem::take(&mut self.f.exclude_tags));
|
||||
cycle(&mut inc, &mut exc, t);
|
||||
(self.f.tags, self.f.exclude_tags) = (inc, exc);
|
||||
self.reload(cx);
|
||||
}
|
||||
("retry", _) => {
|
||||
self.cat.error = None;
|
||||
self.next_page(cx);
|
||||
}
|
||||
(_, key) => {
|
||||
screens::open_card(cx, key, |_| None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn focus(&mut self, cx: &Cx, _line: &str, item: &str) {
|
||||
let id = screens::parse_anime_key(item).or_else(|| item.strip_prefix("ac:").and_then(|r| r.split(':').next()).and_then(|v| v.parse().ok()));
|
||||
match id.and_then(|id| self.find(id)) {
|
||||
Some(a) => {
|
||||
let url = cx.api().image(a.banner_image.as_deref().or(a.cover_image.as_deref()), false);
|
||||
cx.backdrop(&url, Look::Soft, item);
|
||||
}
|
||||
None => cx.backdrop("", Look::Soft, ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn more(&mut self, cx: &Cx, list: &str) {
|
||||
if list == "cat" {
|
||||
self.next_page(cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(&mut self, cx: &Cx) {
|
||||
self.start(cx);
|
||||
}
|
||||
|
||||
fn as_any(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,10 @@ impl Home {
|
||||
s.spotlight = spotlight(&d.rows);
|
||||
s.index = s.index.min(s.spotlight.len().saturating_sub(1));
|
||||
}
|
||||
// The spotlight's picture also shows under the menu.
|
||||
if s.hero_focused {
|
||||
s.focus(cx, "hero", "");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -217,12 +221,12 @@ impl Screen for Home {
|
||||
if t.kind == MediaType::Movie {
|
||||
cx.play(player::Request::title(t.kind, &t.id, t.title.clone(), None, t.backdrop.clone()));
|
||||
} else {
|
||||
cx.push(Box::new(screens::detail::Detail::new(t.kind, &t.id, Some(t))));
|
||||
cx.push(Box::new(screens::detail::Detail::new(t.kind, &t.id.clone(), Some(t.clone()))));
|
||||
}
|
||||
}
|
||||
("hero", "info") => {
|
||||
if let Some(t) = self.current().cloned() {
|
||||
cx.push(Box::new(screens::detail::Detail::new(t.kind, &t.id, Some(t))));
|
||||
cx.push(Box::new(screens::detail::Detail::new(t.kind, &t.id.clone(), Some(t.clone()))));
|
||||
}
|
||||
}
|
||||
("hero", "list") => {
|
||||
|
||||
123
src/screens/mylist.rs
Normal file
123
src/screens/mylist.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
//! Listám: saved titles and the watch history, movies and series apart
|
||||
//! (the web app's pages/MyList.tsx).
|
||||
|
||||
use std::any::Any;
|
||||
|
||||
use crate::api::{ListItem, MediaType, TitleSummary};
|
||||
use crate::app::{Cx, Look, Screen};
|
||||
use crate::page::{Ch, Frame, GRID, L, Spec, grid_lines};
|
||||
use crate::screens::{self, Load, title_card};
|
||||
|
||||
pub struct MyList {
|
||||
history: bool,
|
||||
kind: &'static str,
|
||||
data: Load<Vec<ListItem>>,
|
||||
loaded: Option<bool>,
|
||||
}
|
||||
|
||||
impl MyList {
|
||||
pub fn new() -> MyList {
|
||||
MyList { history: false, kind: "all", data: Load::Loading, loaded: None }
|
||||
}
|
||||
|
||||
fn load(&mut self, cx: &Cx) {
|
||||
self.loaded = Some(self.history);
|
||||
self.data = Load::Loading;
|
||||
let (api, history) = (cx.api(), self.history);
|
||||
cx.spawn::<MyList, _>(move || if history { api.history() } else { api.my_list() }, |s, cx, r| s.data = Load::from(r, cx));
|
||||
}
|
||||
|
||||
fn find(&self, key: &str) -> Option<TitleSummary> {
|
||||
let (kind, id) = screens::parse_title_key(key)?;
|
||||
self.data.ready()?.iter().map(|i| &i.title).find(|t| t.kind == kind && t.id == id).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Screen for MyList {
|
||||
fn spec(&mut self, cx: &Cx) -> Spec {
|
||||
if self.loaded != Some(self.history) {
|
||||
self.load(cx);
|
||||
}
|
||||
let api = cx.api();
|
||||
let mut lines = vec![
|
||||
L::page_title("title", "Listám", ""),
|
||||
L::chips("tabs", "", vec![Ch::new("mine", "Mentett").active(!self.history), Ch::new("history", "Előzmények").active(self.history)]),
|
||||
];
|
||||
match &self.data {
|
||||
Load::Ready(items) if items.is_empty() => {
|
||||
if self.history {
|
||||
lines.push(L::notice("empty", "info", "Még nem néztél semmit", "Amit elkezdesz, az itt marad, hogy bármikor visszatalálj hozzá."));
|
||||
} else {
|
||||
lines.push(L::notice("empty", "info", "A listád még üres", "Amit később megnéznél, azt egy film vagy sorozat oldalán a + gombbal mentheted el. Itt vár majd rád."));
|
||||
}
|
||||
}
|
||||
Load::Ready(items) => {
|
||||
lines.push(L::chips("kind", "", [("all", "Minden"), ("movie", "Filmek"), ("tv", "Sorozatok")].iter().map(|(id, l)| Ch::new(*id, *l).active(self.kind == *id)).collect()));
|
||||
let group = |kind: MediaType| -> Vec<ListItem> { items.iter().filter(|i| i.title.kind == kind).cloned().collect() };
|
||||
let mut any = false;
|
||||
for (kind, title, key) in [(MediaType::Movie, "Filmek", "movie"), (MediaType::Tv, "Sorozatok", "tv")] {
|
||||
if self.kind != "all" && self.kind != key {
|
||||
continue;
|
||||
}
|
||||
let g = group(kind);
|
||||
if g.is_empty() {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
lines.push(L::heading(format!("h:{key}"), title).sub(format!("{} cím", g.len())));
|
||||
let cards = g
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let mut c = title_card(&api, &i.title, None);
|
||||
if self.history && kind == MediaType::Tv && i.watched_episodes > 0 {
|
||||
c.detail = format!("{} · {} rész", c.detail, i.watched_episodes);
|
||||
}
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
lines.extend(grid_lines(&format!("g{key}"), "", "poster", cards, GRID));
|
||||
}
|
||||
if !any {
|
||||
lines.push(L::notice("empty-kind", "info", if self.kind == "movie" { "Itt még nincs film" } else { "Itt még nincs sorozat" }, "Válts a „Minden” nézetre."));
|
||||
}
|
||||
}
|
||||
other => lines.extend(other.status("status")),
|
||||
}
|
||||
Spec { lines, frame: Frame { nav: Some(4), ..Frame::default() } }
|
||||
}
|
||||
|
||||
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
|
||||
match line {
|
||||
"tabs" => self.history = item == "history",
|
||||
"kind" => {
|
||||
self.kind = match item {
|
||||
"movie" => "movie",
|
||||
"tv" => "tv",
|
||||
_ => "all",
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let found = self.find(item);
|
||||
screens::open_card(cx, item, |_| found.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn focus(&mut self, cx: &Cx, _line: &str, item: &str) {
|
||||
match self.find(item) {
|
||||
Some(t) => {
|
||||
let url = cx.api().image(t.backdrop.as_deref(), false);
|
||||
cx.backdrop(&url, Look::Soft, item);
|
||||
}
|
||||
None => cx.backdrop("", Look::Soft, ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(&mut self, cx: &Cx) {
|
||||
self.load(cx);
|
||||
}
|
||||
|
||||
fn as_any(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
85
src/screens/search.rs
Normal file
85
src/screens/search.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
//! Keresés: the on-screen keyboard and the results (movies and series).
|
||||
|
||||
use std::any::Any;
|
||||
|
||||
use crate::api::{Page, TitleSummary};
|
||||
use crate::app::{Cx, Look, Screen};
|
||||
use crate::page::{Frame, GRID, Kind, L, Spec, grid_lines};
|
||||
use crate::screens::{self, Load, title_card};
|
||||
|
||||
pub struct Search {
|
||||
query: String,
|
||||
searched: String,
|
||||
result: Option<Load<Page<TitleSummary>>>,
|
||||
}
|
||||
|
||||
impl Search {
|
||||
pub fn new() -> Search {
|
||||
Search { query: String::new(), searched: String::new(), result: None }
|
||||
}
|
||||
|
||||
fn find(&self, key: &str) -> Option<TitleSummary> {
|
||||
let (kind, id) = screens::parse_title_key(key)?;
|
||||
self.result.as_ref()?.ready()?.items.iter().find(|t| t.kind == kind && t.id == id).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Screen for Search {
|
||||
fn spec(&mut self, cx: &Cx) -> Spec {
|
||||
let api = cx.api();
|
||||
let mut lines = vec![L::page_title("title", "Mit néznél ma?", "Filmek és sorozatok, az eredeti (angol) címükkel."), L::new("kb", Kind::Keyboard)];
|
||||
match &self.result {
|
||||
None => lines.push(L::notice("hint", "info", "Kezdj el gépelni", "Két betű elég.")),
|
||||
Some(Load::Loading) => lines.push(L::text("loading", "Keresés…", "caption")),
|
||||
Some(Load::Failed(e)) => lines.push(L::notice("error", "bad", "Nem sikerült keresni", e.clone())),
|
||||
Some(Load::Ready(p)) if p.items.is_empty() => lines.push(L::notice("none", "info", "Erre nincs találat", "Próbáld az eredeti, angol címmel.")),
|
||||
Some(Load::Ready(p)) => {
|
||||
let cards = p.items.iter().map(|t| title_card(&api, t, None)).collect();
|
||||
lines.extend(grid_lines("res", &format!("Találatok · {}", self.searched), "poster", cards, GRID));
|
||||
}
|
||||
}
|
||||
Spec { lines, frame: Frame { nav: Some(5), keyboard: Some("Cím, például Dűne vagy The Office".into()), ..Frame::default() } }
|
||||
}
|
||||
|
||||
fn query(&mut self, cx: &Cx, text: &str, _submit: bool) {
|
||||
let q = text.trim().to_string();
|
||||
self.query = q.clone();
|
||||
if q.chars().count() < 2 {
|
||||
self.result = None;
|
||||
self.searched.clear();
|
||||
cx.refresh();
|
||||
return;
|
||||
}
|
||||
if q == self.searched {
|
||||
return;
|
||||
}
|
||||
self.searched = q.clone();
|
||||
self.result = Some(Load::Loading);
|
||||
let api = cx.api();
|
||||
cx.spawn::<Search, _>(move || (api.search(&q), q), |s, cx, (r, q)| {
|
||||
if s.searched == q {
|
||||
s.result = Some(Load::from(r, cx));
|
||||
}
|
||||
});
|
||||
cx.refresh();
|
||||
}
|
||||
|
||||
fn activate(&mut self, cx: &Cx, _line: &str, item: &str) {
|
||||
let found = self.find(item);
|
||||
screens::open_card(cx, item, |_| found.clone());
|
||||
}
|
||||
|
||||
fn focus(&mut self, cx: &Cx, _line: &str, item: &str) {
|
||||
match self.find(item) {
|
||||
Some(t) => {
|
||||
let url = cx.api().image(t.backdrop.as_deref(), false);
|
||||
cx.backdrop(&url, Look::Soft, item);
|
||||
}
|
||||
None => cx.backdrop("", Look::Soft, ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
1092
src/screens/settings.rs
Normal file
1092
src/screens/settings.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -33,6 +33,88 @@ my_list = {}
|
||||
progress = {}
|
||||
VIDEO = None
|
||||
|
||||
ANILIST = "https://graphql.anilist.co"
|
||||
ANIME_FIELDS = """id idMal title { romaji english native } coverImage { extraLarge color } bannerImage format status episodes
|
||||
season seasonYear averageScore genres description duration studios(isMain: true) { nodes { name } }
|
||||
nextAiringEpisode { episode airingAt }"""
|
||||
anime_progress = {}
|
||||
anime_list = {}
|
||||
settings = {"subtitleLang": "hu", "autoNext": True, "autoSkipIntro": False, "transcode": "auto"}
|
||||
anime_prefs = {"preferredResolution": 1080, "preferredGroups": ["SubsPlease"], "preferDub": False, "subtitleLang": "en"}
|
||||
seed_rules = {"minSeedHours": 72, "minRatio": 1.0, "marginHours": 2, "marginRatio": 0.05, "requireNcoreConfirmation": True,
|
||||
"maxDiskGB": 500, "seasonPackMode": "whole", "maxActiveDownloads": 3}
|
||||
source_prefs = {"language": "dub", "maxResolution": 1080, "maxSize": 0, "allowHdr": False}
|
||||
crawl = {"latest": True}
|
||||
tmdb = {"on": False}
|
||||
users = [{"id": 1, "username": "dev", "name": "Dev", "isAdmin": True, "sessions": 2, "lastSeenAt": "2026-10-25T10:00:00Z"},
|
||||
{"id": 2, "username": "anna", "name": "Anna", "isAdmin": False, "sessions": 1, "lastSeenAt": "2026-10-24T19:30:00Z"}]
|
||||
vpn = {"enabled": True, "pf": True}
|
||||
torrents = [
|
||||
{"infoHash": "a" * 40, "name": "Dune.Part.Two.2024.1080p.WEB-DL.HUN.ENG", "size": 6.1e9, "state": "seeding", "keep": False,
|
||||
"completedAt": "2026-10-23T18:00:00Z", "seedingSeconds": 140000, "ratio": 0.62, "eligibleAt": "2026-10-26T20:00:00Z",
|
||||
"ncoreCheckedAt": "2026-10-25T09:00:00Z", "ncoreFound": True, "ncoreRemainingSeconds": 120000, "ncoreHnr": False,
|
||||
"live": {"progress": 1, "downloadSpeed": 0, "uploadSpeed": 420000}, "inUse": False, "pausedForPlayback": False},
|
||||
{"infoHash": "b" * 40, "name": "The.Office.US.S02.1080p.WEB-DL.HUN", "size": 18e9, "state": "downloading", "keep": False,
|
||||
"seedingSeconds": 0, "ratio": 0.0, "live": {"progress": 0.41, "downloadSpeed": 5.2e6, "uploadSpeed": 80000}, "inUse": True,
|
||||
"pausedForPlayback": False},
|
||||
]
|
||||
|
||||
|
||||
def anilist(query, variables):
|
||||
key = json.dumps([query, variables], sort_keys=True)
|
||||
with cache_lock:
|
||||
if key in cache:
|
||||
return cache[key]
|
||||
req = urllib.request.Request(ANILIST, data=json.dumps({"query": query, "variables": variables}).encode(),
|
||||
headers={"Content-Type": "application/json", "Accept": "application/json", "User-Agent": "netflex-mock"})
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
value = json.loads(r.read())["data"]
|
||||
with cache_lock:
|
||||
cache[key] = value
|
||||
return value
|
||||
|
||||
|
||||
def anime(m):
|
||||
cover = m.get("coverImage") or {}
|
||||
return {"id": m["id"], "idMal": m.get("idMal"), "title": m["title"], "coverImage": cover.get("extraLarge"),
|
||||
"coverColor": cover.get("color"), "bannerImage": m.get("bannerImage"), "format": m.get("format"),
|
||||
"status": m.get("status"), "episodes": m.get("episodes"), "season": m.get("season"), "seasonYear": m.get("seasonYear"),
|
||||
"averageScore": m.get("averageScore"), "genres": m.get("genres") or [], "description": m.get("description"),
|
||||
"duration": m.get("duration"), "studios": [n["name"] for n in ((m.get("studios") or {}).get("nodes") or [])],
|
||||
"nextAiringEpisode": m.get("nextAiringEpisode")}
|
||||
|
||||
|
||||
def anime_page(sort, page=1, search=None, genres=None, season=None, year=None):
|
||||
args = {"sort": [sort], "page": page}
|
||||
q = "query($sort:[MediaSort],$page:Int"
|
||||
f = "type: ANIME, sort: $sort, isAdult: false"
|
||||
if search:
|
||||
q += ",$search:String"
|
||||
f += ", search: $search"
|
||||
args["search"] = search
|
||||
if genres:
|
||||
q += ",$genres:[String]"
|
||||
f += ", genre_in: $genres"
|
||||
args["genres"] = genres
|
||||
if season:
|
||||
q += ",$season:MediaSeason,$year:Int"
|
||||
f += ", season: $season, seasonYear: $year"
|
||||
args["season"] = season
|
||||
args["year"] = year
|
||||
q += f"){{ Page(page:$page, perPage:30) {{ pageInfo {{ hasNextPage total }} media({f}) {{ {ANIME_FIELDS} }} }} }}"
|
||||
d = anilist(q, args)["Page"]
|
||||
return {"items": [anime(m) for m in d["media"]], "page": page, "hasNextPage": d["pageInfo"]["hasNextPage"], "total": d["pageInfo"]["total"]}
|
||||
|
||||
|
||||
def anime_detail(i):
|
||||
rel = "relations { edges { relationType node { id title { romaji english native } format episodes seasonYear coverImage { extraLarge } } } }"
|
||||
return anilist(f"query($id:Int){{ Media(id:$id, type: ANIME) {{ {ANIME_FIELDS} {rel} }} }}", {"id": i})["Media"]
|
||||
|
||||
|
||||
def aired(m):
|
||||
n = m.get("nextAiringEpisode")
|
||||
return (n["episode"] - 1) if n else (m.get("episodes") or 1)
|
||||
|
||||
|
||||
def fetch(url, binary=False):
|
||||
with cache_lock:
|
||||
@@ -176,6 +258,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self.send_json({"token": TOKEN, "user": {"id": 1, "username": b.get("username", "dev"), "name": "Dev", "isAdmin": True}})
|
||||
if not self.authed(q):
|
||||
return self.send_json({"error": "Bejelentkezés szükséges", "code": "unauthenticated"}, 401)
|
||||
r = self.account(method, p) or self.anime(method, p, q)
|
||||
if r is not None:
|
||||
return r
|
||||
if p == "/api/img":
|
||||
return self.image(q.get("u", [""])[0])
|
||||
if p.startswith("/api/stream/"):
|
||||
@@ -257,6 +342,172 @@ class Handler(BaseHTTPRequestHandler):
|
||||
print("mock: error", p, e)
|
||||
return self.send_json({"error": f"mock: {e}"}, 502)
|
||||
|
||||
def j(self, value, status=200):
|
||||
self.send_json(value, status)
|
||||
return True
|
||||
|
||||
def account(self, method, p):
|
||||
"""Settings, users, sessions and the admin's server setup."""
|
||||
j = self.j
|
||||
if p == "/api/health":
|
||||
return j({"ok": True, "vpn": "vpn" if vpn["enabled"] else "blocked"})
|
||||
if p == "/api/settings":
|
||||
if method == "PUT":
|
||||
settings.update(self.body())
|
||||
return j(settings)
|
||||
if p == "/api/auth/sessions":
|
||||
return j([{"id": 1, "device": "Fennec OS TV", "ip": "192.168.1.20", "createdAt": "2026-10-01T10:00:00Z", "lastSeenAt": "2026-10-25T10:00:00Z", "current": True},
|
||||
{"id": 2, "device": "Chrome · Windows", "ip": "192.168.1.11", "createdAt": "2026-09-12T10:00:00Z", "lastSeenAt": "2026-10-20T21:00:00Z", "current": False}])
|
||||
if p.startswith("/api/auth/sessions/") or p == "/api/auth/logout":
|
||||
return j({"ok": True})
|
||||
if p == "/api/users":
|
||||
if method == "POST":
|
||||
b = self.body()
|
||||
users.append({"id": len(users) + 1, "username": b["username"], "name": b.get("name") or b["username"], "isAdmin": False, "sessions": 0, "lastSeenAt": None})
|
||||
return j({"ok": True})
|
||||
return j(users)
|
||||
m = re.fullmatch(r"/api/users/(\d+)(/password)?", p)
|
||||
if m:
|
||||
if method == "DELETE":
|
||||
users[:] = [u for u in users if u["id"] != int(m[1])]
|
||||
return j({"ok": True})
|
||||
if p == "/api/config":
|
||||
return j({"seedRules": seed_rules, "seedRuleDefaults": {**seed_rules, "minSeedHours": 72, "minRatio": 1.0},
|
||||
"sourcePrefs": source_prefs, "crawl": crawl, "tmdbConfigured": tmdb["on"]})
|
||||
targets = {"/api/config/seed-rules": seed_rules, "/api/config/source-prefs": source_prefs, "/api/config/crawl": crawl}
|
||||
if p in targets:
|
||||
targets[p].update(self.body())
|
||||
return j({"ok": True})
|
||||
if p == "/api/config/tmdb-key":
|
||||
tmdb["on"] = bool(self.body().get("key"))
|
||||
return j({"ok": True})
|
||||
if re.fullmatch(r"/api/ncore/torrents/\d+/languages", p):
|
||||
return j({"audio": ["hu", "en"], "subs": ["hu", "en"], "found": True})
|
||||
if p.startswith("/api/ncore"):
|
||||
return j({"configured": True, "username": "devuser", "loggedIn": True, "hasPasskey": True, "circuit": {"state": "ok"},
|
||||
"minIntervalMs": 2500, "lastRequestAt": "2026-10-25T09:58:00Z", "latestCrawl": {"lastRun": "2026-10-25T09:30:00Z"}})
|
||||
if p.startswith("/api/vpn"):
|
||||
if p == "/api/vpn" and method == "PUT":
|
||||
b = self.body()
|
||||
if "enabled" in b:
|
||||
vpn["enabled"] = b["enabled"]
|
||||
if "portForwarding" in b:
|
||||
vpn["pf"] = b["portForwarding"]
|
||||
on = vpn["enabled"]
|
||||
check = {"ok": True, "checkedAt": "2026-10-25T09:55:00Z", "publicIp": {"ip": "185.10.20.31", "country": "HU", "city": "Budapest", "org": "Proton AG"},
|
||||
"realIp": "84.1.2.3", "ipChanged": True, "routeDevice": "wg0", "dnsServers": ["10.2.0.1"], "dnsThroughTunnel": True}
|
||||
return j({"supported": True, "settings": {"enabled": on}, "state": "connected" if on else "off",
|
||||
"profile": {"name": "proton-hu-12.conf", "importedAt": "2026-09-01T12:00:00Z", "server": "185.10.20.30:51820", "addresses": ["10.2.0.2/32"]},
|
||||
"check": check if on else None,
|
||||
"tunnel": {"interface": "wg0", "lastHandshake": "2026-10-25T09:59:00Z", "transfer": {"rx": 52e9, "tx": 31e9}} if on else None,
|
||||
"traffic": {"path": "vpn" if on else "blocked", "reason": None if on else "A VPN ki van kapcsolva."},
|
||||
"portForwarding": {"enabled": vpn["pf"], "port": 51413 if vpn["pf"] and on else None, "gateway": "10.2.0.1", "lastRenewal": "2026-10-25T09:59:30Z"}})
|
||||
if p == "/api/torrents":
|
||||
return j({"rules": seed_rules, "engine": {"ready": True}, "seedKeeper": {"lastActivityAt": "2026-10-25T09:00:00Z"}, "diskUsed": 24e9, "items": torrents})
|
||||
m = re.fullmatch(r"/api/torrents/([0-9a-f]{40})(/keep)?", p)
|
||||
if m and m[2]:
|
||||
for t in torrents:
|
||||
if t["infoHash"] == m[1]:
|
||||
t["keep"] = self.body().get("keep", False)
|
||||
return j({"ok": True})
|
||||
if m and method == "DELETE":
|
||||
torrents[:] = [t for t in torrents if t["infoHash"] != m[1]]
|
||||
return j({"ok": True})
|
||||
if p == "/api/torrents/check":
|
||||
return j({"ok": True})
|
||||
if p == "/api/continue":
|
||||
return j([])
|
||||
if p == "/api/history":
|
||||
return j([{"title": v, "addedAt": None, "lastWatchedAt": None, "watchedEpisodes": 2} for v in my_list.values()])
|
||||
if re.fullmatch(r"/api/progress/(movie|tv)/([^/]+)/watched", p):
|
||||
return j({"ok": True})
|
||||
return None
|
||||
|
||||
def anime(self, method, p, q):
|
||||
"""Anime: real AniList data, made-up nyaa releases."""
|
||||
j = self.j
|
||||
if p == "/api/anime/home":
|
||||
trending = anime_page("TRENDING_DESC")["items"]
|
||||
popular = anime_page("POPULARITY_DESC")["items"]
|
||||
season = anime_page("POPULARITY_DESC", season="FALL", year=2026)["items"]
|
||||
cont = [{"anime": trending[0], "episode": 3, "position": 400, "duration": 1420}] if trending else []
|
||||
return j({"rows": [{"id": "season", "title": "Ősz 2026", "items": season}, {"id": "trending", "title": "Felkapott", "items": trending},
|
||||
{"id": "popular", "title": "Mindenkori kedvencek", "items": popular}],
|
||||
"continueWatching": cont, "season": {"season": "FALL", "year": 2026}, "source": "anilist"})
|
||||
if p == "/api/anime/browse":
|
||||
sorts = {"popularity": "POPULARITY_DESC", "score": "SCORE_DESC", "trending": "TRENDING_DESC", "newest": "START_DATE_DESC",
|
||||
"relevance": "SEARCH_MATCH", "title": "TITLE_ROMAJI"}
|
||||
sort = sorts.get(q.get("sort", ["popularity"])[0], "POPULARITY_DESC")
|
||||
genres = [x for x in q.get("genres", [""])[0].split(",") if x]
|
||||
return j(anime_page(sort, int(q.get("page", ["1"])[0]), q.get("search", [None])[0], genres or None))
|
||||
if p == "/api/anime/taxonomy":
|
||||
return j({"genres": ["Action", "Adventure", "Comedy", "Drama", "Fantasy", "Romance", "Sci-Fi", "Slice of Life", "Sports", "Mystery"],
|
||||
"tags": [{"name": "Isekai", "category": "Theme", "description": ""}, {"name": "Mecha", "category": "Theme", "description": ""}]})
|
||||
if p == "/api/anime/prefs":
|
||||
if method == "PUT":
|
||||
anime_prefs.update(self.body())
|
||||
return j(anime_prefs)
|
||||
if p == "/api/anime/torrents":
|
||||
return j({"graceSeconds": 900, "items": [{"infoHash": "c" * 40, "name": "[SubsPlease] Frieren - 03 (1080p).mkv", "size": 1.4e9, "episode": 3,
|
||||
"inUse": False, "lastUsedAt": "2026-10-25T09:40:00Z"}]})
|
||||
if p == "/api/anime/library":
|
||||
return j([{"anime": v} for v in anime_list.values()])
|
||||
if p == "/api/anime/progress":
|
||||
b = self.body()
|
||||
rows = [r for r in anime_progress.get(b["animeId"], []) if r["episode"] != b["episode"]]
|
||||
dur = b.get("duration")
|
||||
rows.append({"episode": b["episode"], "position": b["position"], "duration": dur, "completed": bool(dur and b["position"] / dur >= 0.9)})
|
||||
anime_progress[b["animeId"]] = rows
|
||||
return j({"ok": True})
|
||||
if p == "/api/anime/play/start":
|
||||
return j({"infoHash": "1" * 40, "fileIndex": 0, "fileName": os.path.basename(VIDEO or "none.mkv")})
|
||||
if re.fullmatch(r"/api/anime/torrents/[0-9a-f]{40}/keepalive", p):
|
||||
return j({"ok": True})
|
||||
m = re.fullmatch(r"/api/anime/(\d+)(/[a-z]+)?(/\d+/skip)?", p)
|
||||
if not m:
|
||||
return None
|
||||
i, sub = int(m[1]), m[2] or ""
|
||||
if sub == "/list":
|
||||
if method == "PUT":
|
||||
anime_list[i] = anime(anime_detail(i))
|
||||
else:
|
||||
anime_list.pop(i, None)
|
||||
return j({"ok": True})
|
||||
if sub == "/watched":
|
||||
return j({"ok": True})
|
||||
if sub == "/progress":
|
||||
return j(anime_progress.get(i, []))
|
||||
d = anime_detail(i)
|
||||
if sub == "":
|
||||
a = anime(d)
|
||||
a["mal"] = {"score": (d.get("averageScore") or 0) / 10, "scoredBy": 120000, "rank": 50}
|
||||
return j(a)
|
||||
if sub == "/franchise":
|
||||
edges = [e for e in d["relations"]["edges"] if e["relationType"] in ("PREQUEL", "SEQUEL") and e["node"]["format"] in ("TV", "MOVIE", "ONA")]
|
||||
out = [{"id": d["id"], "title": d["title"], "format": d["format"], "episodes": d.get("episodes"), "seasonYear": d.get("seasonYear"),
|
||||
"coverImage": d["coverImage"]["extraLarge"], "seasonNumber": 1 if edges else None, "current": True}]
|
||||
for n, e in enumerate(edges):
|
||||
x = e["node"]
|
||||
out.append({"id": x["id"], "title": x["title"], "format": x["format"], "episodes": x.get("episodes"), "seasonYear": x.get("seasonYear"),
|
||||
"coverImage": (x.get("coverImage") or {}).get("extraLarge"), "seasonNumber": n + 2 if x["format"] != "MOVIE" else None})
|
||||
return j(out)
|
||||
if sub == "/episodes" and m[3]:
|
||||
return j([{"type": "op", "start": 85, "end": 175, "episodeLength": 1420}, {"type": "ed", "start": 1300, "end": 1390, "episodeLength": 1420}])
|
||||
if sub == "/episodes":
|
||||
n = aired(d)
|
||||
return j({"aired": n, "total": d.get("episodes"),
|
||||
"episodes": [{"number": k, "title": f"{k}. epizód", "overview": "Egy rész leírása.", "runtime": d.get("duration")} for k in range(1, n + 1)]})
|
||||
if sub == "/releases":
|
||||
n = aired(d)
|
||||
groups = [("SubsPlease", 1080), ("Erai-raws", 1080), ("ToonsHub", 2160)]
|
||||
name = d["title"]["romaji"]
|
||||
eps = [{"number": k, "sources": [{"infoHash": f"{k:040x}", "nyaaId": k * 10 + n2, "torrentTitle": f"[{g}] {name} - {k:02d} ({r}p).mkv", "group": g,
|
||||
"resolution": r, "seeders": 300 - 40 * n2, "isBatch": False, "sizeBytes": 1.4e9 * (2 if r > 1080 else 1)}
|
||||
for n2, (g, r) in enumerate(groups)]} for k in range(1, n + 1)]
|
||||
return j({"queries": [name], "groups": [{"key": f"{g}|{r}", "episodes": list(range(1, n + 1)), "lang": {"englishDub": g == "ToonsHub"}} for g, r in groups],
|
||||
"selectedGroup": "SubsPlease|1080", "episodes": eps})
|
||||
return None
|
||||
|
||||
def image(self, u):
|
||||
if not u.startswith("https://"):
|
||||
return self.send_json({"error": "bad url"}, 400)
|
||||
|
||||
@@ -596,7 +596,8 @@ export component LinePage inherits Rectangle {
|
||||
}
|
||||
|
||||
// ---- settings side list ----
|
||||
if root.side: Headline {
|
||||
// Under the top nav its own tab already names the page.
|
||||
if root.side && !root.show-nav: Headline {
|
||||
x: Tv.safe-x;
|
||||
y: 56 * Tv.u;
|
||||
text: root.side-title;
|
||||
|
||||
@@ -175,7 +175,9 @@ export component PlayerScreen inherits Rectangle {
|
||||
}
|
||||
|
||||
// ---- skip prompt (anime) ----
|
||||
// Outside a layout a button would fill its parent: content width.
|
||||
skip := GlassButton {
|
||||
width: self.preferred-width;
|
||||
x: root.width - Tv.safe-x - self.width;
|
||||
y: root.height - (root.osd-t > 0.5 ? 340 : 120) * Tv.u;
|
||||
text: root.skip-label;
|
||||
@@ -289,6 +291,7 @@ export component PlayerScreen inherits Rectangle {
|
||||
b4 := GlassButton { icon: "next"; text: "Következő rész"; enabled: root.has-next; focused: root.buttons && root.osd-button == 4; alpha: root.has-next ? root.osd-a : 0; visible: root.has-next; }
|
||||
}
|
||||
b5 := GlassButton {
|
||||
width: self.preferred-width;
|
||||
x: root.width - Tv.safe-x - self.width;
|
||||
y: root.height - 146 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
|
||||
icon: "subtitles";
|
||||
|
||||
Reference in New Issue
Block a user