Compare commits
1 Commits
main
...
file-where
| Author | SHA1 | Date | |
|---|---|---|---|
| 5ef01593d7 |
@@ -1,11 +1,11 @@
|
||||
---
|
||||
name: ipx-prod-check
|
||||
description: Look for problems in production ipx (the ipx-web, iPX, ipx-directory and ipx-play containers on Tower, Tower itself and the monitoring that watches them) from their logs in Loki, their traces in Tempo and the metrics in Prometheus, and file what is found as Gitea issues. Use when asked to check on production, look for issues or errors in ipx, see why something is slow or failing in production, review the logs, or investigate a report about the live site.
|
||||
description: Look for problems in production ipx (the ipx-web, iPX and ipx-directory containers on Tower, Tower itself and the monitoring that watches them) from their logs in Loki, their traces in Tempo and the metrics in Prometheus, and file what is found as Gitea issues. Use when asked to check on production, look for issues or errors in ipx, see why something is slow or failing in production, review the logs, or investigate a report about the live site.
|
||||
---
|
||||
|
||||
# Checking production ipx
|
||||
|
||||
Production is four containers in the Arcane project `ipx` on Tower
|
||||
Production is three containers in the Arcane project `ipx` on Tower
|
||||
(`/mnt/fast/arcane/projects/ipx/compose.yaml`), one request passing through them in this order:
|
||||
|
||||
| container | what | logs, in Loki | traces, in Tempo | metrics, in Prometheus |
|
||||
@@ -13,12 +13,11 @@ Production is four containers in the Arcane project `ipx` on Tower
|
||||
| `ipx-web` | Caddy: serves the page, passes `/api` and `/media` to ipx (#203). Port 8099, the LAN and the tunnel | `{container="ipx-web"}`, JSON: a line a request (`http.log.access`), its own errors | service `ipx-web`: a span a request, passing `traceparent` on to ipx (#213) | `job="ipx-web"`: Caddy's own `caddy_http_*`, from `METRICS_BIND`, published as `192.168.1.130:9190` (#371) |
|
||||
| `iPX` | the daemon: API, scans, downloads, DeadAir | `{container="iPX"}`, JSON (`IPX_LOG_FORMAT=json`) | service `ipx`; passes `traceparent` to the directory | `job="ipx"`, its `/metrics` |
|
||||
| `ipx-directory` | the directory of public podcasts, `directory.ipxreader.app` (#204, #214) | `{container="ipx-directory"}`, JSON (`DIRECTORY_LOG_FORMAT=json`) | service `ipx-directory`: a span a request, joining ipx's trace when ipx called; a trace a refresher round (#213) | `job="ipx-directory"`, its `/metrics` |
|
||||
| `ipx-play` | the page a shared episode opens, `play.ipxreader.app` (#447); ipx sends it the episodes shared | `{container="ipx-play"}`, JSON (`PLAY_LOG_FORMAT=json`): a line a request (`ipx_play::http`), one a share | service `ipx-play`: a span a request, joining ipx's trace on a share | `job="ipx-play"`, its `/metrics` on `metrics_bind` (production `192.168.1.130:9191`, LAN only, #458) |
|
||||
|
||||
Grafana's alert rules (`grafana/alerts.py`, #365) watch all of it between checks: start by asking
|
||||
which are firing (the monitoring section). Under them, Tower itself: `job="node"` (the node exporter: load, CPU, memory, disks). The Grafana
|
||||
dashboard `iPX` draws all of it in that order (`grafana/dashboard.py`). A trace without the
|
||||
production tag (`resource.deployment.environment.name="production"`, on all four) is a daemon run
|
||||
production tag (`resource.deployment.environment.name="production"`, on all three) is a daemon run
|
||||
by hand, not production. Since #213 a request is one trace across the services it touched: a
|
||||
Directory page is ipx-web, then ipx, then the directory, so start from the trace, not the logs. Alloy ships the logs; Loki, Tempo and
|
||||
Prometheus publish no query port to this machine, so use the script beside this file:
|
||||
@@ -39,7 +38,7 @@ $Q flame '<TraceQL>' [since] [out.svg] # where the matching spans' time went,
|
||||
"Since the last deploy" is since that container started (each deploys on its own):
|
||||
|
||||
```sh
|
||||
for c in iPX ipx-web ipx-directory ipx-play; do S=$(docker inspect $c -f '{{.State.StartedAt}}'); echo "$c $(( ($(date +%s) - $(date -d "$S" +%s)) / 60 + 1 ))m"; done
|
||||
for c in iPX ipx-web ipx-directory; do S=$(docker inspect $c -f '{{.State.StartedAt}}'); echo "$c $(( ($(date +%s) - $(date -d "$S" +%s)) / 60 + 1 ))m"; done
|
||||
```
|
||||
|
||||
Start every check by seeing that all three run, since Loki cannot see a container that is not:
|
||||
@@ -423,12 +422,12 @@ container's lines are reaching Loki:
|
||||
```sh
|
||||
curl -s http://192.168.1.130:9090/api/v1/targets | python3 -c 'import json,sys
|
||||
for t in json.load(sys.stdin)["data"]["activeTargets"]: print(t["health"], t["labels"]["job"], t["scrapeUrl"], t.get("lastError","")[:80])'
|
||||
for c in iPX ipx-web ipx-directory ipx-play; do echo "$c $($Q metric "sum(count_over_time({container=\"$c\"} [24h]))" 24h | tail -1)"; done
|
||||
for c in iPX ipx-web ipx-directory; do echo "$c $($Q metric "sum(count_over_time({container=\"$c\"} [24h]))" 24h | tail -1)"; done
|
||||
docker ps -a --filter label=com.docker.compose.project=monitoring --format '{{.Names}} {{.Status}}'
|
||||
docker logs --since 1h tempo 2>&1 | grep -E 'failed to poll|blocklist poll complete' | tail -2
|
||||
```
|
||||
|
||||
`ipx`, `ipx-directory`, `ipx-play`, `ipx-web`, `node` and the monitoring's own, `prometheus`, `tempo`, `loki`
|
||||
`ipx`, `ipx-directory`, `ipx-web`, `node` and the monitoring's own, `prometheus`, `tempo`, `loki`
|
||||
and `alloy` (#366), should be `up`. Alloy is scraped at `alloy:12345` because its command sets
|
||||
`--server.http.listen-addr`; it listens on 127.0.0.1 without it.
|
||||
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
# Refuses a commit whose Rust is not as rustfmt writes it, or that clippy warns about. Clippy only
|
||||
# checks and never links, so it is light beside a test build (CLAUDE.md, Tests). It checks the
|
||||
# crates the commit touches and those built on them, not the workspace: ipx uses ipx-play and
|
||||
# ipx-directory, ipx-play uses ipx-directory, and all use ipx-feed and ipx-wire. A commit to the page alone runs nothing here.
|
||||
# ipx-directory, ipx-play uses ipx-directory, and all use ipx-feed. A commit to the page alone runs nothing here.
|
||||
staged=$(git diff --cached --name-only --diff-filter=ACMD)
|
||||
echo "$staged" | grep -q -e '\.rs$' -e 'Cargo\.toml$' -e '^Cargo\.lock$' || exit 0
|
||||
if ! cargo fmt --all --check >/dev/null 2>&1; then
|
||||
echo "pre-commit: the Rust is not formatted; run cargo fmt --all" >&2
|
||||
exit 1
|
||||
fi
|
||||
if echo "$staged" | grep -q -e '^Cargo\.toml$' -e '^Cargo\.lock$' -e '^crates/feed/' -e '^crates/wire/'; then
|
||||
pkgs="ipx-feed ipx-wire ipx-directory ipx-play ipx ipx-tui"
|
||||
if echo "$staged" | grep -q -e '^Cargo\.toml$' -e '^Cargo\.lock$' -e '^crates/feed/'; then
|
||||
pkgs="ipx-feed ipx-directory ipx-play ipx ipx-tui"
|
||||
elif echo "$staged" | grep -q '^crates/tui/'; then
|
||||
pkgs="ipx-tui"
|
||||
elif echo "$staged" | grep -q '^crates/directory/'; then
|
||||
|
||||
16
CLAUDE.md
16
CLAUDE.md
@@ -20,7 +20,7 @@ service of the `content` project, beside audiobookshelf, immich and Plex (#208).
|
||||
| Old database | `/mnt/user/ipx/state.db`, SQLite, used until the move to Postgres on 2026-09-18 and kept for rollback | `/data/state.db` |
|
||||
| Downloads | `/mnt/user/ipx/downloads` | `/downloads` |
|
||||
| Directory | `ipx-directory` in the same project, `192.168.1.130:8100`, public at `directory.ipxreader.app` through the tunnel with no Access in front: its pages are anyone's to browse, read only (#215), and its API (`/v1`) takes a token for everything. Until 2026-10-12 it was `ipx-dir.sdf1.net` (#214). Config `/mnt/fast/appdata/ipx-directory/directory.toml` (token hashes; Tower's own token in `tower.token` beside it, and entered in ipx's Admin, Directory, which keeps it in the database's `settings`, with the address ipx reaches it at: `http://ipx-directory:8100`, inside Docker, not the public address, which went out through Cloudflare and the tunnel, 170-340 ms a call where the directory answers in 16 ms), database `ipx_directory` on the same Postgres, URL in `directory.env` beside the compose file. See [docs/directory.md](docs/directory.md) | `/config/directory.toml` |
|
||||
| Shared episodes | `ipx-play` in the same project, `192.168.1.130:8102`, public at `play.ipxreader.app` through the tunnel with no Access in front: the page a shared episode opens, anyone's to see (#447). `/v1` takes a token. Config `/mnt/fast/appdata/ipx-play/play.toml` (token hashes; Tower's token entered in ipx's Admin, Directory, Sharing episodes, with the address `http://ipx-play:8102`), database `ipx_play` on the same Postgres, URL in `play.env` beside the compose file. Metrics for Prometheus on `192.168.1.130:9191`, LAN only, as `job="ipx-play"` (#458). See [docs/play.md](docs/play.md) | `/config/play.toml` |
|
||||
| Shared episodes | `ipx-play` in the same project, `192.168.1.130:8102`, public at `play.ipxreader.app` through the tunnel with no Access in front: the page a shared episode opens, anyone's to see (#447). `/v1` takes a token. Config `/mnt/fast/appdata/ipx-play/play.toml` (token hashes; Tower's token entered in ipx's Admin, Directory, Sharing episodes, with the address `http://ipx-play:8102`), database `ipx_play` on the same Postgres, URL in `play.env` beside the compose file. See [docs/play.md](docs/play.md) | `/config/play.toml` |
|
||||
| Home page | `ipxreader.app` (and `www`): a static page from `site/`, on the Cloudflare Pages project `ipxreader`, not on Tower. See below | |
|
||||
| Web UI | `ipx-web` (Caddy) in the same project, at `192.168.1.130:8099`, also `ipodderx.sdf1.net` via a Cloudflare tunnel. It serves the page and passes `/api` and `/media` to ipx, whose own port is published nowhere; its address on `ipx_default` is pinned to `192.168.64.10` (#203) | ipx `0.0.0.0:8099`, Caddy `:8080` |
|
||||
| Sign-in via the tunnel | Cloudflare Access app `ipodderx`, with Authentik as its identity provider; see [docs/sso.md](docs/sso.md) | Caddy passes `Cf-Access-*` only from `192.168.64.1`, the `ipx_default` gateway cloudflared arrives from (`TUNNEL_PEER`; the subnet is pinned in the compose file); ipx trusts them only from Caddy, `192.168.64.10`, and only with a valid `Cf-Access-Jwt-Assertion` (`access_team`, `access_aud`) |
|
||||
@@ -52,7 +52,7 @@ Deploying a change is: build and push the image, then pull it and recreate the c
|
||||
**Build only with `scripts/build-image.sh`, never a bare `docker buildx build`.** On 2026-11-04
|
||||
a plain build of ipx, its dependency layer invalidated by a `Cargo.toml` change, rebuilt
|
||||
everything in release on all twelve threads with 5 GB free; Tower thrashed for three hours with
|
||||
every core pegged and had to be rebooted. The script refuses to start under 6 GB available or
|
||||
every core pegged and had to be rebooted. The script refuses to start under 9 GB available or
|
||||
above load 12, and builds in the BuildKit container `ipx-capped` (made on first use), held to 6
|
||||
GB of memory and six threads by its cgroup: a build that outgrows that is killed, and production
|
||||
keeps running. If one is killed, say so and wait for the user to decide; do not raise the caps or go
|
||||
@@ -148,10 +148,7 @@ running the command and kills the session (exit 144), which has happened more th
|
||||
see [ios/README.md](ios/README.md). It builds only on a Mac with Xcode, from `ios/project.yml`
|
||||
through XcodeGen: nothing here compiles or checks the Swift, so say so when handing over a change
|
||||
to it. A change to the bridge's messages is a change to `native.ts`, `tests/native-bridge.ts` and
|
||||
`ios/Sources/Bridge.swift` together, and the page deploys first. The app's own calls to ipx (the
|
||||
player, the badge, CarPlay) are protobuf, from `ios/Sources/Wire`, generated from
|
||||
`crates/wire/proto` by `sh ios/scripts/proto.sh`: run it after changing a `.proto`, and deploy ipx
|
||||
before shipping an app that needs a new field.
|
||||
`ios/Sources/Bridge.swift` together, and the page deploys first.
|
||||
|
||||
## Before you touch the page
|
||||
|
||||
@@ -253,7 +250,7 @@ session was stopped. So:
|
||||
* Look at the load before and after each (`cat /proc/loadavg`). Above about 24, Tower's twelve
|
||||
threads twice over, wait for it to come down before starting another.
|
||||
* Test only what the change is in. ipx uses ipx-play and ipx-directory, ipx-play uses
|
||||
ipx-directory, and all use ipx-feed and ipx-wire, so:
|
||||
ipx-directory, and all use ipx-feed, so:
|
||||
|
||||
| changed | run |
|
||||
|---|---|
|
||||
@@ -263,8 +260,7 @@ session was stopped. So:
|
||||
| `crates/play/` | `cargo test -p ipx-play`, then `-p ipx` |
|
||||
| `crates/feed/` | `cargo test -p ipx-feed`, then `-p ipx-directory`, `-p ipx-play`, then `-p ipx` |
|
||||
| `crates/tui/` | `cargo test -p ipx-tui`; it uses only the API, none of the other crates |
|
||||
| `crates/wire/` | `cargo test -p ipx-wire`, then `-p ipx-play`, `-p ipx-directory`, then `-p ipx`; the browser suite, whose debug builds check every answer against the `.proto` |
|
||||
| `Cargo.toml`, `Cargo.lock` | all six, one at a time |
|
||||
| `Cargo.toml`, `Cargo.lock` | all five, one at a time |
|
||||
|
||||
The pre-commit hook's clippy follows the same table. The whole browser suite once, at the end
|
||||
of a change to the page or the API; never `cargo test` for the workspace in one command.
|
||||
@@ -420,7 +416,7 @@ ms in ipx, the difference being new connections, 80-330 ms each to open (#241).
|
||||
|
||||
Comments explain **why**, not what. If a line looks odd, the comment says what went wrong without
|
||||
it. No emoji, no exclamation marks, no "obviously". Prose in the UI and docs is plain English and
|
||||
addressed to the person using it. The words in the interface follow [docs/STYLE-GUIDE.md](docs/STYLE-GUIDE.md).
|
||||
addressed to the person using it.
|
||||
|
||||
Every change gets one line under `## [Unreleased]` in the changelog of the service it changes, in
|
||||
its [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) group: Added, Changed, Deprecated,
|
||||
|
||||
1526
Cargo.lock
generated
1526
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
11
Cargo.toml
11
Cargo.toml
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = ["crates/ipx", "crates/feed", "crates/directory", "crates/tui", "crates/play", "crates/wire"]
|
||||
members = ["crates/ipx", "crates/feed", "crates/directory", "crates/tui", "crates/play"]
|
||||
resolver = "3"
|
||||
|
||||
# Each service has its own version, in its own Cargo.toml (ipx, ipx-directory) or package.json
|
||||
@@ -15,7 +15,6 @@ unsafe_code = "forbid"
|
||||
ipx-feed = { path = "crates/feed" }
|
||||
ipx-directory = { path = "crates/directory" }
|
||||
ipx-play = { path = "crates/play" }
|
||||
ipx-wire = { path = "crates/wire" }
|
||||
ammonia = "4.1.4"
|
||||
anyhow = "1.0.104"
|
||||
argon2 = "0.6.0"
|
||||
@@ -26,22 +25,18 @@ chrono = { version = "0.4.45", default-features = false, features = ["std", "clo
|
||||
clap = { version = "4.6.6", features = ["derive"] }
|
||||
futures-util = { version = "0.3.34", default-features = false, features = ["std"] }
|
||||
jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] }
|
||||
librqbit = { version = "9.0.1", default-features = false, features = ["rust-tls", "http-api-client"] }
|
||||
opentelemetry = { version = "0.33", default-features = false, features = ["trace"] }
|
||||
opentelemetry-otlp = { version = "0.33", default-features = false, features = ["trace", "http-proto", "reqwest-blocking-client", "gzip-http"] }
|
||||
opentelemetry_sdk = { version = "0.33", default-features = false, features = ["trace"] }
|
||||
opml = "1.1.6"
|
||||
prost = "0.14.4"
|
||||
prost-build = "0.14"
|
||||
prost-reflect = { version = "0.16", features = ["serde"] }
|
||||
protox = "0.9"
|
||||
prost-types = "0.14"
|
||||
pulldown-cmark = { version = "0.13.4", default-features = false, features = ["html"] }
|
||||
mimalloc = "0.1.52"
|
||||
http = "1.5.0"
|
||||
hyper-util = { version = "0.1.20", features = ["client-legacy"] }
|
||||
percent-encoding = "2.3.2"
|
||||
quick-xml = { version = "0.42.0", features = ["escape-html"] }
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2", "gzip", "brotli", "zstd", "stream", "json", "form", "multipart", "charset", "system-proxy"] }
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2", "gzip", "brotli", "zstd", "stream", "json", "charset", "system-proxy"] }
|
||||
rss = "2.1.1"
|
||||
sea-orm = { version = "2.0.3", default-features = false, features = ["sqlx-sqlite", "sqlx-postgres", "runtime-tokio-rustls", "macros", "with-json", "sqlite-use-returning-for-3_35"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
|
||||
@@ -20,7 +20,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/
|
||||
RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,id=ipx-target,target=/src/target,sharing=locked \
|
||||
touch crates/ipx/src/main.rs crates/ipx/src/lib.rs crates/feed/src/lib.rs \
|
||||
crates/directory/src/lib.rs crates/play/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \
|
||||
crates/directory/src/lib.rs \
|
||||
&& cargo build --release --locked -p ipx \
|
||||
&& cp target/release/ipxd /usr/local/bin/ipxd
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/
|
||||
# of its own: built with ipx's, the two would rebuild shared crates for each other's features.
|
||||
RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,id=ipx-directory-target,target=/src/target,sharing=locked \
|
||||
touch crates/directory/src/main.rs crates/directory/src/lib.rs crates/feed/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \
|
||||
touch crates/directory/src/main.rs crates/directory/src/lib.rs crates/feed/src/lib.rs \
|
||||
&& cargo build --release --locked -p ipx-directory \
|
||||
&& cp target/release/ipx-directory /usr/local/bin/ipx-directory
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/
|
||||
# Compiled crates kept in the builder between builds (#438), in a target of its own.
|
||||
RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,id=ipx-play-target,target=/src/target,sharing=locked \
|
||||
touch crates/play/src/main.rs crates/play/src/lib.rs crates/directory/src/lib.rs crates/feed/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \
|
||||
touch crates/play/src/main.rs crates/play/src/lib.rs crates/directory/src/lib.rs crates/feed/src/lib.rs \
|
||||
&& cargo build --release --locked -p ipx-play \
|
||||
&& cp target/release/ipx-play /usr/local/bin/ipx-play
|
||||
|
||||
|
||||
@@ -5,8 +5,6 @@ WORKDIR /src
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev
|
||||
COPY web ./web
|
||||
# The protobuf messages the page reads its answers in (#470).
|
||||
COPY crates/wire/proto ./crates/wire/proto
|
||||
RUN node web/build.mts /dist
|
||||
|
||||
FROM caddy:2
|
||||
|
||||
@@ -19,7 +19,7 @@ behind iPodderX (2004-2008, Ray Slakinski & August Trometer).
|
||||
- **Scanning.** Feeds are checked on a schedule, globally or per feed, and a feed's own TTL is
|
||||
honoured. Keyword, explicit-content and media-type filters decide what is downloaded, with a limit
|
||||
on how many of a feed's newest episodes are downloaded.
|
||||
- **Downloads.** Files come over HTTP, BitTorrent through qBittorrent, or Usenet through SABnzbd, and are filed into a folder per feed.
|
||||
- **Downloads.** Files come over HTTP or BitTorrent and are filed into a folder per feed.
|
||||
Retention deletes the oldest files to stay under a disk quota or an age limit, and never touches
|
||||
an item someone has pinned.
|
||||
- **OPML.** You can import and export your own subscriptions. You can also subscribe to an OPML
|
||||
@@ -37,8 +37,8 @@ docker compose up -d
|
||||
|
||||
`docker-compose.yml` is a sample: ipx, with its database in SQLite and its three volumes
|
||||
(`/config`, `/data` and `/downloads`) in folders beside the file, and ipx-web, the page, served by
|
||||
Caddy in front of it. Change them to suit. The UI is on port 8099. Torrents need a qBittorrent
|
||||
of your own, set in `[torrent]`, and NZBs a SABnzbd, set in `[nzb]` (docs/configuration.md). Files are written as `PUID`/`PGID`, 99:100 by default.
|
||||
Caddy in front of it. Change them to suit. The UI is on port 8099. BitTorrent uses 6881
|
||||
over TCP and UDP. Files are written as `PUID`/`PGID`, 99:100 by default.
|
||||
|
||||
From source:
|
||||
|
||||
|
||||
@@ -12,15 +12,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- `/v1` answers in protobuf for a client that asks for it (`Accept: application/x-protobuf`) and takes a snapshot sent so; JSON stays the default. The messages are in `crates/wire/proto/directory.proto`, and answers go through structs generated from them (#465, #470).
|
||||
- A `robots.txt` and a sitemap listing the home page, A to Z, every category and every feed, so search engines find the pages, not only the links between them (#380).
|
||||
- `/metrics` counts its requests and their times by route and status, the feeds it checks and those that failed, and the snapshots it takes (#370).
|
||||
- Its log lines inside a trace carry the trace's and span's ids, as ipx's do, so a failed feed check leads to its trace (#375).
|
||||
|
||||
### Changed
|
||||
|
||||
- On a phone the directory's pages fit at 200% zoom without scrolling sideways, its tabs, buttons and search box are 40 px to tap, and a link does not stay underlined after a tap (#507).
|
||||
- An episode its feed gives no title is named by the opening of its text or else its file's name, where it had none (#502).
|
||||
- Its checks of YouTube channels go one at a time, two seconds apart, since YouTube refuses many asked together (#386).
|
||||
- Its JSON log lines no longer carry their span, once on its own and again in a list, which said nothing the line's own fields did not (#363).
|
||||
|
||||
@@ -28,11 +25,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
- A YouTube channel's check no longer fails on the 404 or 500 YouTube answers some feed requests with and does not mean: it is asked again, twice, a second apart (#382).
|
||||
|
||||
### Security
|
||||
|
||||
- Built with SQLite 3.54 (libsqlite3-sys 0.40, through sqlx 0.9.1), past an advisory on opening a crafted database (RUSTSEC-2026-0459, #467), and url 2.5.9, which a web address nested thousands of times in `blob:` can no longer crash (RUSTSEC-2026-0592, #492).
|
||||
- Feeds and Markdown items are read with pulldown-cmark 0.13.6, and compressed answers with zstd 0.14.4 and zstd-safe 8.3, each closing published advisories (#467).
|
||||
|
||||
## [1.4.1] - 2026-10-24
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -18,7 +18,6 @@ axum.workspace = true
|
||||
clap.workspace = true
|
||||
futures-util.workspace = true
|
||||
ipx-feed.workspace = true
|
||||
ipx-wire.workspace = true
|
||||
opentelemetry.workspace = true
|
||||
opentelemetry-otlp.workspace = true
|
||||
opentelemetry_sdk.workspace = true
|
||||
|
||||
@@ -17,18 +17,6 @@ use tower_http::compression::CompressionLayer;
|
||||
use tower_http::decompression::RequestDecompressionLayer;
|
||||
use tracing::Instrument;
|
||||
|
||||
/// Each route's protobuf messages (#465), beside its JSON.
|
||||
const WIRE: ipx_wire::Routes = &[
|
||||
("GET", "/v1/me", "", "directory.Me"),
|
||||
("GET", "/v1/feeds", "", "directory.Listings"),
|
||||
("GET", "/v1/popular", "", "directory.Listings"),
|
||||
("GET", "/v1/feeds/{id}", "", "directory.FeedPage"),
|
||||
("POST", "/v1/feeds/{id}/refresh", "", "directory.FeedPage"),
|
||||
("POST", "/v1/snapshot", "directory.Snapshot", "directory.SnapshotResult"),
|
||||
("GET", "/v1/blocked", "", "directory.BlockedList"),
|
||||
("GET", "/v1/instances", "", "directory.Instances"),
|
||||
];
|
||||
|
||||
/// Every route: the API under `/v1`, behind a token, and the public pages.
|
||||
pub fn router(dir: Shared) -> Router {
|
||||
let v1 = Router::new()
|
||||
@@ -42,7 +30,6 @@ pub fn router(dir: Shared) -> Router {
|
||||
.route("/v1/blocked/{id}", delete(unblock))
|
||||
.route("/v1/instances", get(instances))
|
||||
.route("/v1/instances/{name}", delete(drop_instance))
|
||||
.route_layer(axum::middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
|
||||
.layer(axum::middleware::from_fn_with_state(dir.clone(), authenticate));
|
||||
Router::new()
|
||||
.route("/healthz", get(healthz))
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
html{-webkit-text-size-adjust:100%}
|
||||
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
||||
a{color:var(--accent);text-decoration:none}
|
||||
@media (hover:hover){a:hover{text-decoration:underline}}
|
||||
a:hover{text-decoration:underline}
|
||||
a:focus-visible,button:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
||||
header{display:flex;align-items:center;gap:16px;padding:12px 20px;background:var(--panel);border-bottom:1px solid var(--line);position:sticky;top:0;z-index:1}
|
||||
.brand{display:flex;align-items:center;gap:10px;color:var(--fg);font-weight:700;font-size:17px;white-space:nowrap}
|
||||
@@ -29,21 +29,21 @@ h3{font-size:17px;margin:28px 0 8px}
|
||||
/* A grid item is as wide as its content unless told otherwise, and a long title then runs off the page. */
|
||||
.chart li,.tile{min-width:0}
|
||||
.chart a{display:flex;align-items:center;gap:12px;padding:8px;border-radius:10px;color:var(--fg)}
|
||||
@media (hover:hover){.chart a:hover{background:var(--panel);text-decoration:none}}
|
||||
.chart a:hover{background:var(--panel);text-decoration:none}
|
||||
.no{width:22px;text-align:right;color:var(--faint);font-variant-numeric:tabular-nums;flex:none}
|
||||
.txt{display:flex;flex-direction:column;min-width:0}
|
||||
.txt b,.tile b{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
small{color:var(--dim);font-size:13px}
|
||||
.cats{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(180px,100%),1fr));gap:12px}
|
||||
.cats{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px}
|
||||
.cat{display:flex;flex-direction:column;gap:2px;padding:14px 16px;border-radius:12px;background:var(--panel);border:1px solid var(--line);color:var(--fg)}
|
||||
@media (hover:hover){.cat:hover{border-color:var(--accent);text-decoration:none}}
|
||||
.cat:hover{border-color:var(--accent);text-decoration:none}
|
||||
.tabs,.pills{display:flex;gap:6px;flex-wrap:wrap;margin:0 0 12px}
|
||||
.tabs a,.pills a{padding:6px 14px;border-radius:999px;background:var(--panel);border:1px solid var(--line);color:var(--fg);font-size:14px}
|
||||
.tabs a[aria-current],.pills a[aria-current]{background:var(--accent);border-color:var(--accent);color:var(--ink)}
|
||||
.pills a[aria-current] small{color:inherit}
|
||||
.tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:18px 14px}
|
||||
.tile{display:flex;flex-direction:column;gap:4px;min-width:0;color:var(--fg)}
|
||||
@media (hover:hover){.tile:hover{text-decoration:none}.tile:hover b{text-decoration:underline}}
|
||||
.tile:hover{text-decoration:none}.tile:hover b{text-decoration:underline}
|
||||
.show{display:flex;gap:24px;align-items:flex-end;margin-top:8px}
|
||||
.meta{display:flex;flex-direction:column;gap:6px;min-width:0;flex:1}
|
||||
.meta h2{margin:0;font-size:28px;line-height:1.15;overflow-wrap:anywhere}
|
||||
@@ -58,17 +58,9 @@ button{font:inherit;font-weight:600;padding:8px 16px;border-radius:10px;border:0
|
||||
article{padding:12px 0;border-bottom:1px solid var(--line);max-width:80ch}
|
||||
article p{margin:4px 0;color:var(--dim)}
|
||||
@media (max-width:600px){
|
||||
header{padding:10px 16px;gap:10px;flex-wrap:wrap}
|
||||
/* Under the name rather than squeezed beside it: at 200% zoom the two did not fit (#507). */
|
||||
header form{flex:1 1 100%}
|
||||
/* 40 px to tap, as the style guide asks of a phone (#507). */
|
||||
.tabs a,.pills a{padding:9px 14px}
|
||||
button,input{padding-top:10px;padding-bottom:10px}
|
||||
header{padding:10px 16px;gap:10px}
|
||||
.brand span,.brand{font-size:15px}
|
||||
/* Its name may take two lines: on one, it ran past the edge at 200% zoom (#507). */
|
||||
.brand{white-space:normal}
|
||||
/* A word too long for the line breaks rather than pushing the page sideways at 200% zoom (#507). */
|
||||
main{padding:16px;overflow-wrap:anywhere}
|
||||
main{padding:16px}
|
||||
.show{flex-direction:column;align-items:flex-start;gap:14px}
|
||||
.art.lg{width:140px}
|
||||
.tiles{grid-template-columns:repeat(auto-fill,minmax(104px,1fr));gap:14px 10px}
|
||||
|
||||
@@ -97,98 +97,3 @@ pub struct Blocked {
|
||||
/// The most a snapshot may list: far more than one server's subscriptions, few enough that one
|
||||
/// request cannot hold the database for long.
|
||||
pub const MAX_SNAPSHOT: usize = 20_000;
|
||||
|
||||
// The same in protobuf (#470): ipx reads and writes these through ipx-wire's structs, which
|
||||
// mirror the ones above field for field.
|
||||
use ipx_wire::pb::directory as pb;
|
||||
|
||||
impl From<pb::Listing> for Listing {
|
||||
fn from(l: pb::Listing) -> Self {
|
||||
Listing {
|
||||
id: l.id,
|
||||
url: l.url,
|
||||
title: l.title,
|
||||
image: l.image,
|
||||
category: l.category,
|
||||
subcategory: l.subcategory,
|
||||
podcast: l.podcast,
|
||||
subscribers: l.subscribers,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pb::Item> for Item {
|
||||
fn from(i: pb::Item) -> Self {
|
||||
Item {
|
||||
guid: i.guid,
|
||||
title: i.title,
|
||||
link: i.link,
|
||||
published: i.published,
|
||||
duration: i.duration,
|
||||
description: i.description,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pb::FeedPage> for FeedPage {
|
||||
fn from(p: pb::FeedPage) -> Self {
|
||||
FeedPage {
|
||||
listing: Listing {
|
||||
id: p.id,
|
||||
url: p.url,
|
||||
title: p.title,
|
||||
image: p.image,
|
||||
category: p.category,
|
||||
subcategory: p.subcategory,
|
||||
podcast: p.podcast,
|
||||
subscribers: p.subscribers,
|
||||
},
|
||||
description: p.description,
|
||||
failing: p.failing,
|
||||
items: p.items.into_iter().map(Item::from).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::Me> for Me {
|
||||
type Error = String;
|
||||
fn try_from(m: pb::Me) -> Result<Self, String> {
|
||||
let access = match m.access.as_str() {
|
||||
"ro" => Access::Ro,
|
||||
"rw" => Access::Rw,
|
||||
"rwa" => Access::Rwa,
|
||||
other => return Err(format!("an access level not known here: {other:?}")),
|
||||
};
|
||||
Ok(Me { name: m.name, access })
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pb::Instance> for Instance {
|
||||
fn from(i: pb::Instance) -> Self {
|
||||
Instance { name: i.name, feeds: i.feeds, subscribers: i.subscribers }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pb::Blocked> for Blocked {
|
||||
fn from(b: pb::Blocked) -> Self {
|
||||
Blocked { id: b.id, url: b.url, title: b.title, at: b.at }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pb::SnapshotResult> for SnapshotResult {
|
||||
fn from(r: pb::SnapshotResult) -> Self {
|
||||
let n = |v: u64| usize::try_from(v).unwrap_or(usize::MAX);
|
||||
SnapshotResult {
|
||||
accepted: n(r.accepted),
|
||||
refused_private: n(r.refused_private),
|
||||
refused_blocked: n(r.refused_blocked),
|
||||
refused_invalid: n(r.refused_invalid),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SnapshotEntry> for pb::SnapshotEntry {
|
||||
fn from(e: &SnapshotEntry) -> Self {
|
||||
pb::SnapshotEntry { url: e.url.clone(), subscribers: e.subscribers, category: e.category.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ chrono.workspace = true
|
||||
http.workspace = true
|
||||
hyper-util.workspace = true
|
||||
opml.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
pulldown-cmark.workspace = true
|
||||
quick-xml.workspace = true
|
||||
reqwest.workspace = true
|
||||
|
||||
@@ -21,7 +21,7 @@ pub use failure::{Failure, explain_failure, failure_kind, is_temporary_lookup_fa
|
||||
pub use fetch::{FEED_SILENCE, FEED_TIMEOUT, FETCHED_BYTES, FETCHES, Fetched, fetch, is_youtube_feed};
|
||||
pub use jev::{JEV_URL, classify};
|
||||
pub use outlines::{collect_outlines, is_opml, opml_title, parse_opml, read_opml};
|
||||
pub use parse::{Enclosure, Entry, ParsedFeed, markdown_html, parse, same_file_key, untitled_name};
|
||||
pub use parse::{Enclosure, Entry, ParsedFeed, markdown_html, parse, same_file_key};
|
||||
pub use patreon::{is_patreon_creator, patreon_shows, same_feed};
|
||||
pub use privacy::{redact, redact_text, url_looks_private};
|
||||
|
||||
|
||||
@@ -46,9 +46,6 @@ pub struct Entry {
|
||||
pub duration: Option<i64>,
|
||||
pub episode: Option<i64>,
|
||||
pub season: Option<i64>,
|
||||
/// Where its chapters are, `<podcast:chapters url>`: a JSON file of the Podcasting 2.0
|
||||
/// namespace's, read when someone plays it (#477).
|
||||
pub chapters: Option<String>,
|
||||
pub enclosures: Vec<Enclosure>,
|
||||
}
|
||||
|
||||
@@ -62,53 +59,9 @@ pub struct Enclosure {
|
||||
pub length: Option<i64>,
|
||||
}
|
||||
|
||||
/// RSS first, then Atom -- the same split the original made on `parsedFeed.version`. An item
|
||||
/// without a title is named here, once, for everything that shows it (#502).
|
||||
/// RSS first, then Atom -- the same split the original made on `parsedFeed.version`.
|
||||
#[tracing::instrument(skip_all, fields(bytes = bytes.len()))]
|
||||
pub fn parse(bytes: &[u8]) -> Result<ParsedFeed> {
|
||||
let mut feed = parse_any(bytes)?;
|
||||
for e in &mut feed.entries {
|
||||
if e.title.is_none() {
|
||||
e.title = untitled_name(e.description.as_deref(), e.enclosures.first().map(|x| x.url.as_str()));
|
||||
}
|
||||
}
|
||||
Ok(feed)
|
||||
}
|
||||
|
||||
/// A name for an item its feed gave no title: the first words of its text, cut at a word near
|
||||
/// 120 characters, or else its file's name without the extension. What the page worked out each
|
||||
/// time it drew one, until the iOS widget, CarPlay and search, which never saw it, needed it too.
|
||||
pub fn untitled_name(description: Option<&str>, file: Option<&str>) -> Option<String> {
|
||||
// Entities decoded, spaces made single; a tag is a space, so "2010)</p><p>Recorded" stays apart.
|
||||
let words = description
|
||||
.and_then(|d| title_text(Some(&text_of(d).split_whitespace().collect::<Vec<_>>().join(" "))))
|
||||
.unwrap_or_default();
|
||||
if !words.is_empty() {
|
||||
let mut chars = words.chars();
|
||||
let head: String = chars.by_ref().take(120).collect();
|
||||
if chars.next().is_none() {
|
||||
return Some(words);
|
||||
}
|
||||
// The word the cut fell in is dropped whole, as the page's /\s+\S*$/ did.
|
||||
let cut = head.rfind(char::is_whitespace).map_or(head.as_str(), |at| head[..at].trim_end());
|
||||
return Some(format!("{cut}\u{2026}"));
|
||||
}
|
||||
let path = file?.split(['?', '#']).next()?;
|
||||
let last = path.rsplit('/').next().filter(|s| !s.is_empty())?;
|
||||
let stem = match last.rsplit_once('.') {
|
||||
Some((stem, ext))
|
||||
if !stem.is_empty() && (1..=5).contains(&ext.len()) && ext.chars().all(|c| c.is_ascii_alphanumeric()) =>
|
||||
{
|
||||
stem
|
||||
}
|
||||
_ => last,
|
||||
};
|
||||
let name =
|
||||
percent_encoding::percent_decode_str(stem).decode_utf8().map_or_else(|_| stem.to_owned(), |d| d.into_owned());
|
||||
non_empty(Some(&name))
|
||||
}
|
||||
|
||||
fn parse_any(bytes: &[u8]) -> Result<ParsedFeed> {
|
||||
if bytes.trim_ascii_start().starts_with(b"[")
|
||||
&& let Ok(posts) = serde_json::from_slice::<Vec<serde_json::Value>>(bytes)
|
||||
{
|
||||
@@ -330,7 +283,6 @@ pub(crate) fn from_rss(ch: rss::Channel, bytes: &[u8]) -> ParsedFeed {
|
||||
duration: it.and_then(|i| i.duration()).and_then(parse_duration),
|
||||
episode: it.and_then(|i| i.episode()).and_then(|e| e.trim().parse().ok()),
|
||||
season: it.and_then(|i| i.season()).and_then(|e| e.trim().parse().ok()),
|
||||
chapters: podcast_chapters(item),
|
||||
enclosures,
|
||||
})
|
||||
})
|
||||
@@ -396,7 +348,6 @@ pub(crate) fn from_atom(feed: atom_syndication::Feed) -> ParsedFeed {
|
||||
duration: None,
|
||||
episode: None,
|
||||
season: None,
|
||||
chapters: None,
|
||||
enclosures,
|
||||
})
|
||||
})
|
||||
@@ -509,12 +460,6 @@ pub(crate) fn notes(content: Option<&str>, description: Option<&str>, markdown:
|
||||
///
|
||||
/// shortcut: found by the `source` prefix the namespace's own docs and feeds use; a feed binding
|
||||
/// it to another prefix is not read, until one turns up.
|
||||
/// `<podcast:chapters url="..." type="application/json+chapters">`, by the prefix feeds give it.
|
||||
fn podcast_chapters(item: &rss::Item) -> Option<String> {
|
||||
let url = item.extensions().get("podcast")?.get("chapters")?.first()?.attrs().get("url")?.trim();
|
||||
(url.starts_with("http://") || url.starts_with("https://")).then(|| url.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn source_markdown(item: &rss::Item) -> Option<&str> {
|
||||
item.extensions().get("source")?.get("markdown")?.first()?.value()
|
||||
}
|
||||
@@ -657,37 +602,6 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::failure;
|
||||
|
||||
#[test]
|
||||
fn an_untitled_item_is_named_by_its_words_or_its_file() {
|
||||
// Short text whole, decoded, the blocks kept apart.
|
||||
assert_eq!(
|
||||
untitled_name(Some("<p>Fish & chips (2010)</p><p>Recorded</p>"), None).as_deref(),
|
||||
Some("Fish & chips (2010) Recorded")
|
||||
);
|
||||
// Long text cut at the last whole word inside 120 characters.
|
||||
let long = "word ".repeat(40);
|
||||
let name = untitled_name(Some(&long), None).unwrap();
|
||||
assert_eq!(name, format!("{}\u{2026}", "word ".repeat(24).trim_end()));
|
||||
assert!(name.chars().count() <= 121);
|
||||
// No text: the file's name, its query and extension gone, its escapes decoded.
|
||||
assert_eq!(
|
||||
untitled_name(Some("<img src=x>"), Some("https://x.example/a/Ep%2042.mp3?t=1")).as_deref(),
|
||||
Some("Ep 42")
|
||||
);
|
||||
assert_eq!(untitled_name(None, Some("https://x.example/")), None);
|
||||
assert_eq!(untitled_name(None, None), None);
|
||||
// Through parse: the feed's own title is kept, and only a missing one is made.
|
||||
let feed = parse(
|
||||
br#"<rss version="2.0"><channel><title>t</title>
|
||||
<item><guid>a</guid><description>Hello there</description></item>
|
||||
<item><guid>b</guid><title>Kept</title><description>Not this</description></item>
|
||||
</channel></rss>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let titles: Vec<_> = feed.entries.iter().map(|e| e.title.as_deref()).collect();
|
||||
assert_eq!(titles, [Some("Hello there"), Some("Kept")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_rss_with_itunes_extensions() {
|
||||
let bytes = include_bytes!("../../../tests/data/rss2.xml");
|
||||
@@ -985,21 +899,6 @@ Some **bold** and [a link](https://x.example/).</description></item>
|
||||
assert_eq!((p1.season, p1.episode), (Some(8), Some(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_items_chapters_are_where_podcast_chapters_says() {
|
||||
let xml = br#"<?xml version="1.0"?>
|
||||
<rss version="2.0" xmlns:podcast="https://podcastindex.org/namespace/1.0">
|
||||
<channel><title>Show</title><link>https://x</link><description>d</description>
|
||||
<item><title>A</title><guid>a</guid>
|
||||
<podcast:chapters url=" https://x/a.json " type="application/json+chapters"/></item>
|
||||
<item><title>B</title><guid>b</guid><podcast:chapters url="file:///etc/passwd"/></item>
|
||||
<item><title>C</title><guid>c</guid></item>
|
||||
</channel></rss>"#;
|
||||
let feed = parse(xml).unwrap();
|
||||
let got: Vec<_> = feed.entries.iter().map(|e| e.chapters.as_deref()).collect();
|
||||
assert_eq!(got, [Some("https://x/a.json"), None, None], "only a web address, trimmed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_item_may_carry_several_enclosures() {
|
||||
// The rss crate keeps only one per item -- the last -- so these come from the XML.
|
||||
|
||||
@@ -14,13 +14,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- Episodes published as NZBs download through SABnzbd, set in `[nzb]`, as torrents do through qBittorrent; with none set they are held back instead of filed as the episode (#496).
|
||||
- An episode's chapters, from the chapters file its feed names (`<podcast:chapters>`) or else from the downloaded file itself, at `GET /api/enclosures/{id}/chapters`, in the clock of DeadAir's shortened copy when that is what plays; episodes already out pick theirs up at the next scan (#477).
|
||||
- `GET /api/feeds/{id}/seasons` gives a podcast's seasons with how many episodes and unread each has, and a podcast's episodes can be asked for one season at a time, or for those naming none (`season=none`), and in its own order (`sort=episode`), season by season and episode by episode. `download-latest` takes a `season` to download all of it, first episode first (#482).
|
||||
- Smart playlists: `GET` and `POST /api/playlists`, `PATCH` and `DELETE /api/playlists/{id}`, and `GET /api/playlists/{id}/entries`, the episodes of the podcasts chosen in the playlist's order, those set to play first ahead of the rest (#476).
|
||||
- A feed in `/api/feeds` says whether it has audio or video (`podcast`), for the page's Podcasts shelf (#474).
|
||||
- Up Next, a queue of episodes kept per account so every device shares it: `GET /api/queue` lists it in order, `PUT /api/queue` sets it, and an episode leaves it once it is 90% played (#473).
|
||||
- The API answers in protobuf as well as JSON: a client that sends `Accept: application/x-protobuf` gets protobuf, and one that sends `Content-Type: application/x-protobuf` may send its body so; JSON stays the default for a client that does not ask, and an answer of null stays JSON. The messages are in `crates/wire/proto/ipx.proto`. ipx's own calls to the directory and ipx-play go in protobuf too, so both need their protobuf releases first. Answers and those calls go through structs generated from the `.proto` files, about four times quicker to read than the JSON (#465, #470).
|
||||
- Sharing an episode gives a link to its page on ipx-play, which anyone can open and play, set up in Admin, Directory, Sharing episodes; private and paid feeds still share their own address (#447).
|
||||
- The iOS app's icon count stays right with the app closed: with `[push]` set to an APNs key, ipx sends each registered phone (`POST /api/push/devices`, removed with `DELETE`) its All Subscriptions unread count through Apple's push service, within a minute of a change (#433). The push also wakes the app for a moment, for its widget to show the same count (#428).
|
||||
- A place in an episode saved from DeadAir's shortened version names its file (`deadair` in `POST .../position`), so it is read in that version's clock even when ipx never handed out its playlist, as for a copy kept on the device or after a restart (#412).
|
||||
@@ -31,9 +24,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Changed
|
||||
|
||||
- A feed whose items have not changed is checked less often even when its server rewrites it at every read, as Substack's build time and Patreon's signed file links do: it is judged by its items, not its bytes. An item's text edited with nothing else changed shows at the next full read, at most four hours on (#503).
|
||||
- An item its feed gives no title is named as it is stored, by the opening of its text or else its file's name, so search, Signals, the iOS widget and CarPlay show the same name the page does; the untitled items already stored are named once at start (#502).
|
||||
- Torrents go to qBittorrent through its Web API, set in `[torrent]` (`qbittorrent_url`, `username`, `password`, `save_path`), which downloads and seeds them until the episode is deleted; ipx no longer runs a BitTorrent client of its own or listens on 6881, and `port_range` is gone. Without a qBittorrent set, torrents are held back as when they are turned off (#494, #495).
|
||||
- The server's command is `ipxd`, not `ipx`: `ipxd daemon`, `ipxd status`, `ipxd user add` and the rest, in the container as `docker exec iPX ipxd ...`. `ipx` is now the reader in a terminal (#437).
|
||||
|
||||
- The log no longer has a line for every request that went well, over half its size: `/metrics` counts each request and its time by route and status as `ipx_http_request_duration_seconds`, a request that failed keeps its warning, and the admin page's log view still shows them all (#364).
|
||||
@@ -41,12 +31,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Fixed
|
||||
|
||||
- Counting the files waiting to download, which the status and the metrics do every 30 seconds, reads only those files instead of every one ipx knows of: about 1 ms instead of 90 (#489).
|
||||
- Downloading a season takes back the files of it retention removed, rather than queuing nothing, and no file on its way already is queued twice (#483).
|
||||
- A feed an OPML stops listing leaves All Subscriptions with it, rather than its items staying there with no feed name beside them: the scan no longer reads it again after the list drops it, and its subscriptions go with it, as they do when a feed is removed with `ipx rm`. Any left from before are removed when ipx starts (#478).
|
||||
- Searching All Subscriptions answers in a fraction of a second, not five: a search reads each item's title and text without its markup, indexed on Postgres, and still finds part of a word. It no longer matches words inside the HTML's tags, such as a link's address. Text past the first 4,000 characters of a very long post is not searched (#459, #472).
|
||||
- Artwork that cannot be shown is asked for again a day later rather than every hour: one too large is refused on its stated size before it is read, and a refusal from the publisher or one ipx makes (too large, not an image) is remembered for a day; JPEG XL pictures sent without a type are shown (#448).
|
||||
- `ipx reap --dry-run` says "would delete" of each file and of the total, rather than "deleted", word for word a real reap, of files it kept (#461).
|
||||
- Subscribing to a feed someone here already reads puts its recent items to your Signals at once, rather than at the judge's next pass, up to five minutes later (#415).
|
||||
- A download a restart stopped, a deploy's for one, is taken up again as the daemon starts, rather than waiting for its feed's next check, an hour or a day away (#410).
|
||||
- A YouTube channel no longer misses most days' videos: YouTube answers some feed requests with a 404 or 500 it does not mean, and ipx now asks again, twice, a second apart, before calling the feed failing (#382), and then every hour for a day where it would have waited a day, since YouTube's failures run for hours; and its YouTube feeds are read one at a time, two seconds apart, since YouTube refuses many asked together (#386).
|
||||
@@ -56,8 +40,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Security
|
||||
|
||||
- Built with SQLite 3.54 (libsqlite3-sys 0.40, through sqlx 0.9.1), past an advisory on opening a crafted database (RUSTSEC-2026-0459, #467), and url 2.5.9, which a web address nested thousands of times in `blob:` can no longer crash (RUSTSEC-2026-0592, #492).
|
||||
- Show notes are cleaned with ammonia 4.2.5, which no longer lets SVG or MathML in a feed's HTML carry script past it (RUSTSEC-2026-0533); Markdown items are read with pulldown-cmark 0.13.6, and compressed feeds and answers with zstd 0.14.4 and zstd-safe 8.3, each closing published advisories (#467).
|
||||
- Ten wrong passwords from one address in a quarter hour hold that address off sign-in for the rest of it, answered `429` with how long to wait; before, a guesser could try as fast as the server checked. The address is the one a trusted proxy names last in `X-Forwarded-For`, or the peer's (#409).
|
||||
|
||||
## [1.5.1] - 2026-10-24
|
||||
|
||||
@@ -17,7 +17,6 @@ workspace = true
|
||||
ipx-feed.workspace = true
|
||||
ipx-directory.workspace = true
|
||||
ipx-play.workspace = true
|
||||
ipx-wire.workspace = true
|
||||
ammonia.workspace = true
|
||||
anyhow.workspace = true
|
||||
argon2.workspace = true
|
||||
@@ -27,6 +26,7 @@ chrono.workspace = true
|
||||
clap.workspace = true
|
||||
futures-util.workspace = true
|
||||
jsonwebtoken.workspace = true
|
||||
librqbit.workspace = true
|
||||
opentelemetry.workspace = true
|
||||
opentelemetry_sdk.workspace = true
|
||||
opml.workspace = true
|
||||
|
||||
@@ -92,10 +92,6 @@ pub fn write(file: &Path, kind: &str, body: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// How long an address that could not be fetched is answered from memory before it is tried again.
|
||||
const RETRY: Duration = Duration::from_secs(60 * 60);
|
||||
/// The same for a failure the publisher will not change by morning: too large, not an image, a
|
||||
/// 4xx. At an hour, five GIFs over the limit were read 20 MB at a time 37 times each in five days,
|
||||
/// about 3 GB for nothing (#448).
|
||||
const RETRY_LASTING: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
|
||||
/// Addresses that could not be fetched lately, and why. Without it a page shown again fetched
|
||||
/// them again: five covers too big to keep were downloaded from Patreon on every load (#169).
|
||||
@@ -103,7 +99,7 @@ const RETRY_LASTING: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
// one per artwork address a feed or item names; move it to disk or prune it on trim if that grows.
|
||||
static FAILED: LazyLock<Mutex<HashMap<String, (Instant, String)>>> = LazyLock::new(Default::default);
|
||||
|
||||
/// Why `url` could not be fetched, if it failed lately: an hour, or a day for a lasting failure.
|
||||
/// Why `url` could not be fetched, if it failed less than an hour ago.
|
||||
pub fn failed(url: &str) -> Option<String> {
|
||||
failed_as_of(url, Instant::now())
|
||||
}
|
||||
@@ -111,7 +107,7 @@ pub fn failed(url: &str) -> Option<String> {
|
||||
fn failed_as_of(url: &str, now: Instant) -> Option<String> {
|
||||
let mut map = FAILED.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match map.get(url) {
|
||||
Some((until, why)) if now < *until => Some(why.clone()),
|
||||
Some((at, why)) if now.duration_since(*at) < RETRY => Some(why.clone()),
|
||||
Some(_) => {
|
||||
map.remove(url);
|
||||
None
|
||||
@@ -120,9 +116,8 @@ fn failed_as_of(url: &str, now: Instant) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fail(url: &str, why: &str, lasting: bool) {
|
||||
let until = Instant::now() + if lasting { RETRY_LASTING } else { RETRY };
|
||||
FAILED.lock().unwrap_or_else(|e| e.into_inner()).insert(url.to_owned(), (until, why.to_owned()));
|
||||
pub fn fail(url: &str, why: &str) {
|
||||
FAILED.lock().unwrap_or_else(|e| e.into_inner()).insert(url.to_owned(), (Instant::now(), why.to_owned()));
|
||||
}
|
||||
|
||||
/// Removes the least recently used images until what is kept fits in `limit` bytes; 0 empties it.
|
||||
@@ -189,16 +184,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failure_is_remembered_for_an_hour_and_a_lasting_one_for_a_day() {
|
||||
fn a_failure_is_remembered_for_an_hour() {
|
||||
let u = "https://example.com/a-failure-is-remembered.png";
|
||||
assert_eq!(failed(u), None);
|
||||
fail(u, "timed out", false);
|
||||
assert_eq!(failed(u).as_deref(), Some("timed out"));
|
||||
fail(u, "larger than 5 MB");
|
||||
assert_eq!(failed(u).as_deref(), Some("larger than 5 MB"));
|
||||
assert_eq!(failed_as_of(u, Instant::now() + RETRY), None);
|
||||
// Asked for after the hour, it is forgotten, not just ignored.
|
||||
assert_eq!(failed(u), None);
|
||||
fail(u, "larger than 20 MB", true);
|
||||
assert_eq!(failed_as_of(u, Instant::now() + RETRY).as_deref(), Some("larger than 20 MB"));
|
||||
assert_eq!(failed_as_of(u, Instant::now() + RETRY_LASTING), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,10 +136,6 @@ pub(crate) async fn rm(ctx: &Ctx, feed: &str) -> Result<()> {
|
||||
return Ok(());
|
||||
};
|
||||
ctx.store_cfg(cfg).await?;
|
||||
// Left subscribed, All Subscriptions listed its items with no feed to name them (#478).
|
||||
for (user, _) in ctx.db.subscribers_of(feed).await? {
|
||||
ctx.db.unsubscribe(user, feed).await?;
|
||||
}
|
||||
// State and files stay: re-adding the feed should not re-download its back catalogue.
|
||||
println!("removed {feed}; downloads and history kept");
|
||||
retire_group(ctx, feed, Some(&parent)).await?;
|
||||
@@ -481,27 +477,6 @@ pub(crate) async fn retire_stranded(ctx: &Ctx) -> Result<usize> {
|
||||
Ok(before.len() - ctx.db.managed_feeds().await?.len())
|
||||
}
|
||||
|
||||
/// Unsubscribes everyone from feeds the catalogue no longer has, and returns how many feeds that
|
||||
/// was. Removing a feed once left its subscriptions behind, 41 of them by 2026-11-19, and All
|
||||
/// Subscriptions listed their items with no feed to name them (#478).
|
||||
pub(crate) async fn drop_stray_subscriptions(ctx: &Ctx) -> Result<usize> {
|
||||
let known: std::collections::HashSet<String> = subscriptions(ctx).await?.into_iter().map(|s| s.id).collect();
|
||||
// A catalogue that came back empty is more likely a fault than a server with no feeds, and
|
||||
// taking it at its word would unsubscribe everyone from everything.
|
||||
if known.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut dropped = 0;
|
||||
for feed in ctx.db.subscriber_counts().await?.into_keys().filter(|f| !known.contains(f)) {
|
||||
for (user, _) in ctx.db.subscribers_of(&feed).await? {
|
||||
ctx.db.unsubscribe(user, &feed).await?;
|
||||
}
|
||||
tracing::info!(feed = %feed, "unsubscribed everyone from a feed no longer in the catalogue");
|
||||
dropped += 1;
|
||||
}
|
||||
Ok(dropped)
|
||||
}
|
||||
|
||||
/// Puts each feed no longer derived in the group its catalogue entry says, and returns how many
|
||||
/// moved. Made a feed of its own before #358, a show kept its list's group in the database, and
|
||||
/// hiding the list from All Subscriptions hid it too.
|
||||
@@ -737,21 +712,6 @@ mod tests {
|
||||
assert_eq!(regroup_unmanaged(&ctx).await.unwrap(), 0, "nothing left to move");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_subscription_to_a_feed_not_in_the_catalogue_is_dropped() {
|
||||
let mut cfg = config::Config::default();
|
||||
cfg.feeds.insert("opml".into(), feed());
|
||||
let ctx = test_ctx(cfg).await;
|
||||
let me = ctx.db.create_user("me", None, false).await.unwrap();
|
||||
ctx.db.upsert_managed("listed", "http://x/l.xml", "Listed", "opml").await.unwrap();
|
||||
for id in ["opml", "listed", "gone"] {
|
||||
ctx.db.subscribe(me, id).await.unwrap();
|
||||
}
|
||||
assert_eq!(drop_stray_subscriptions(&ctx).await.unwrap(), 1);
|
||||
let mine: Vec<String> = ctx.db.subscriptions_for(me).await.unwrap().into_iter().map(|s| s.feed_id).collect();
|
||||
assert!(mine.contains(&"opml".into()) && mine.contains(&"listed".into()) && !mine.contains(&"gone".into()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stranded_group_is_retired_but_a_promoted_feed_keeps_its_entries() {
|
||||
// davewiner: the OPML left config before retire_group existed, and 11 of its feeds
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
//! An episode's chapters (#477): from the JSON file its item names (`<podcast:chapters>`, the
|
||||
//! Podcasting 2.0 namespace's), or else from the file itself once downloaded (ID3 `CHAP` frames,
|
||||
//! MP4 chapters), which ffprobe reads as it does for DeadAir.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::Serialize;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
pub struct Chapter {
|
||||
/// Seconds from the start of the original.
|
||||
pub start: f64,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
/// More than any list of chapters needs: a chapters file is a few KB.
|
||||
const MAX: usize = 1 << 20;
|
||||
|
||||
/// The namespace's chapters file: `{"chapters": [{"startTime": 0, "title": "..", "toc": false}]}`.
|
||||
/// One with `toc` false is there to change the artwork, not to be listed.
|
||||
pub fn from_json(body: &[u8]) -> Result<Vec<Chapter>> {
|
||||
let v: serde_json::Value = serde_json::from_slice(body).context("reading the chapters file")?;
|
||||
let list = v["chapters"].as_array().context("no chapters in the chapters file")?;
|
||||
Ok(sorted(
|
||||
list.iter()
|
||||
.filter(|c| c["toc"] != false)
|
||||
.filter_map(|c| Some(Chapter { start: c["startTime"].as_f64()?, title: text(&c["title"]) }))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// ffprobe's `-show_chapters -of json`: `{"chapters": [{"start_time": "0.000000", "tags": {"title": ".."}}]}`.
|
||||
pub fn from_ffprobe(out: &str) -> Result<Vec<Chapter>> {
|
||||
let v: serde_json::Value = serde_json::from_str(out).context("reading ffprobe")?;
|
||||
Ok(sorted(
|
||||
v["chapters"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|c| {
|
||||
Some(Chapter { start: c["start_time"].as_str()?.parse().ok()?, title: text(&c["tags"]["title"]) })
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
fn text(v: &serde_json::Value) -> String {
|
||||
v.as_str().unwrap_or("").trim().to_owned()
|
||||
}
|
||||
|
||||
/// In order, and none before the start: the namespace does not promise either.
|
||||
fn sorted(mut list: Vec<Chapter>) -> Vec<Chapter> {
|
||||
list.retain(|c| c.start.is_finite() && c.start >= 0.0);
|
||||
list.sort_by(|a, b| a.start.total_cmp(&b.start));
|
||||
list
|
||||
}
|
||||
|
||||
// ponytail: fetched each time someone opens Now Playing on an episode, which the page then keeps;
|
||||
// keep them in the database if a chapters host turns out slow or many people play one episode.
|
||||
pub async fn fetch(client: &reqwest::Client, url: &str) -> Result<Vec<Chapter>> {
|
||||
let mut r = client.get(url).timeout(crate::feed::FEED_TIMEOUT).send().await?.error_for_status()?;
|
||||
anyhow::ensure!(r.content_length().is_none_or(|n| n <= MAX as u64), "larger than {MAX} bytes");
|
||||
let mut body = Vec::new();
|
||||
while let Some(c) = r.chunk().await? {
|
||||
body.extend_from_slice(&c);
|
||||
anyhow::ensure!(body.len() <= MAX, "larger than {MAX} bytes");
|
||||
}
|
||||
from_json(&body)
|
||||
}
|
||||
|
||||
pub async fn in_file(path: &Path) -> Result<Vec<Chapter>> {
|
||||
let path = path.display().to_string();
|
||||
from_ffprobe(&crate::deadair::run_out("ffprobe", &["-v", "error", "-show_chapters", "-of", "json", &path]).await?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_namespaces_file_is_read_in_order_without_its_artwork_only_chapters() {
|
||||
let body = br#"{"version":"1.2.0","chapters":[
|
||||
{"startTime":95.5,"title":" Second "},
|
||||
{"startTime":0,"title":"Intro"},
|
||||
{"startTime":40,"img":"https://x/a.jpg","toc":false},
|
||||
{"title":"no start"},
|
||||
{"startTime":200}]}"#;
|
||||
let got = from_json(body).unwrap();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
Chapter { start: 0.0, title: "Intro".into() },
|
||||
Chapter { start: 95.5, title: "Second".into() },
|
||||
Chapter { start: 200.0, title: "".into() },
|
||||
]
|
||||
);
|
||||
assert!(from_json(b"<html>").is_err(), "a web page is not a chapters file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffprobes_chapters_are_read_and_a_file_with_none_has_none() {
|
||||
let out = r#"{"chapters":[
|
||||
{"id":1,"start_time":"61.250000","end_time":"120.000000","tags":{"title":"Two"}},
|
||||
{"id":0,"start_time":"0.000000","end_time":"61.250000","tags":{"title":"One"}}]}"#;
|
||||
assert_eq!(
|
||||
from_ffprobe(out).unwrap(),
|
||||
[Chapter { start: 0.0, title: "One".into() }, Chapter { start: 61.25, title: "Two".into() }]
|
||||
);
|
||||
assert_eq!(from_ffprobe(r#"{"chapters":[]}"#).unwrap(), []);
|
||||
assert_eq!(from_ffprobe("{}").unwrap(), []);
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,6 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub torrent: Torrent,
|
||||
#[serde(default)]
|
||||
pub nzb: Nzb,
|
||||
#[serde(default)]
|
||||
pub web: Web,
|
||||
#[serde(default)]
|
||||
pub push: Push,
|
||||
@@ -114,58 +112,14 @@ impl Push {
|
||||
#[serde(default)]
|
||||
pub struct Torrent {
|
||||
pub enabled: bool,
|
||||
/// qBittorrent's Web UI, which does the downloading and seeding (#494), e.g.
|
||||
/// "http://qbittorrent:8080". Empty: torrents are held back, as when not enabled.
|
||||
pub qbittorrent_url: String,
|
||||
/// Empty when qBittorrent lets ipx's address in without signing in.
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
/// Where qBittorrent sees `download_dir`, when its mount is not at the same path as ipx's.
|
||||
pub save_path: String,
|
||||
/// qBittorrent stops seeding at this ratio, or after seed_time_mins, whichever comes first.
|
||||
/// Stop seeding at this ratio, or after seed_time_mins, whichever comes first.
|
||||
pub seed_ratio: f64,
|
||||
pub seed_time_mins: u64,
|
||||
pub port_range: String,
|
||||
/// Drop a torrent that has made no progress for this long.
|
||||
pub stall_mins: u64,
|
||||
}
|
||||
|
||||
/// NZB enclosures, sent to SABnzbd (#496) as torrents are to qBittorrent.
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(default)]
|
||||
pub struct Nzb {
|
||||
pub enabled: bool,
|
||||
/// SABnzbd's web address, e.g. "http://sabnzbd:8080". Empty: NZBs are held back.
|
||||
pub sabnzbd_url: String,
|
||||
pub api_key: String,
|
||||
/// The category jobs are added under. Its folder in SABnzbd has to be inside `download_dir`,
|
||||
/// where ipx can move the finished job from.
|
||||
pub category: String,
|
||||
/// Where SABnzbd sees `download_dir`, when its mount is not at the same path as ipx's.
|
||||
pub save_path: String,
|
||||
/// Drop an NZB that has made no progress for this long.
|
||||
pub stall_mins: u64,
|
||||
}
|
||||
|
||||
impl Default for Nzb {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
sabnzbd_url: String::new(),
|
||||
api_key: String::new(),
|
||||
category: "ipx".into(),
|
||||
save_path: String::new(),
|
||||
stall_mins: 30,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Nzb {
|
||||
/// NZBs are fetched only with somewhere to send them.
|
||||
pub fn on(&self) -> bool {
|
||||
self.enabled && !self.sabnzbd_url.trim().is_empty() && !self.api_key.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(default)]
|
||||
pub struct Web {
|
||||
@@ -311,16 +265,7 @@ impl Default for General {
|
||||
|
||||
impl Default for Torrent {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
qbittorrent_url: String::new(),
|
||||
username: String::new(),
|
||||
password: String::new(),
|
||||
save_path: String::new(),
|
||||
seed_ratio: 1.0,
|
||||
seed_time_mins: 60,
|
||||
stall_mins: 30,
|
||||
}
|
||||
Self { enabled: true, seed_ratio: 1.0, seed_time_mins: 60, port_range: "6881-6889".into(), stall_mins: 30 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,9 +313,16 @@ pub fn parse_interval(s: &str) -> Option<u64> {
|
||||
}
|
||||
|
||||
impl Torrent {
|
||||
/// Torrents are fetched only with somewhere to send them.
|
||||
pub fn on(&self) -> bool {
|
||||
self.enabled && !self.qbittorrent_url.trim().is_empty()
|
||||
/// Inclusive listen port range. Falls back to the BitTorrent default on garbage input.
|
||||
pub fn ports(&self) -> (u16, u16) {
|
||||
let parse = || -> Option<(u16, u16)> {
|
||||
let (lo, hi) = self.port_range.split_once('-')?;
|
||||
Some((lo.trim().parse().ok()?, hi.trim().parse().ok()?))
|
||||
};
|
||||
match parse() {
|
||||
Some((lo, hi)) if lo <= hi => (lo, hi),
|
||||
_ => (6881, 6889),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,8 +545,8 @@ pub fn wanted_media(mime: Option<&str>, wanted: &[String]) -> bool {
|
||||
return true;
|
||||
};
|
||||
let top = mime.split('/').next().unwrap_or(mime).to_ascii_lowercase();
|
||||
// A .torrent or an .nzb is a container for media, not media itself; judge it once unpacked.
|
||||
if ["torrent", "nzb"].iter().any(|c| mime.to_ascii_lowercase().contains(c)) {
|
||||
// A .torrent is a container for media, not media itself; judge it once unpacked.
|
||||
if mime.to_ascii_lowercase().contains("torrent") {
|
||||
return true;
|
||||
}
|
||||
wanted.iter().any(|w| w.trim().eq_ignore_ascii_case(&top) || w.trim().eq_ignore_ascii_case(mime))
|
||||
@@ -762,13 +714,15 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn torrents_are_on_only_with_a_qbittorrent_to_send_them_to() {
|
||||
fn port_range_falls_back_when_malformed() {
|
||||
let mut t = Torrent::default();
|
||||
assert!(!t.on(), "enabled, but nowhere to send them");
|
||||
t.qbittorrent_url = "http://qbittorrent:8080".into();
|
||||
assert!(t.on());
|
||||
t.enabled = false;
|
||||
assert!(!t.on());
|
||||
assert_eq!(t.ports(), (6881, 6889));
|
||||
t.port_range = "51413-51420".into();
|
||||
assert_eq!(t.ports(), (51413, 51420));
|
||||
t.port_range = "nonsense".into();
|
||||
assert_eq!(t.ports(), (6881, 6889));
|
||||
t.port_range = "900-100".into();
|
||||
assert_eq!(t.ports(), (6881, 6889), "reversed range is not a range");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -782,7 +736,6 @@ mod tests {
|
||||
|
||||
// A torrent is a container; what is inside is judged after unpacking.
|
||||
assert!(wanted_media(Some("application/x-bittorrent"), &want));
|
||||
assert!(wanted_media(Some("application/x-nzb"), &want));
|
||||
// Unknown type: only discoverable by downloading, so do not refuse it outright.
|
||||
assert!(wanted_media(None, &want));
|
||||
assert!(wanted_media(Some(""), &want));
|
||||
|
||||
@@ -29,14 +29,15 @@ pub struct Ctx {
|
||||
/// that moved for good from one sent elsewhere for now.
|
||||
pub feed_client: reqwest::Client,
|
||||
pub out: Emitter,
|
||||
/// qBittorrent's client and session cookie, made on first use (#494).
|
||||
/// Started on first use: a BitTorrent session binds ports and starts a DHT, which is
|
||||
/// rude to do for a config that has never seen a torrent.
|
||||
pub torrents: OnceCell<torrent::Torrents>,
|
||||
/// Caps how many torrents run at once when they are detached.
|
||||
pub torrent_slots: Arc<Semaphore>,
|
||||
/// Needed because a subscribed OPML rewrites the feed list as it syncs.
|
||||
pub config_path: PathBuf,
|
||||
/// Run torrents off the command worker. A torrent takes minutes to fetch metadata and
|
||||
/// more to download, and the worker is sequential -- inline, one torrent
|
||||
/// then seeds for up to an hour, and the worker is sequential -- inline, one torrent
|
||||
/// stops every feed scan, every HTTP download and every status command behind it.
|
||||
/// A one-shot CLI run keeps them inline, or the process would exit mid-download.
|
||||
pub detach_torrents: bool,
|
||||
@@ -207,21 +208,9 @@ impl Ctx {
|
||||
self.directory_wake.notify_one();
|
||||
}
|
||||
|
||||
/// After an enclosure's files are deleted: its torrent, if it was one, out of qBittorrent too
|
||||
/// (#495). Best effort; the files are gone whatever qBittorrent says.
|
||||
pub(crate) async fn forget_torrent(&self, enclosure: i64, path: &str) {
|
||||
let cfg = self.cfg();
|
||||
if !cfg.torrent.on() || !torrent::is_own_folder(std::path::Path::new(path), enclosure) {
|
||||
return;
|
||||
}
|
||||
match self.torrents().await {
|
||||
Ok(t) => t.forget(&cfg, enclosure).await,
|
||||
Err(e) => tracing::warn!(error = %format!("{e:#}"), "no qBittorrent client"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn torrents(&self) -> Result<&torrent::Torrents> {
|
||||
self.torrents.get_or_try_init(|| async { torrent::Torrents::new() }).await
|
||||
let cfg = self.cfg();
|
||||
self.torrents.get_or_try_init(|| torrent::Torrents::new(&cfg)).await
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,12 +97,6 @@ pub(crate) async fn daemon(
|
||||
Ok(n) => tracing::info!(feeds = n, "retired feeds whose OPML is no longer in config"),
|
||||
Err(e) => tracing::warn!(error = %format!("{e:#}"), "could not retire feeds whose OPML is no longer in config"),
|
||||
}
|
||||
// After retire_stranded, which drops feeds whose subscriptions this then finds.
|
||||
match catalogue::drop_stray_subscriptions(&ctx).instrument(db::step("drop_stray_subscriptions")).await {
|
||||
Ok(0) => {}
|
||||
Ok(n) => tracing::info!(feeds = n, "unsubscribed everyone from feeds no longer in the catalogue"),
|
||||
Err(e) => tracing::warn!(error = %format!("{e:#}"), "could not drop subscriptions to feeds no longer in the catalogue"),
|
||||
}
|
||||
match catalogue::regroup_unmanaged(&ctx).instrument(db::step("regroup_unmanaged")).await {
|
||||
Ok(0) => {}
|
||||
Ok(n) => tracing::info!(feeds = n, "took feeds of their own out of their old list's group"),
|
||||
@@ -168,7 +162,6 @@ pub(crate) async fn daemon(
|
||||
tokio::spawn(signals::run(ctx.clone(), rx_stop.clone()));
|
||||
tokio::spawn(directory::run(ctx.clone(), rx_stop.clone()));
|
||||
tokio::spawn(crate::push::run(ctx.clone(), rx_stop.clone()));
|
||||
tokio::spawn(crate::search::run(ctx.clone(), rx_stop.clone()));
|
||||
// The library's counts for /metrics. The Docker healthcheck asked for them every 30 s until
|
||||
// it was removed: Docker runs it with exec, which failed on Tower whenever root was logged
|
||||
// out (#218).
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -590,7 +590,7 @@ async fn ffmpeg(args: &[&str]) -> Result<String> {
|
||||
Ok(log)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_out(prog: &str, args: &[&str]) -> Result<String> {
|
||||
async fn run_out(prog: &str, args: &[&str]) -> Result<String> {
|
||||
let out = command(prog).args(args).output().await.with_context(|| format!("running {prog}"))?;
|
||||
if !out.status.success() {
|
||||
bail!("{prog} failed: {}", String::from_utf8_lossy(&out.stderr).trim());
|
||||
|
||||
@@ -5,8 +5,6 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use ipx_directory::{FeedPage, Listing, Me, SnapshotEntry, SnapshotResult};
|
||||
use ipx_wire::Message as _;
|
||||
use ipx_wire::pb::directory as pb;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::catalogue::Sub;
|
||||
@@ -67,13 +65,6 @@ pub fn configured(cfg: &config::Config) -> bool {
|
||||
target(cfg).is_some()
|
||||
}
|
||||
|
||||
/// How an answer in protobuf becomes what the caller wants (#470).
|
||||
type Decode<T> = fn(&[u8]) -> Result<T, String>;
|
||||
|
||||
fn listings(b: &[u8]) -> Result<Vec<Listing>, String> {
|
||||
Ok(pb::Listings::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Listing::from).collect())
|
||||
}
|
||||
|
||||
/// A span the whole call, its answer read and parsed included: the directory's own span ends when it
|
||||
/// has answered, so a slow read of a large answer showed under no span (#250).
|
||||
#[tracing::instrument(name = "directory_call", skip_all, fields(http.request.method = %method, url.path = %path.split('?').next().unwrap_or(path), http.response.body.size))]
|
||||
@@ -82,7 +73,6 @@ async fn call<T: DeserializeOwned>(
|
||||
method: reqwest::Method,
|
||||
path: &str,
|
||||
body: Option<&[SnapshotEntry]>,
|
||||
answer: Option<Decode<T>>,
|
||||
) -> Result<T, DirError> {
|
||||
let (base, token) = target(&ctx.cfg()).ok_or(DirError::NotConfigured)?;
|
||||
let mut req =
|
||||
@@ -91,19 +81,15 @@ async fn call<T: DeserializeOwned>(
|
||||
if let Some(tp) = ipx_directory::otel::traceparent() {
|
||||
req = req.header("traceparent", tp);
|
||||
}
|
||||
// Protobuf both ways (#465), where the answer has a message: a smaller body to read.
|
||||
if answer.is_some() {
|
||||
req = req.header(reqwest::header::ACCEPT, ipx_wire::PROTOBUF);
|
||||
}
|
||||
// A snapshot is about 100 KB, sent gzipped; the directory unpacks it (#253).
|
||||
// A snapshot is about 100 KB of JSON, sent gzipped; the directory unpacks it (#253).
|
||||
if let Some(b) = body {
|
||||
use std::io::Write as _;
|
||||
let pb = pb::Snapshot { items: b.iter().map(pb::SnapshotEntry::from).collect() }.encode_to_vec();
|
||||
let json = serde_json::to_vec(b).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
gz.write_all(&pb).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
gz.write_all(&json).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
let packed = gz.finish().map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
req = req
|
||||
.header(reqwest::header::CONTENT_TYPE, ipx_wire::PROTOBUF)
|
||||
.header(reqwest::header::CONTENT_TYPE, "application/json")
|
||||
.header(reqwest::header::CONTENT_ENCODING, "gzip")
|
||||
.body(packed);
|
||||
}
|
||||
@@ -118,16 +104,9 @@ async fn call<T: DeserializeOwned>(
|
||||
.unwrap_or_default();
|
||||
return Err(DirError::Refused(status.as_u16(), msg));
|
||||
}
|
||||
let protobuf = resp
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.is_some_and(|v| v.as_bytes().starts_with(ipx_wire::PROTOBUF.as_bytes()));
|
||||
// A removal or an unblock answers 204, with nothing to read: that reads as null, which is ().
|
||||
let body = resp.bytes().await.map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
tracing::Span::current().record("http.response.body.size", body.len());
|
||||
if let Some(decode) = answer.filter(|_| protobuf) {
|
||||
return decode(&body).map_err(|e| DirError::Unreachable(format!("its answer did not read: {e}")));
|
||||
}
|
||||
serde_json::from_slice(if body.is_empty() { b"null" } else { &body })
|
||||
.map_err(|e| DirError::Unreachable(format!("its answer did not read: {e:#}")))
|
||||
}
|
||||
@@ -137,31 +116,23 @@ fn seg(s: &str) -> percent_encoding::PercentEncode<'_> {
|
||||
}
|
||||
|
||||
pub async fn me(ctx: &Ctx) -> Result<Me, DirError> {
|
||||
call(ctx, reqwest::Method::GET, "/v1/me", None, Some(|b| pb::Me::decode(b).map_err(|e| e.to_string())?.try_into()))
|
||||
.await
|
||||
call(ctx, reqwest::Method::GET, "/v1/me", None).await
|
||||
}
|
||||
|
||||
pub async fn feeds(ctx: &Ctx) -> Result<Vec<Listing>, DirError> {
|
||||
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/feeds", None, Some(listings)).await?;
|
||||
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/feeds", None).await?;
|
||||
note_art(got.iter());
|
||||
Ok(got)
|
||||
}
|
||||
|
||||
pub async fn popular(ctx: &Ctx) -> Result<Vec<Listing>, DirError> {
|
||||
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/popular?limit=10", None, Some(listings)).await?;
|
||||
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/popular?limit=10", None).await?;
|
||||
note_art(got.iter());
|
||||
Ok(got)
|
||||
}
|
||||
|
||||
pub async fn page(ctx: &Ctx, id: &str) -> Result<FeedPage, DirError> {
|
||||
let got: FeedPage = call(
|
||||
ctx,
|
||||
reqwest::Method::GET,
|
||||
&format!("/v1/feeds/{}", seg(id)),
|
||||
None,
|
||||
Some(|b| pb::FeedPage::decode(b).map(FeedPage::from).map_err(|e| e.to_string())),
|
||||
)
|
||||
.await?;
|
||||
let got: FeedPage = call(ctx, reqwest::Method::GET, &format!("/v1/feeds/{}", seg(id)), None).await?;
|
||||
note_art(std::iter::once(&got.listing));
|
||||
Ok(got)
|
||||
}
|
||||
@@ -186,45 +157,29 @@ pub fn listed_art(url: &str) -> bool {
|
||||
|
||||
/// Removes a feed and blocks it, so no snapshot brings it back.
|
||||
pub async fn remove(ctx: &Ctx, id: &str) -> Result<(), DirError> {
|
||||
call(ctx, reqwest::Method::DELETE, &format!("/v1/feeds/{}", seg(id)), None, None).await
|
||||
call(ctx, reqwest::Method::DELETE, &format!("/v1/feeds/{}", seg(id)), None).await
|
||||
}
|
||||
|
||||
pub async fn refresh(ctx: &Ctx, id: &str) -> Result<serde::de::IgnoredAny, DirError> {
|
||||
call(ctx, reqwest::Method::POST, &format!("/v1/feeds/{}/refresh", seg(id)), None, None).await
|
||||
call(ctx, reqwest::Method::POST, &format!("/v1/feeds/{}/refresh", seg(id)), None).await
|
||||
}
|
||||
|
||||
pub async fn blocked(ctx: &Ctx) -> Result<Vec<ipx_directory::Blocked>, DirError> {
|
||||
call(
|
||||
ctx,
|
||||
reqwest::Method::GET,
|
||||
"/v1/blocked",
|
||||
None,
|
||||
Some(|b| {
|
||||
Ok(pb::BlockedList::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Into::into).collect())
|
||||
}),
|
||||
)
|
||||
.await
|
||||
call(ctx, reqwest::Method::GET, "/v1/blocked", None).await
|
||||
}
|
||||
|
||||
pub async fn unblock(ctx: &Ctx, id: &str) -> Result<(), DirError> {
|
||||
call(ctx, reqwest::Method::DELETE, &format!("/v1/blocked/{}", seg(id)), None, None).await
|
||||
call(ctx, reqwest::Method::DELETE, &format!("/v1/blocked/{}", seg(id)), None).await
|
||||
}
|
||||
|
||||
pub async fn instances(ctx: &Ctx) -> Result<Vec<ipx_directory::Instance>, DirError> {
|
||||
call(
|
||||
ctx,
|
||||
reqwest::Method::GET,
|
||||
"/v1/instances",
|
||||
None,
|
||||
Some(|b| Ok(pb::Instances::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Into::into).collect())),
|
||||
)
|
||||
.await
|
||||
call(ctx, reqwest::Method::GET, "/v1/instances", None).await
|
||||
}
|
||||
|
||||
/// Drops one server's snapshot, and its counts with it. It comes back with that server's next
|
||||
/// one: to keep a server out, revoke its token.
|
||||
pub async fn drop_instance(ctx: &Ctx, name: &str) -> Result<(), DirError> {
|
||||
call(ctx, reqwest::Method::DELETE, &format!("/v1/instances/{}", seg(name)), None, None).await
|
||||
call(ctx, reqwest::Method::DELETE, &format!("/v1/instances/{}", seg(name)), None).await
|
||||
}
|
||||
|
||||
/// Has the snapshot sent again now, changed or not.
|
||||
@@ -279,14 +234,7 @@ async fn snapshot(ctx: &Ctx) -> Result<Vec<SnapshotEntry>, DirError> {
|
||||
}
|
||||
|
||||
pub async fn share(ctx: &Ctx, entries: &[SnapshotEntry]) -> Result<SnapshotResult, DirError> {
|
||||
let r: SnapshotResult = call(
|
||||
ctx,
|
||||
reqwest::Method::POST,
|
||||
"/v1/snapshot",
|
||||
Some(entries),
|
||||
Some(|b| pb::SnapshotResult::decode(b).map(Into::into).map_err(|e| e.to_string())),
|
||||
)
|
||||
.await?;
|
||||
let r: SnapshotResult = call(ctx, reqwest::Method::POST, "/v1/snapshot", Some(entries)).await?;
|
||||
if r.refused_private > 0 {
|
||||
// The directory caught what this side should have: worth knowing which check differs.
|
||||
tracing::warn!(refused = r.refused_private, "the directory refused feeds as private that ipx sent");
|
||||
|
||||
@@ -114,32 +114,8 @@ fn disposition_filename(header: &str) -> Option<String> {
|
||||
/// What the download turned out to be, once the bytes were on disk.
|
||||
pub enum Kind {
|
||||
File,
|
||||
/// A .torrent or an .nzb body, whatever the advertised MIME said: handed on, not filed.
|
||||
Via(Via),
|
||||
}
|
||||
|
||||
/// Where an enclosure goes instead of being downloaded here: a torrent to qBittorrent (#494), an
|
||||
/// NZB to SABnzbd (#496).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Via {
|
||||
/// A .torrent body, whatever the advertised MIME said. Step 7 takes it from here.
|
||||
Torrent,
|
||||
Nzb,
|
||||
}
|
||||
|
||||
impl Via {
|
||||
pub fn on(self, cfg: &Config) -> bool {
|
||||
match self {
|
||||
Via::Torrent => cfg.torrent.on(),
|
||||
Via::Nzb => cfg.nzb.on(),
|
||||
}
|
||||
}
|
||||
/// The `last_error` of one held back while its kind is off, which no filter can overturn.
|
||||
pub fn off(self) -> &'static str {
|
||||
match self {
|
||||
Via::Torrent => "torrents disabled",
|
||||
Via::Nzb => "NZBs disabled",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Downloaded {
|
||||
@@ -198,8 +174,7 @@ pub async fn download(
|
||||
let _ = tokio::fs::remove_file(&tmp).await;
|
||||
bail!("server returned an HTML page, not a media file");
|
||||
}
|
||||
Sniffed::Torrent => Kind::Via(Via::Torrent),
|
||||
Sniffed::Nzb => Kind::Via(Via::Nzb),
|
||||
Sniffed::Torrent => Kind::Torrent,
|
||||
Sniffed::Other => Kind::File,
|
||||
};
|
||||
|
||||
@@ -245,23 +220,15 @@ pub fn playable(path: &Path) -> PathBuf {
|
||||
best.map_or_else(|| path.to_owned(), |(_, p)| p)
|
||||
}
|
||||
|
||||
/// Advertised as a torrent or an NZB, before spending any bandwidth on it.
|
||||
pub fn handed_on(url: &str, mime: Option<&str>) -> Option<Via> {
|
||||
let mime = mime.unwrap_or("").to_ascii_lowercase();
|
||||
let path = url.split('?').next().unwrap_or(url).to_ascii_lowercase();
|
||||
if mime.contains("torrent") || path.ends_with(".torrent") {
|
||||
Some(Via::Torrent)
|
||||
} else if mime.contains("nzb") || path.ends_with(".nzb") {
|
||||
Some(Via::Nzb)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
/// Advertised as a torrent, before spending any bandwidth on it.
|
||||
pub fn looks_like_torrent(url: &str, mime: Option<&str>) -> bool {
|
||||
mime.is_some_and(|m| m.to_ascii_lowercase().contains("torrent"))
|
||||
|| url.split('?').next().unwrap_or(url).to_ascii_lowercase().ends_with(".torrent")
|
||||
}
|
||||
|
||||
enum Sniffed {
|
||||
Html,
|
||||
Torrent,
|
||||
Nzb,
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -277,12 +244,6 @@ async fn sniff(path: &Path) -> Result<Sniffed> {
|
||||
if lead.starts_with("<!doctype html") || lead.starts_with("<html") {
|
||||
return Ok(Sniffed::Html);
|
||||
}
|
||||
if lead.starts_with("<!doctype nzb")
|
||||
|| lead.starts_with("<nzb")
|
||||
|| lead.starts_with("<?xml") && lead.contains("<nzb")
|
||||
{
|
||||
return Ok(Sniffed::Nzb);
|
||||
}
|
||||
Ok(Sniffed::Other)
|
||||
}
|
||||
|
||||
@@ -462,15 +423,6 @@ mod tests {
|
||||
assert_eq!(folder_for(&cfg, "id", &f, None), "etc/Show");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn torrents_and_nzbs_are_told_by_type_or_by_name() {
|
||||
assert_eq!(handed_on("http://x/a.mp3", Some("application/x-bittorrent")), Some(Via::Torrent));
|
||||
assert_eq!(handed_on("http://x/a.TORRENT?k=1", None), Some(Via::Torrent));
|
||||
assert_eq!(handed_on("http://x/a", Some("application/x-nzb")), Some(Via::Nzb));
|
||||
assert_eq!(handed_on("http://x/get.nzb?id=3", Some("")), Some(Via::Nzb));
|
||||
assert_eq!(handed_on("http://x/a.mp3?f=.nzb", Some("audio/mpeg")), None, "the query is not the name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torrent_folder_plays_its_largest_file_and_deletes_whole() {
|
||||
let d = std::env::temp_dir().join(format!("ipx-torrent-test-{}", std::process::id()));
|
||||
@@ -512,7 +464,6 @@ mod tests {
|
||||
.route("/ep.mp3", get(|| async { "ID3 an episode" }))
|
||||
.route("/wall.mp3", get(|| async { "\n <!DOCTYPE html><html>Sign in</html>" }))
|
||||
.route("/show.torrent", get(|| async { "d8:announce35:udp://tracker.example:80/announcee" }))
|
||||
.route("/show.nzb", get(|| async { "<?xml version=\"1.0\"?>\n<!DOCTYPE nzb><nzb xmlns=\"x\"/>" }))
|
||||
.route("/gone.mp3", get(|| async { axum::http::StatusCode::NOT_FOUND }));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let at = listener.local_addr().unwrap();
|
||||
@@ -549,8 +500,7 @@ mod tests {
|
||||
assert!(format!("{wall:#}").contains("HTML page"), "{wall:#}");
|
||||
assert!(!d.join(".ipx-incomplete/wall.mp3").exists(), "a login page is not kept");
|
||||
|
||||
assert!(matches!(get("/show.torrent").await.unwrap().kind, Kind::Via(Via::Torrent)));
|
||||
assert!(matches!(get("/show.nzb").await.unwrap().kind, Kind::Via(Via::Nzb)), "an NZB is not an episode (#496)");
|
||||
assert!(matches!(get("/show.torrent").await.unwrap().kind, Kind::Torrent));
|
||||
assert!(format!("{:#}", get("/gone.mp3").await.err().unwrap()).contains("404"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
@@ -86,13 +86,6 @@ pub mod entries {
|
||||
pub duration: Option<i64>,
|
||||
pub episode: Option<i64>,
|
||||
pub season: Option<i64>,
|
||||
/// Where its chapters are, from `<podcast:chapters>` (#477).
|
||||
#[sea_orm(column_type = "Text", nullable)]
|
||||
pub chapters: Option<String>,
|
||||
/// The title and the text without markup, lowercased and cut short, which search reads
|
||||
/// (#459); none until search.rs makes it.
|
||||
#[sea_orm(column_type = "Text", nullable)]
|
||||
pub search_text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
@@ -273,53 +266,6 @@ pub mod entry_state {
|
||||
owned_by_user!();
|
||||
}
|
||||
|
||||
/// Up Next (#473): the episodes someone has lined up to play, in order. Per person, and on the
|
||||
/// server so the phone and the browser play through the same one.
|
||||
pub mod queue {
|
||||
use sea_orm::entity::prelude::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
|
||||
#[sea_orm(table_name = "queue")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub user_id: i64,
|
||||
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
|
||||
pub feed_id: String,
|
||||
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
|
||||
pub guid: String,
|
||||
pub pos: i64,
|
||||
}
|
||||
|
||||
owned_by_user!();
|
||||
}
|
||||
|
||||
/// Smart playlists (#476): episodes of the podcasts chosen, kept up to date by themselves. The
|
||||
/// priority podcasts' episodes come first.
|
||||
pub mod playlists {
|
||||
use sea_orm::entity::prelude::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
|
||||
#[sea_orm(table_name = "playlists")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i64,
|
||||
pub user_id: i64,
|
||||
#[sea_orm(column_type = "Text")]
|
||||
pub name: String,
|
||||
/// JSON array of feed ids.
|
||||
#[sea_orm(column_type = "Text")]
|
||||
pub feeds: String,
|
||||
/// JSON array of feed ids, of those in `feeds`.
|
||||
#[sea_orm(column_type = "Text")]
|
||||
pub priority: String,
|
||||
pub only_unplayed: bool,
|
||||
pub oldest_first: bool,
|
||||
pub created: i64,
|
||||
}
|
||||
|
||||
owned_by_user!();
|
||||
}
|
||||
|
||||
/// Words someone never wants to see: an item whose title or text has one is hidden from them and
|
||||
/// not downloaded on their account (issue #47). `feed_id` is empty for the list that applies to
|
||||
/// every feed they read.
|
||||
|
||||
@@ -83,9 +83,6 @@ pub enum Event {
|
||||
Reaped {
|
||||
path: String,
|
||||
bytes: u64,
|
||||
/// Only what would go: `reap --dry-run` said "deleted" of files it kept (#461).
|
||||
#[serde(default)]
|
||||
dry_run: bool,
|
||||
},
|
||||
/// Terminal: a client that asked for work stops reading here.
|
||||
ScanDone {
|
||||
@@ -100,8 +97,6 @@ pub enum Event {
|
||||
ReapDone {
|
||||
files: usize,
|
||||
bytes: u64,
|
||||
#[serde(default)]
|
||||
dry_run: bool,
|
||||
},
|
||||
Status {
|
||||
feeds: usize,
|
||||
@@ -170,11 +165,11 @@ impl Event {
|
||||
},
|
||||
Event::DownloadDone { path, .. } => format!(" saved {path}"),
|
||||
Event::DownloadError { url, msg, .. } => format!(" failed {url}: {msg}"),
|
||||
Event::Reaped { path, bytes, dry_run } => {
|
||||
format!("{} {path} ({:.1} MB)", deleted(*dry_run), *bytes as f64 / 1_048_576.0)
|
||||
Event::Reaped { path, bytes } => {
|
||||
format!("deleted {path} ({:.1} MB)", *bytes as f64 / 1_048_576.0)
|
||||
}
|
||||
Event::ReapDone { files, bytes, dry_run } => {
|
||||
format!("{} {files} old file(s), {:.1} MB", deleted(*dry_run), *bytes as f64 / 1_048_576.0)
|
||||
Event::ReapDone { files, bytes } => {
|
||||
format!("deleted {files} old file(s), {:.1} MB", *bytes as f64 / 1_048_576.0)
|
||||
}
|
||||
Event::Status { feeds, pending, downloaded } => {
|
||||
format!("{feeds} feeds, {pending} queued to download, {downloaded} downloaded")
|
||||
@@ -293,10 +288,6 @@ impl Event {
|
||||
}
|
||||
}
|
||||
|
||||
const fn deleted(dry_run: bool) -> &'static str {
|
||||
if dry_run { "would delete" } else { "deleted" }
|
||||
}
|
||||
|
||||
/// An event, logged once (#91): its words as the message, and `ev`, `feed`, `new` and the rest as
|
||||
/// fields, so Loki reads them without parsing the message. A failure also gets `error.type` and,
|
||||
/// from an HTTP error, `http.response.status_code`, so failures group by kind without a regex.
|
||||
@@ -525,9 +516,7 @@ mod tests {
|
||||
assert!(Event::ScanDone { feeds: 3, only: None, forced: false }.is_for(&me, &mine));
|
||||
assert!(Event::SignalHits { user: 1, hits: 2 }.is_for(&me, &mine));
|
||||
assert!(!Event::SignalHits { user: 3, hits: 2 }.is_for(&me, &mine));
|
||||
assert!(
|
||||
!Event::Reaped { path: "/downloads/Theirs/ep.mp3".into(), bytes: 1, dry_run: false }.is_for(&me, &mine)
|
||||
);
|
||||
assert!(!Event::Reaped { path: "/downloads/Theirs/ep.mp3".into(), bytes: 1 }.is_for(&me, &mine));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -638,7 +627,7 @@ mod tests {
|
||||
#[test]
|
||||
fn only_completion_events_end_a_client_session() {
|
||||
assert!(Event::ScanDone { feeds: 1, only: None, forced: false }.is_terminal());
|
||||
assert!(Event::ReapDone { files: 0, bytes: 0, dry_run: false }.is_terminal());
|
||||
assert!(Event::ReapDone { files: 0, bytes: 0 }.is_terminal());
|
||||
assert!(!Event::FeedDone { feed: "a".into(), new: 0, downloaded: 0, failed: 0, torrents: 0 }.is_terminal());
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ mod access;
|
||||
mod art;
|
||||
mod auth;
|
||||
mod catalogue;
|
||||
mod chapters;
|
||||
mod cli;
|
||||
mod config;
|
||||
mod ctx;
|
||||
@@ -24,12 +23,10 @@ mod lists;
|
||||
mod logbuf;
|
||||
mod logging;
|
||||
mod metrics;
|
||||
mod nzb;
|
||||
mod play;
|
||||
mod push;
|
||||
mod retention;
|
||||
mod scan;
|
||||
mod search;
|
||||
mod signals;
|
||||
#[cfg(test)]
|
||||
mod test_util;
|
||||
|
||||
@@ -182,7 +182,7 @@ pub(crate) async fn sync_group(ctx: &Arc<Ctx>, parent_id: &str, listed: &[(Strin
|
||||
.await?;
|
||||
|
||||
// Anything in this group the OPML no longer lists.
|
||||
let mut removed = vec![];
|
||||
let mut removed = 0;
|
||||
let mut kept = 0;
|
||||
let parent = ctx.cfg().feeds.get(parent_id).cloned();
|
||||
async {
|
||||
@@ -203,7 +203,7 @@ pub(crate) async fn sync_group(ctx: &Arc<Ctx>, parent_id: &str, listed: &[(Strin
|
||||
tracing::info!(feed = %m.id, "dropped from the OPML but has downloads; keeping it");
|
||||
} else {
|
||||
ctx.db.drop_managed(&m.id).await?;
|
||||
removed.push(m.id.clone());
|
||||
removed += 1;
|
||||
tracing::info!(feed = %m.id, "dropped from the OPML with nothing downloaded; removed");
|
||||
}
|
||||
}
|
||||
@@ -291,21 +291,4 @@ mod tests {
|
||||
assert!(ctx.db.subscription(me, "b").await.unwrap().is_some());
|
||||
assert!(ctx.db.subscription(you, "b").await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_feed_the_list_drops_takes_its_subscriptions_with_it() {
|
||||
let mut cfg = config::Config::default();
|
||||
cfg.feeds.insert("opml".into(), feed());
|
||||
let ctx = Arc::new(test_ctx(cfg).await);
|
||||
let me = ctx.db.create_user("me", None, false).await.unwrap();
|
||||
ctx.db.upsert_managed("a", "http://x/a.xml", "a", "opml").await.unwrap();
|
||||
ctx.db.subscribe(me, "opml").await.unwrap();
|
||||
ctx.db.subscribe(me, "a").await.unwrap();
|
||||
|
||||
// Left subscribed, All Subscriptions listed a's items with no feed to name them (#478).
|
||||
let Outcome::Opml { removed, .. } = sync_group(&ctx, "opml", &[]).await.unwrap() else { panic!("a list") };
|
||||
assert_eq!(removed, ["a"], "the scan is told, so it does not read a again");
|
||||
assert!(ctx.db.subscription(me, "a").await.unwrap().is_none());
|
||||
assert!(ctx.db.subscription(me, "opml").await.unwrap().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,349 +0,0 @@
|
||||
//! NZB enclosures through SABnzbd's API (#496), the way torrents go through qBittorrent (#494).
|
||||
//! ipx fetches the .nzb itself, adds it under a category of its own with a job name it can find
|
||||
//! again, follows it through the queue and post-processing, and moves the finished folder into
|
||||
//! the enclosure's own. SABnzbd takes no save path for a job, only a category's folder, so that
|
||||
//! folder has to be one ipx can see, inside `download_dir`.
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use reqwest::multipart::{Form, Part};
|
||||
use serde::Deserialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::LazyLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
/// Not the guarded client feeds are fetched with: SABnzbd is on the LAN by design, at the address
|
||||
/// the admin gave, which the guard would refuse (#320).
|
||||
static HTTP: LazyLock<reqwest::Client> =
|
||||
LazyLock::new(|| reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("a client"));
|
||||
|
||||
/// One job in the queue, as much as ipx reads. SABnzbd gives sizes there as strings of MB.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct Queued {
|
||||
nzo_id: String,
|
||||
filename: String,
|
||||
mb: String,
|
||||
mbleft: String,
|
||||
}
|
||||
|
||||
/// One job in the history: downloaded, and being or done being post-processed.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct Done {
|
||||
nzo_id: String,
|
||||
name: String,
|
||||
status: String,
|
||||
storage: String,
|
||||
bytes: i64,
|
||||
fail_message: String,
|
||||
}
|
||||
|
||||
enum Job {
|
||||
Queued(Queued),
|
||||
Done(Done),
|
||||
}
|
||||
|
||||
const POLL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Downloads an NZB through SABnzbd into the enclosure's own folder inside `feed_dir`, which is the
|
||||
/// path returned, with its size.
|
||||
pub async fn fetch(
|
||||
cfg: &Config,
|
||||
client: &reqwest::Client,
|
||||
url: &str,
|
||||
feed_dir: &Path,
|
||||
enclosure: i64,
|
||||
mut on_progress: impl FnMut(u64, u64),
|
||||
) -> Result<(PathBuf, u64)> {
|
||||
let limit = Duration::from_secs(cfg.nzb.stall_mins.max(1) * 60);
|
||||
let name = job_name(enclosure);
|
||||
|
||||
// There already when ipx stopped while it ran (#410): taken up where SABnzbd has it.
|
||||
if find(cfg, &name).await?.is_none() {
|
||||
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
|
||||
let file = tokio::time::timeout(limit, nzb_file(client, url))
|
||||
.await
|
||||
.map_err(|_| anyhow!("no .nzb after {} minutes, gave up", limit.as_secs() / 60))??;
|
||||
let form = Form::new().part("name", Part::bytes(file).file_name(format!("{name}.nzb")));
|
||||
let said: Added =
|
||||
call(cfg, &[("mode", "addfile"), ("nzbname", &name), ("cat", &cfg.nzb.category)], Some(form)).await?;
|
||||
if said.nzo_ids.is_empty() {
|
||||
bail!("SABnzbd would not take the NZB");
|
||||
}
|
||||
}
|
||||
|
||||
let mut last = (-1i64, Instant::now());
|
||||
let done = loop {
|
||||
tokio::time::sleep(POLL).await;
|
||||
// A SABnzbd restarting is a pause, not a failure, until the stall limit says so.
|
||||
let job = match find(cfg, &name).await {
|
||||
Ok(j) => j,
|
||||
Err(e) if last.1.elapsed() < limit => {
|
||||
tracing::debug!(error = %format!("{e:#}"), "SABnzbd did not answer");
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let left = match job {
|
||||
None => bail!("the NZB is no longer in SABnzbd"),
|
||||
Some(Job::Done(d)) if d.status == "Completed" => break d,
|
||||
Some(Job::Done(d)) if d.status == "Failed" => {
|
||||
forget(cfg, "history", &d.nzo_id).await;
|
||||
bail!("SABnzbd says the download failed: {}", d.fail_message);
|
||||
}
|
||||
// Verifying, repairing, unpacking: all of it is here, and a large repair is slow.
|
||||
Some(Job::Done(_)) => {
|
||||
last.1 = Instant::now();
|
||||
continue;
|
||||
}
|
||||
Some(Job::Queued(q)) => {
|
||||
let mb = |s: &str| (s.trim().parse::<f64>().unwrap_or(0.0) * 1_048_576.0) as i64;
|
||||
let (total, left) = (mb(&q.mb), mb(&q.mbleft));
|
||||
on_progress((total - left).max(0) as u64, total.max(0) as u64);
|
||||
(left, q)
|
||||
}
|
||||
};
|
||||
let (left, q) = left;
|
||||
if last.0 < 0 || left < last.0 {
|
||||
last = (left, Instant::now());
|
||||
} else if last.1.elapsed() > limit {
|
||||
forget(cfg, "queue", &q.nzo_id).await;
|
||||
bail!("no progress for {} minutes, gave up", limit.as_secs() / 60);
|
||||
}
|
||||
};
|
||||
|
||||
let dir = feed_dir.join(&name);
|
||||
let from = their_path(cfg, Path::new(&done.storage));
|
||||
tokio::fs::create_dir_all(feed_dir).await?;
|
||||
if tokio::fs::metadata(&from).await.with_context(|| format!("finding {}", from.display()))?.is_dir() {
|
||||
tokio::fs::rename(&from, &dir).await
|
||||
} else {
|
||||
tokio::fs::create_dir_all(&dir).await?;
|
||||
tokio::fs::rename(&from, dir.join(from.file_name().unwrap_or_default())).await
|
||||
}
|
||||
// shortcut: a rename only, so SABnzbd's category folder must be on the same mount as
|
||||
// download_dir; copy across filesystems if one ever is not.
|
||||
.with_context(|| format!("moving {} into {}", from.display(), dir.display()))?;
|
||||
// Out of the history once its files are ipx's, so nothing there points at a folder gone.
|
||||
forget(cfg, "history", &done.nzo_id).await;
|
||||
Ok((dir, done.bytes.max(0) as u64))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Added {
|
||||
#[serde(default)]
|
||||
nzo_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// The job by its name, in the queue or the history.
|
||||
async fn find(cfg: &Config, name: &str) -> Result<Option<Job>> {
|
||||
#[derive(Deserialize)]
|
||||
struct Slots<T> {
|
||||
slots: Vec<T>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Q {
|
||||
queue: Slots<Queued>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct H {
|
||||
history: Slots<Done>,
|
||||
}
|
||||
// search matches part of a name, so nzb-9 finds nzb-90 too: the exact one is picked out.
|
||||
let q: Q = call(cfg, &[("mode", "queue"), ("search", name)], None).await?;
|
||||
if let Some(j) = q.queue.slots.into_iter().find(|s| s.filename == name) {
|
||||
return Ok(Some(Job::Queued(j)));
|
||||
}
|
||||
let h: H = call(cfg, &[("mode", "history"), ("search", name)], None).await?;
|
||||
Ok(h.history.slots.into_iter().find(|s| s.name == name).map(Job::Done))
|
||||
}
|
||||
|
||||
/// Takes a job out of the queue or the history, its files with it from the queue (they are half
|
||||
/// of a download), not from the history (they are the episode's, or already moved). Logged, not
|
||||
/// raised: what called it is already giving up, or done.
|
||||
async fn forget(cfg: &Config, from: &str, nzo_id: &str) {
|
||||
let files = if from == "queue" { "1" } else { "0" };
|
||||
let query = [("mode", from), ("name", "delete"), ("value", nzo_id), ("del_files", files)];
|
||||
if let Err(e) = call::<serde_json::Value>(cfg, &query, None).await {
|
||||
tracing::warn!(error = %format!("{e:#}"), "could not remove the NZB from SABnzbd");
|
||||
}
|
||||
}
|
||||
|
||||
/// One call to the API. SABnzbd answers a wrong key or a bad call with 200 and `status: false`.
|
||||
/// Everything goes in the body, which SABnzbd reads as it reads a query: reqwest's errors say the
|
||||
/// URL, and the key in it would have gone to the log and the episode's error.
|
||||
async fn call<T: serde::de::DeserializeOwned>(cfg: &Config, query: &[(&str, &str)], form: Option<Form>) -> Result<T> {
|
||||
let n = &cfg.nzb;
|
||||
let url = format!("{}/api", n.sabnzbd_url.trim_end_matches('/'));
|
||||
let mode = query.first().map_or("", |q| q.1);
|
||||
let params = query.iter().copied().chain([("apikey", n.api_key.as_str()), ("output", "json")]);
|
||||
let req = match form {
|
||||
Some(f) => HTTP.post(url).multipart(params.fold(f, |f, (k, v)| f.text(k.to_owned(), v.to_owned()))),
|
||||
None => HTTP.post(url).form(¶ms.collect::<Vec<_>>()),
|
||||
};
|
||||
let body = req
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("asking SABnzbd ({mode})"))?
|
||||
.error_for_status()
|
||||
.with_context(|| format!("SABnzbd refused {mode}"))?
|
||||
.text()
|
||||
.await?;
|
||||
let v: serde_json::Value = serde_json::from_str(&body).with_context(|| format!("reading SABnzbd's {mode}"))?;
|
||||
if v.get("status") == Some(&serde_json::Value::Bool(false)) {
|
||||
bail!("SABnzbd refused {mode}: {}", v.get("error").and_then(|e| e.as_str()).unwrap_or("no reason given"));
|
||||
}
|
||||
serde_json::from_value(v).with_context(|| format!("reading SABnzbd's {mode}"))
|
||||
}
|
||||
|
||||
/// The job's name in SABnzbd, which is also the folder it finishes in.
|
||||
fn job_name(enclosure: i64) -> String {
|
||||
format!("nzb-{enclosure}")
|
||||
}
|
||||
|
||||
/// Where ipx sees a path SABnzbd gave: `download_dir` in place of `save_path` when SABnzbd's mount
|
||||
/// of it is somewhere else.
|
||||
fn their_path(cfg: &Config, path: &Path) -> PathBuf {
|
||||
let theirs = cfg.nzb.save_path.trim();
|
||||
match path.strip_prefix(theirs) {
|
||||
Ok(rest) if !theirs.is_empty() => cfg.general.download_dir.join(rest),
|
||||
_ => path.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An NZB lists the articles of a release: a few MB even for a large one.
|
||||
const MAX_NZB_FILE: usize = 20 << 20;
|
||||
|
||||
async fn nzb_file(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
|
||||
let mut resp = client.get(url).send().await.context("fetching the .nzb")?.error_for_status()?;
|
||||
let mut out = Vec::new();
|
||||
while let Some(c) = resp.chunk().await.context("reading the .nzb")? {
|
||||
out.extend_from_slice(&c);
|
||||
if out.len() > MAX_NZB_FILE {
|
||||
bail!("the .nzb is larger than {} MB, too large to be one", MAX_NZB_FILE >> 20);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// A SABnzbd that, as the feed's server, serves the .nzb too. A job added is finished at once,
|
||||
/// into its category's folder, and is in the history after one look at the queue. Its address,
|
||||
/// and the calls it was asked to delete.
|
||||
async fn sabnzbd(category_dir: PathBuf, episode: Vec<u8>) -> (std::net::SocketAddr, Arc<Mutex<Vec<String>>>) {
|
||||
use axum::routing::{get, post};
|
||||
use std::collections::HashMap;
|
||||
type Jobs = Arc<Mutex<Vec<(String, u8)>>>;
|
||||
let jobs: Jobs = Default::default();
|
||||
let deleted: Arc<Mutex<Vec<String>>> = Default::default();
|
||||
let (j, d) = (jobs.clone(), deleted.clone());
|
||||
let app = axum::Router::new().route("/ep.nzb", get(|| async { "<?xml version=\"1.0\"?><nzb/>" })).route(
|
||||
"/api",
|
||||
post(move |body: axum::body::Bytes| async move {
|
||||
// Either form: a multipart body read as text is enough to find a field's value.
|
||||
let text = String::from_utf8_lossy(&body);
|
||||
let q: HashMap<String, String> = if text.contains("Content-Disposition") {
|
||||
let field = |p: &str| {
|
||||
let (k, rest) = p.split_once('"')?;
|
||||
Some((k.to_owned(), rest.split_once("\r\n\r\n")?.1.split("\r\n").next()?.to_owned()))
|
||||
};
|
||||
text.split("; name=\"").skip(1).filter_map(field).collect()
|
||||
} else {
|
||||
url::form_urlencoded::parse(&body).into_owned().collect()
|
||||
};
|
||||
if q["apikey"] != "key" {
|
||||
return axum::Json(serde_json::json!({"status": false, "error": "API Key Incorrect"}));
|
||||
}
|
||||
let mut jobs = j.lock().unwrap();
|
||||
let name = q.get("search").or(q.get("nzbname")).cloned().unwrap_or_default();
|
||||
match q["mode"].as_str() {
|
||||
"addfile" => {
|
||||
assert_eq!(q["cat"], "ipx");
|
||||
assert!(q["name"].starts_with("<?xml"), "the .nzb ipx fetched");
|
||||
let folder = category_dir.join(&name);
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
std::fs::write(folder.join("episode.mp3"), &episode).unwrap();
|
||||
jobs.push((name, 0));
|
||||
axum::Json(serde_json::json!({"status": true, "nzo_ids": ["SABnzbd_nzo_1"]}))
|
||||
}
|
||||
_ if q.get("name").is_some_and(|n| n == "delete") => {
|
||||
d.lock().unwrap().push(format!("{} {} {}", q["mode"], q["value"], q["del_files"]));
|
||||
jobs.clear();
|
||||
axum::Json(serde_json::json!({"status": true}))
|
||||
}
|
||||
"queue" => {
|
||||
let slots: Vec<_> = jobs.iter_mut().filter(|(n, _)| n.contains(&name)).filter(|(_, s)| *s == 0).map(|(n, s)| {
|
||||
*s = 1;
|
||||
serde_json::json!({"nzo_id": "SABnzbd_nzo_1", "filename": n, "mb": "2.0", "mbleft": "1.0"})
|
||||
}).collect();
|
||||
axum::Json(serde_json::json!({"queue": {"slots": slots}}))
|
||||
}
|
||||
"history" => {
|
||||
let slots: Vec<_> = jobs.iter().filter(|(n, s)| n.contains(&name) && *s == 1).map(|(n, _)| serde_json::json!({
|
||||
"nzo_id": "SABnzbd_nzo_1", "name": n, "status": "Completed", "bytes": episode.len(),
|
||||
"storage": format!("/sab/ipx/{n}"),
|
||||
})).collect();
|
||||
axum::Json(serde_json::json!({"history": {"slots": slots}}))
|
||||
}
|
||||
m => panic!("no mode {m}"),
|
||||
}
|
||||
}),
|
||||
);
|
||||
let web = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let at = web.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(web, app).await });
|
||||
(at, deleted)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_nzb_lands_in_its_own_folder_and_leaves_sabnzbd_s_history() {
|
||||
let root = std::env::temp_dir().join(format!("ipx-nzb-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let downloads = root.join("downloads");
|
||||
let episode: Vec<u8> = (0..50_000u32).map(|i| (i % 251) as u8).collect();
|
||||
let (at, deleted) = sabnzbd(downloads.join("ipx"), episode.clone()).await;
|
||||
|
||||
let mut cfg = Config::default();
|
||||
cfg.general.download_dir = downloads.clone();
|
||||
cfg.nzb.sabnzbd_url = format!("http://{at}/");
|
||||
cfg.nzb.api_key = "key".into();
|
||||
// SABnzbd sees download_dir as /sab, and its category's folder inside it.
|
||||
cfg.nzb.save_path = "/sab".into();
|
||||
|
||||
let mut seen = Vec::new();
|
||||
let (path, bytes) =
|
||||
fetch(&cfg, &reqwest::Client::new(), &format!("http://{at}/ep.nzb"), &downloads.join("Show"), 9, |d, t| {
|
||||
seen.push((d, t))
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(path, downloads.join("Show/nzb-9"));
|
||||
assert_eq!(bytes, episode.len() as u64);
|
||||
assert_eq!(std::fs::read(path.join("episode.mp3")).unwrap(), episode);
|
||||
assert_eq!(seen, [(1 << 20, 2 << 20)], "progress from the queue's MB");
|
||||
assert_eq!(*deleted.lock().unwrap(), ["history SABnzbd_nzo_1 0"], "out of the history, files kept");
|
||||
|
||||
cfg.nzb.api_key = "wrong".into();
|
||||
let err = fetch(&cfg, &reqwest::Client::new(), &format!("http://{at}/ep.nzb"), &downloads, 10, |_, _| {})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(format!("{err:#}").contains("API Key Incorrect"), "{err:#}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_sabnzbd_gives_is_where_ipx_sees_it() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.general.download_dir = "/downloads".into();
|
||||
let p = Path::new("/ipx-downloads/.sabnzbd/nzb-9");
|
||||
assert_eq!(their_path(&cfg, p), p, "the same mount");
|
||||
cfg.nzb.save_path = "/ipx-downloads".into();
|
||||
assert_eq!(their_path(&cfg, p), Path::new("/downloads/.sabnzbd/nzb-9"));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
//! file address, which carries someone's access, never leaves this server.
|
||||
|
||||
use crate::ctx::Ctx;
|
||||
use ipx_wire::Message as _;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -77,25 +76,7 @@ pub async fn share(
|
||||
.post(format!("{base}/v1/shares"))
|
||||
.bearer_auth(token)
|
||||
.timeout(Duration::from_secs(15))
|
||||
// Protobuf both ways (#465).
|
||||
.header(reqwest::header::CONTENT_TYPE, ipx_wire::PROTOBUF)
|
||||
.header(reqwest::header::ACCEPT, ipx_wire::PROTOBUF)
|
||||
.body(
|
||||
ipx_wire::pb::play::Episode {
|
||||
feed_url: episode.feed_url,
|
||||
guid: episode.guid,
|
||||
feed_title: episode.feed_title,
|
||||
feed_image: episode.feed_image,
|
||||
title: episode.title,
|
||||
description: episode.description,
|
||||
link: episode.link,
|
||||
published: episode.published,
|
||||
duration: episode.duration,
|
||||
audio_url: episode.audio_url,
|
||||
mime: episode.mime,
|
||||
}
|
||||
.encode_to_vec(),
|
||||
);
|
||||
.json(&episode);
|
||||
// Its spans join this request's trace.
|
||||
if let Some(tp) = ipx_directory::otel::traceparent() {
|
||||
req = req.header("traceparent", tp);
|
||||
@@ -106,10 +87,7 @@ pub async fn share(
|
||||
let msg = resp.json::<serde_json::Value>().await.ok().and_then(|v| v["error"].as_str().map(str::to_owned));
|
||||
return Err(NoLink::Failed(format!("ipx-play answered {status}: {}", msg.unwrap_or_default())));
|
||||
}
|
||||
let body = resp.bytes().await.map_err(|e| NoLink::Failed(format!("reading ipx-play's answer: {e:#}")))?;
|
||||
let shared = ipx_wire::pb::play::Shared::decode(body)
|
||||
.map_err(|e| NoLink::Failed(format!("ipx-play's answer did not read: {e}")))?;
|
||||
Ok(ipx_play::Shared { id: shared.id, url: shared.url })
|
||||
resp.json().await.map_err(|e| NoLink::Failed(format!("ipx-play's answer did not read: {e:#}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -142,14 +142,10 @@ pub(crate) async fn reap(ctx: &Ctx, dry_run: bool, standalone: bool) -> Result<(
|
||||
}
|
||||
let removed = r.aged_out.iter().chain(r.over_quota.iter());
|
||||
for c in removed {
|
||||
// Only what is really gone: a folder that would not delete keeps seeding.
|
||||
if !dry_run && !Path::new(&c.path).exists() {
|
||||
ctx.forget_torrent(c.id, &c.path).await;
|
||||
}
|
||||
ctx.out.emit(Event::Reaped { path: c.path.clone(), bytes: c.bytes.max(0) as u64, dry_run });
|
||||
ctx.out.emit(Event::Reaped { path: c.path.clone(), bytes: c.bytes.max(0) as u64 });
|
||||
}
|
||||
if standalone {
|
||||
ctx.out.emit(Event::ReapDone { files: r.aged_out.len() + r.over_quota.len(), bytes: r.bytes_freed, dry_run });
|
||||
ctx.out.emit(Event::ReapDone { files: r.aged_out.len() + r.over_quota.len(), bytes: r.bytes_freed });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
use crate::catalogue::Sub;
|
||||
use crate::ctx::Ctx;
|
||||
use crate::ipc::Event;
|
||||
use crate::{catalogue, cli, config, db, download, feed, lists, metrics, nzb, signals};
|
||||
use crate::{catalogue, cli, config, db, download, feed, lists, metrics, signals, torrent};
|
||||
use anyhow::Result;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -24,8 +23,6 @@ pub(crate) async fn fetch(ctx: &Arc<Ctx>, only: Option<&str>, force: bool, scope
|
||||
let subscribed = ctx.db.subscriber_counts().await?;
|
||||
let mut scanned = 0;
|
||||
let mut fresh: Vec<String> = vec![];
|
||||
// Feeds a list read earlier in this run dropped: still in `due`, scanned they came back (#478).
|
||||
let mut dropped: HashSet<String> = HashSet::new();
|
||||
let in_scope =
|
||||
|s: &Sub| scope.is_empty() || scope.contains(&s.id) || s.cfg.group.as_ref().is_some_and(|g| scope.contains(g));
|
||||
let mut states = ctx.db.http_states().await?;
|
||||
@@ -98,9 +95,6 @@ pub(crate) async fn fetch(ctx: &Arc<Ctx>, only: Option<&str>, force: bool, scope
|
||||
let (id, feed_cfg) = (&sub.id, &sub.cfg);
|
||||
// A task that panicked has no body; scan_one then fetches it itself.
|
||||
let fetched = futures_util::StreamExt::next(&mut bodies).await.and_then(|j| j.ok()).flatten();
|
||||
if dropped.contains(id) {
|
||||
continue;
|
||||
}
|
||||
scanned += 1;
|
||||
ctx.out.emit(Event::FeedStart { feed: id.clone() });
|
||||
match scan_one(ctx, id, feed_cfg, state, force, fetched).await {
|
||||
@@ -119,12 +113,10 @@ pub(crate) async fn fetch(ctx: &Arc<Ctx>, only: Option<&str>, force: bool, scope
|
||||
ctx.out.emit(Event::FeedSkip {
|
||||
feed: id.clone(),
|
||||
reason: format!(
|
||||
"{total} feed(s) listed, {} added, {} unsubscribed, {kept} kept without a listing",
|
||||
added.len(),
|
||||
removed.len()
|
||||
"{total} feed(s) listed, {} added, {removed} unsubscribed, {kept} kept without a listing",
|
||||
added.len()
|
||||
),
|
||||
});
|
||||
dropped.extend(removed);
|
||||
// Read them in the same pass, as the original did, rather than making
|
||||
// the user wait a whole interval for a newly listed show.
|
||||
fresh.extend(added);
|
||||
@@ -229,38 +221,6 @@ pub(crate) fn quiet(usual: u64, same_for: Option<u64>) -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
fn sha256(bytes: &[u8]) -> String {
|
||||
use sha2::Digest as _;
|
||||
sha2::Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// What a feed's "the same as last time" is decided on (#242): its items and what it calls
|
||||
/// itself, not its bytes. Substack stamps a new build time on every read and Patreon signs its
|
||||
/// file links afresh, so their bytes were never the same and they stayed hourly with nothing
|
||||
/// new (#503). An item's text edited with nothing else changed waits for the next full read.
|
||||
fn identity(p: &feed::ParsedFeed) -> Vec<u8> {
|
||||
let bare = |u: &str| u.split(['?', '#']).next().unwrap_or_default().to_owned();
|
||||
let mut out = String::new();
|
||||
let mut put = |s: &str| {
|
||||
out.push_str(s);
|
||||
out.push('\0');
|
||||
};
|
||||
put(p.title.as_deref().unwrap_or_default());
|
||||
put(&bare(p.image.as_deref().unwrap_or_default()));
|
||||
put(p.description.as_deref().unwrap_or_default());
|
||||
put(&p.ttl_mins.map(|t| t.to_string()).unwrap_or_default());
|
||||
for e in &p.entries {
|
||||
put(&e.guid);
|
||||
put(e.title.as_deref().unwrap_or_default());
|
||||
put(&e.published.map(|t| t.to_string()).unwrap_or_default());
|
||||
for enc in &e.enclosures {
|
||||
put(&bare(&enc.url));
|
||||
}
|
||||
put("\x1e");
|
||||
}
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
pub(crate) fn backoff(usual: u64, failing_for: Option<u64>) -> u64 {
|
||||
const CEILING: u64 = 86_400;
|
||||
match failing_for {
|
||||
@@ -287,7 +247,7 @@ pub(crate) enum Outcome {
|
||||
/// The URL is a list of feeds rather than a feed: an OPML, or a Patreon creator's shows.
|
||||
Opml {
|
||||
added: Vec<String>,
|
||||
removed: Vec<String>,
|
||||
removed: usize,
|
||||
kept: usize,
|
||||
total: usize,
|
||||
},
|
||||
@@ -386,27 +346,26 @@ pub(crate) async fn scan_one(
|
||||
return Ok(Outcome::Empty);
|
||||
}
|
||||
|
||||
// A subscribed OPML is a list of feeds, not a feed. The original matched on a ".opml"
|
||||
// URL; sniffing the body also catches one served from a URL without that extension.
|
||||
let opml = feed::is_opml(&bytes);
|
||||
let parsed = if opml { None } else { Some(feed::parse(&bytes)?) };
|
||||
|
||||
// The same feed as last time, from a server that ignores "not modified": nothing to read,
|
||||
// The same body as last time, from a server that ignores "not modified": nothing to read,
|
||||
// as a 304 would have said (#242). Not when something is missing that a read would fill, as
|
||||
// above, nor when someone asked for a full check.
|
||||
let hash = sha256(&match &parsed {
|
||||
Some(p) => identity(p),
|
||||
None => bytes.to_vec(),
|
||||
});
|
||||
let hash = {
|
||||
use sha2::Digest as _;
|
||||
sha2::Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect::<String>()
|
||||
};
|
||||
if !force && state.body_hash.as_deref() == Some(hash.as_str()) && stored.entries > 0 && stored.image.is_some() {
|
||||
ctx.db.touch_feed(id, &feed_cfg.url).await?;
|
||||
return Ok(Outcome::NotModified);
|
||||
}
|
||||
|
||||
let Some(mut parsed) = parsed else {
|
||||
// A subscribed OPML is a list of feeds, not a feed. The original matched on a ".opml"
|
||||
// URL; sniffing the body also catches one served from a URL without that extension.
|
||||
if feed::is_opml(&bytes) {
|
||||
ctx.db.touch_feed(id, &feed_cfg.url).await?;
|
||||
return lists::sync_opml(ctx, id, &bytes).await;
|
||||
};
|
||||
}
|
||||
|
||||
let mut parsed = feed::parse(&bytes)?;
|
||||
// Artwork on http moves to https where its host serves it (#110), before it is compared
|
||||
// with what is stored, which is then the https address too.
|
||||
let mut secure = std::collections::HashMap::new();
|
||||
@@ -565,10 +524,9 @@ pub(crate) async fn scan_one(
|
||||
let dest_dir = cfg.general.download_dir.join(&folder);
|
||||
|
||||
for item in ctx.db.pending(id, budget).await? {
|
||||
// NZBs go the torrents' way and are counted with them (#496).
|
||||
if let Some(via) = download::handed_on(&item.url, item.mime.as_deref()) {
|
||||
if !via.on(&ctx.cfg()) {
|
||||
ctx.db.mark_enclosure(&item.url, "skipped", Some(via.off())).await?;
|
||||
if download::looks_like_torrent(&item.url, item.mime.as_deref()) {
|
||||
if !ctx.cfg().torrent.enabled {
|
||||
ctx.db.mark_enclosure(&item.url, "skipped", Some("torrents disabled")).await?;
|
||||
ctx.out.emit(Event::TorrentDeferred { feed: id.to_string(), url: item.url.clone() });
|
||||
scan.torrents += 1;
|
||||
continue;
|
||||
@@ -576,11 +534,11 @@ pub(crate) async fn scan_one(
|
||||
if ctx.detach_torrents {
|
||||
// 'downloading' keeps the next scan from queueing it a second time.
|
||||
ctx.db.mark_enclosure(&item.url, "downloading", None).await?;
|
||||
spawn_torrent(ctx, via, id.to_string(), item.id, item.url.clone(), dest_dir.clone());
|
||||
spawn_torrent(ctx, id.to_string(), item.id, item.url.clone(), dest_dir.clone());
|
||||
scan.torrents += 1;
|
||||
continue;
|
||||
}
|
||||
match torrent_one(ctx, via, id, item.id, &item.url, &dest_dir).await {
|
||||
match torrent_one(ctx, id, item.id, &item.url, &dest_dir).await {
|
||||
Ok((path, bytes)) => {
|
||||
ctx.db.mark_downloaded(&item.url, &path, bytes).await?;
|
||||
ctx.out.emit(Event::DownloadDone {
|
||||
@@ -780,23 +738,23 @@ pub(crate) async fn fetch_one(
|
||||
})
|
||||
.await?;
|
||||
|
||||
if let download::Kind::Via(via) = got.kind {
|
||||
// The MIME lied. Hand the URL to qBittorrent or SABnzbd instead of filing a .torrent or
|
||||
// an .nzb as if it were an episode.
|
||||
if matches!(got.kind, download::Kind::Torrent) {
|
||||
// The MIME lied. Hand the URL to the torrent session instead of filing a .torrent
|
||||
// as if it were an episode.
|
||||
let _ = tokio::fs::remove_file(&got.tmp).await;
|
||||
if !via.on(&ctx.cfg()) {
|
||||
ctx.db.mark_enclosure(url, "skipped", Some(via.off())).await?;
|
||||
anyhow::bail!("body is a {via:?} and {}", via.off());
|
||||
if !ctx.cfg().torrent.enabled {
|
||||
ctx.db.mark_enclosure(url, "skipped", Some("torrents disabled")).await?;
|
||||
anyhow::bail!("body is a torrent and torrents are disabled");
|
||||
}
|
||||
// As one advertised as a torrent goes: off the worker where it can be, and recorded either
|
||||
// way. Run here and never recorded, it stayed pending, and every scan of its feed ran it
|
||||
// again, on the worker, for up to the stall limit and the seeding time (#155).
|
||||
if ctx.detach_torrents {
|
||||
ctx.db.mark_enclosure(url, "downloading", None).await?;
|
||||
spawn_torrent(ctx, via, feed_id.to_owned(), enclosure, url.to_owned(), dest_dir.to_owned());
|
||||
spawn_torrent(ctx, feed_id.to_owned(), enclosure, url.to_owned(), dest_dir.to_owned());
|
||||
return Ok(None);
|
||||
}
|
||||
let (path, bytes) = torrent_one(ctx, via, feed_id, enclosure, url, dest_dir).await?;
|
||||
let (path, bytes) = torrent_one(ctx, feed_id, enclosure, url, dest_dir).await?;
|
||||
ctx.db.mark_downloaded(url, &path, bytes).await?;
|
||||
return Ok(Some((path, bytes)));
|
||||
}
|
||||
@@ -806,16 +764,9 @@ pub(crate) async fn fetch_one(
|
||||
Ok(Some((path, got.bytes)))
|
||||
}
|
||||
|
||||
/// Runs a torrent or an NZB off the command worker, so feed scans and HTTP downloads keep moving
|
||||
/// while qBittorrent or SABnzbd has it.
|
||||
pub(crate) fn spawn_torrent(
|
||||
ctx: &Arc<Ctx>,
|
||||
via: download::Via,
|
||||
feed_id: String,
|
||||
enclosure: i64,
|
||||
url: String,
|
||||
dest_dir: PathBuf,
|
||||
) {
|
||||
/// Runs a torrent off the command worker, so feed scans and HTTP downloads keep moving
|
||||
/// while it fetches metadata, transfers and then seeds.
|
||||
pub(crate) fn spawn_torrent(ctx: &Arc<Ctx>, feed_id: String, enclosure: i64, url: String, dest_dir: PathBuf) {
|
||||
let ctx = ctx.clone();
|
||||
tokio::spawn(async move {
|
||||
// Held for the whole job, so a feed full of torrents cannot open hundreds at once.
|
||||
@@ -823,7 +774,7 @@ pub(crate) fn spawn_torrent(
|
||||
Ok(p) => p,
|
||||
Err(_) => return,
|
||||
};
|
||||
let outcome = torrent_one(&ctx, via, &feed_id, enclosure, &url, &dest_dir).await;
|
||||
let outcome = torrent_one(&ctx, &feed_id, enclosure, &url, &dest_dir).await;
|
||||
let db = &ctx.db;
|
||||
match outcome {
|
||||
Ok((path, bytes)) => {
|
||||
@@ -871,19 +822,20 @@ pub(crate) async fn download_one(ctx: &Arc<Ctx>, id: i64) -> Result<()> {
|
||||
let dest_dir = cfg.general.download_dir.join(&folder);
|
||||
|
||||
ctx.out.emit(Event::FeedStart { feed: enc.feed_id.clone() });
|
||||
let via = download::handed_on(&enc.url, enc.mime.as_deref());
|
||||
if let Some(via) = via
|
||||
&& via.on(&cfg)
|
||||
&& ctx.detach_torrents
|
||||
{
|
||||
let is_torrent = download::looks_like_torrent(&enc.url, enc.mime.as_deref());
|
||||
if is_torrent && cfg.torrent.enabled && ctx.detach_torrents {
|
||||
ctx.db.mark_enclosure(&enc.url, "downloading", None).await?;
|
||||
spawn_torrent(ctx, via, enc.feed_id.clone(), enc.id, enc.url.clone(), dest_dir);
|
||||
spawn_torrent(ctx, enc.feed_id.clone(), enc.id, enc.url.clone(), dest_dir);
|
||||
return Ok(());
|
||||
}
|
||||
let result = match via {
|
||||
Some(via) if !via.on(&cfg) => Err(anyhow::anyhow!("{}", via.off())),
|
||||
Some(via) => torrent_one(ctx, via, &enc.feed_id, enc.id, &enc.url, &dest_dir).await.map(Some),
|
||||
None => fetch_one(ctx, &enc.feed_id, enc.id, feed_cfg, &enc.url, &dest_dir).await,
|
||||
let result = if is_torrent {
|
||||
if !cfg.torrent.enabled {
|
||||
Err(anyhow::anyhow!("torrents are disabled"))
|
||||
} else {
|
||||
torrent_one(ctx, &enc.feed_id, enc.id, &enc.url, &dest_dir).await.map(Some)
|
||||
}
|
||||
} else {
|
||||
fetch_one(ctx, &enc.feed_id, enc.id, feed_cfg, &enc.url, &dest_dir).await
|
||||
};
|
||||
|
||||
match result {
|
||||
@@ -919,7 +871,6 @@ pub(crate) async fn download_one(ctx: &Arc<Ctx>, id: i64) -> Result<()> {
|
||||
#[tracing::instrument(name = "torrent", skip_all, fields(feed = feed_id, enclosure = enclosure))]
|
||||
pub(crate) async fn torrent_one(
|
||||
ctx: &Arc<Ctx>,
|
||||
via: download::Via,
|
||||
feed_id: &str,
|
||||
enclosure: i64,
|
||||
url: &str,
|
||||
@@ -928,27 +879,24 @@ pub(crate) async fn torrent_one(
|
||||
let name = download::filename_for(url, None);
|
||||
let mut last_pct = -1i64;
|
||||
let cfg = ctx.cfg();
|
||||
let progress = |done: u64, total: u64| {
|
||||
if let Some(pct) = (done * 100).checked_div(total).map(|p| p as i64)
|
||||
&& pct > last_pct
|
||||
{
|
||||
last_pct = pct;
|
||||
ctx.out.emit(Event::Progress {
|
||||
feed: feed_id.to_string(),
|
||||
enclosure,
|
||||
url: url.to_string(),
|
||||
file: name.clone(),
|
||||
done,
|
||||
total: Some(total),
|
||||
});
|
||||
}
|
||||
};
|
||||
match via {
|
||||
download::Via::Torrent => {
|
||||
ctx.torrents().await?.fetch(&cfg, &ctx.client, url, dest_dir, enclosure, progress).await
|
||||
}
|
||||
download::Via::Nzb => nzb::fetch(&cfg, &ctx.client, url, dest_dir, enclosure, progress).await,
|
||||
}
|
||||
ctx.torrents()
|
||||
.await?
|
||||
.fetch(&cfg, &ctx.client, url, &torrent::own_folder(dest_dir, enclosure), |done, total| {
|
||||
if let Some(pct) = (done * 100).checked_div(total).map(|p| p as i64)
|
||||
&& pct > last_pct
|
||||
{
|
||||
last_pct = pct;
|
||||
ctx.out.emit(Event::Progress {
|
||||
feed: feed_id.to_string(),
|
||||
enclosure,
|
||||
url: url.to_string(),
|
||||
file: name.clone(),
|
||||
done,
|
||||
total: Some(total),
|
||||
});
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -997,22 +945,6 @@ mod tests {
|
||||
assert_eq!(same(&set), hour, "someone's own schedule wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_feed_is_the_same_by_its_items_not_its_build_time_or_signed_links() {
|
||||
let feed = |built: &str, token: &str, title: &str| {
|
||||
let xml = format!(
|
||||
"<rss><channel><title>Show</title><lastBuildDate>{built}</lastBuildDate>\
|
||||
<item><guid>1</guid><title>{title}</title>\
|
||||
<enclosure url=\"https://c.example/a.mp3?token={token}\" type=\"audio/mpeg\"/></item>\
|
||||
</channel></rss>"
|
||||
);
|
||||
sha256(&identity(&feed::parse(xml.as_bytes()).unwrap()))
|
||||
};
|
||||
let first = feed("Mon, 01 Jan 2024 00:00:00 GMT", "a", "One");
|
||||
assert_eq!(first, feed("Tue, 02 Jan 2024 00:00:00 GMT", "b", "One"), "rebuilt and re-signed, the same");
|
||||
assert_ne!(first, feed("Mon, 01 Jan 2024 00:00:00 GMT", "a", "Two"), "an item renamed is a change");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_same_body_again_is_not_modified_unless_a_check_is_forced() {
|
||||
let base = empty_or_feed_server().await;
|
||||
@@ -1032,9 +964,10 @@ mod tests {
|
||||
matches!(scan_one(&ctx, "same", &cfg, &state, true, None).await, Ok(Outcome::Feed(_))),
|
||||
"a forced check reads it"
|
||||
);
|
||||
// Only an item's text edited: the same feed, read at the next forced or changed read (#503).
|
||||
let edited = config::Feed { url: format!("{base}/fixed"), ..feed() };
|
||||
assert!(matches!(scan_one(&ctx, "same", &edited, &state, false, None).await, Ok(Outcome::NotModified)));
|
||||
// Changed: read, and the same from now.
|
||||
let moved = config::Feed { url: format!("{base}/fixed"), ..feed() };
|
||||
assert!(matches!(scan_one(&ctx, "same", &moved, &state, false, None).await, Ok(Outcome::Feed(_))));
|
||||
assert_ne!(ctx.db.http_state("same").await.unwrap().body_hash, state.body_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1148,17 +1081,17 @@ mod tests {
|
||||
let state = |ctx: Arc<Ctx>| async move { ctx.db.strings_for_test("SELECT state FROM enclosures").await };
|
||||
|
||||
// Detached, as the daemon runs them: no slot free, so it waits its turn as 'downloading'.
|
||||
let mut on = config::Config::default();
|
||||
on.torrent.qbittorrent_url = "http://127.0.0.1:9".into();
|
||||
let mut ctx = test_ctx(on).await;
|
||||
let mut ctx = test_ctx(config::Config::default()).await;
|
||||
ctx.detach_torrents = true;
|
||||
ctx.torrent_slots = Arc::new(tokio::sync::Semaphore::new(0));
|
||||
let ctx = Arc::new(ctx);
|
||||
assert_eq!(scan(ctx.clone()).await, (0, 1), "counted as a torrent, not a download");
|
||||
assert_eq!(state(ctx).await, ["downloading"], "so the next scan does not queue it again");
|
||||
|
||||
// With no qBittorrent to send it to, it is skipped and still counted.
|
||||
let ctx = Arc::new(test_ctx(config::Config::default()).await);
|
||||
// Turned off, it is skipped and still counted.
|
||||
let mut cfg = config::Config::default();
|
||||
cfg.torrent.enabled = false;
|
||||
let ctx = Arc::new(test_ctx(cfg).await);
|
||||
assert_eq!(scan(ctx.clone()).await, (0, 1));
|
||||
assert_eq!(state(ctx).await, ["skipped"]);
|
||||
}
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
//! What a search reads (#459): each item's title and text, the markup taken out, lowercased and cut
|
||||
//! short, kept in `entries.search_text` beside the HTML. Matching the HTML itself took 5 s on All
|
||||
//! Subscriptions, most of it reading 4 GB of descriptions; the plain text is a fraction of that,
|
||||
//! and Postgres indexes it with pg_trgm, so a part of a word still finds the word, as before.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tracing::Instrument;
|
||||
|
||||
use crate::ctx::Ctx;
|
||||
|
||||
/// Enough of a post for its subject to be in it; a word only past this in a very long post is not
|
||||
/// found. It keeps the index a size the shared Postgres carries.
|
||||
pub const MAX_CHARS: usize = 4000;
|
||||
/// Items made at a time, and how long between looks for more once none are left.
|
||||
const BATCH: i64 = 500;
|
||||
const EVERY: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
/// The title, then the text with its markup taken out (an image's alt and title kept, as Signals
|
||||
/// read them), lowercased, its spaces made single, and at most `MAX_CHARS` long.
|
||||
pub fn search_text(title: Option<&str>, description: Option<&str>) -> String {
|
||||
let text = crate::signals::text_of(description.unwrap_or(""));
|
||||
let all = format!("{} {}", title.unwrap_or(""), text).to_lowercase();
|
||||
all.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(MAX_CHARS).collect()
|
||||
}
|
||||
|
||||
/// Makes every item's search text that is missing, then the index, then looks again now and then:
|
||||
/// a scan that changes an item's title or text leaves its search text to be made again here, and
|
||||
/// a search reads that item the old way until it is.
|
||||
pub async fn run(ctx: Arc<Ctx>, mut stop: tokio::sync::watch::Receiver<bool>) {
|
||||
let mut indexed = false;
|
||||
loop {
|
||||
let pass = async {
|
||||
let made = fill(&ctx).await?;
|
||||
if !indexed {
|
||||
indexed = ctx.db.search_index().instrument(crate::db::step("search_index")).await?;
|
||||
}
|
||||
anyhow::Ok(made)
|
||||
};
|
||||
tokio::select! {
|
||||
_ = stop.changed() => return,
|
||||
done = pass.instrument(tracing::info_span!("search_text")) => match done {
|
||||
Ok(n) if n > 0 => tracing::info!(items = n, "search: made items' search text"),
|
||||
Ok(_) => {}
|
||||
Err(e) => tracing::warn!(error = %format!("{e:#}"), "search: items' search text could not be made"),
|
||||
},
|
||||
}
|
||||
tokio::select! {
|
||||
_ = stop.changed() => return,
|
||||
_ = tokio::time::sleep(EVERY) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every item without search text, given one, a batch at a time: how many.
|
||||
async fn fill(ctx: &Ctx) -> anyhow::Result<usize> {
|
||||
name_untitled(&ctx.db).await?;
|
||||
let mut made = 0;
|
||||
loop {
|
||||
let batch = ctx.db.unsearched(BATCH).await?;
|
||||
if batch.is_empty() {
|
||||
return Ok(made);
|
||||
}
|
||||
for (feed, guid, title, description) in &batch {
|
||||
ctx.db.set_search_text(feed, guid, &search_text(title.as_deref(), description.as_deref())).await?;
|
||||
}
|
||||
made += batch.len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Names the items stored before a feed's untitled ones were named as they were read (#502),
|
||||
/// once, in batches; then finds none and costs one query a pass. Before the search text, which
|
||||
/// the name goes into.
|
||||
pub(crate) async fn name_untitled(db: &crate::db::Db) -> anyhow::Result<()> {
|
||||
let mut after = (String::new(), String::new());
|
||||
loop {
|
||||
let batch = db.untitled((&after.0, &after.1), BATCH).await?;
|
||||
let Some(last) = batch.last() else { return Ok(()) };
|
||||
after = (last.0.clone(), last.1.clone());
|
||||
for (feed, guid, description, file) in &batch {
|
||||
if let Some(name) = crate::feed::untitled_name(description.as_deref(), file.as_deref()) {
|
||||
db.name_untitled(feed, guid, &name).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_text_is_the_words_not_the_markup() {
|
||||
let t = search_text(
|
||||
Some("Apple's NEW Thing"),
|
||||
Some(r#"<p>Read <a href="https://x.example/app">more</a></p><img alt="A Chart" src="c.png">"#),
|
||||
);
|
||||
assert_eq!(t, "apple's new thing read more a chart");
|
||||
assert!(!t.contains("href") && !t.contains("x.example"), "an address in a tag is not a word of the post");
|
||||
assert_eq!(search_text(None, None), "");
|
||||
let long = "word ".repeat(2000);
|
||||
assert_eq!(search_text(Some("Title"), Some(&long)).chars().count(), MAX_CHARS);
|
||||
assert!(search_text(Some("Title"), Some(&long)).starts_with("title word"), "the title is always in it");
|
||||
}
|
||||
}
|
||||
@@ -497,7 +497,7 @@ fn chosen(answer: &serde_json::Value, candidates: &[(String, String)]) -> Option
|
||||
/// Show notes are HTML: Jev is given their words, and an image's alt and title text, which is all
|
||||
/// the words some posts have. xkcd's is a comic and its hover text; dropping the tag whole sent Jev
|
||||
/// "Ground Effect" alone, an F1 aerodynamics term, and the comic went into Formula 1 (#267).
|
||||
pub(crate) fn text_of(html: &str) -> String {
|
||||
fn text_of(html: &str) -> String {
|
||||
let mut out = String::with_capacity(html.len());
|
||||
let mut tag: Option<String> = None;
|
||||
for c in html.chars() {
|
||||
|
||||
@@ -1,39 +1,20 @@
|
||||
//! Torrent enclosures through qBittorrent's Web API (#494). ipx fetches the .torrent itself, hands
|
||||
//! it over with the enclosure's own folder as its save path, and watches it to the end; qBittorrent
|
||||
//! downloads it and seeds it to the limits set here. Until then ipx ran a BitTorrent session of its
|
||||
//! own (librqbit), which replaced iPXDownloader.getTorrent and the vendored BitTorrent 4.2.1.
|
||||
//! Torrent enclosures via librqbit. Replaces iPXDownloader.getTorrent and the vendored
|
||||
//! BitTorrent 4.2.1 + khashmir tree.
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use reqwest::header::{COOKIE, SET_COOKIE};
|
||||
use reqwest::multipart::{Form, Part};
|
||||
use serde::Deserialize;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use librqbit::{AddTorrent, AddTorrentOptions, AddTorrentResponse, Session, SessionOptions};
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::config::Config;
|
||||
use librqbit::{ListenerOptions, ManagedTorrent};
|
||||
|
||||
pub struct Torrents {
|
||||
/// Not the guarded client feeds are fetched with: qBittorrent is on the LAN by design, at the
|
||||
/// address the admin gave, which the guard would refuse (#320).
|
||||
http: reqwest::Client,
|
||||
/// The session cookie, `name=value`; qBittorrent 5 names it after its port.
|
||||
cookie: tokio::sync::Mutex<Option<String>>,
|
||||
session: Arc<Session>,
|
||||
}
|
||||
|
||||
/// What `torrents/info` says of one torrent, as much as ipx reads.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct Info {
|
||||
hash: String,
|
||||
state: String,
|
||||
progress: f64,
|
||||
total_size: i64,
|
||||
completed: i64,
|
||||
}
|
||||
|
||||
/// How often a running torrent is looked at.
|
||||
const POLL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// How long a torrent may make no progress before we give up on it. The original called
|
||||
/// this torrentMaxBeatTime and counted display ticks; a wall clock is easier to reason about.
|
||||
fn stall_limit(cfg: &Config) -> Duration {
|
||||
@@ -41,192 +22,132 @@ fn stall_limit(cfg: &Config) -> Duration {
|
||||
}
|
||||
|
||||
impl Torrents {
|
||||
pub fn new() -> Result<Self> {
|
||||
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build()?;
|
||||
Ok(Self { http, cookie: Default::default() })
|
||||
pub async fn new(cfg: &Config) -> Result<Self> {
|
||||
let (lo, _hi) = cfg.torrent.ports();
|
||||
let listen_addr: SocketAddr = format!("0.0.0.0:{lo}").parse()?;
|
||||
|
||||
let opts = SessionOptions {
|
||||
listen: Some(ListenerOptions { listen_addr, ..Default::default() }),
|
||||
client_name_and_version: Some(concat!("ipx ", env!("CARGO_PKG_VERSION")).into()),
|
||||
// A test's swarm is two sessions and a tracker on 127.0.0.1, not the public DHT or the LAN.
|
||||
dht: if cfg!(test) { None } else { Some(Default::default()) },
|
||||
disable_local_service_discovery: cfg!(test),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// The session root is only a fallback; every torrent names its own output folder.
|
||||
let session = Session::new_with_opts(cfg.general.download_dir.clone(), opts)
|
||||
.await
|
||||
.context("starting the torrent session")?;
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
/// Downloads a torrent (a .torrent URL or a magnet link) through qBittorrent into the
|
||||
/// enclosure's own folder inside `feed_dir`, which is the path returned: a file of several or
|
||||
/// one. Done once qBittorrent has all of it; the seeding is qBittorrent's.
|
||||
/// Downloads a torrent (a .torrent URL or a magnet link) straight into `dest_dir`,
|
||||
/// seeds it up to the configured limit, then stops. `dest_dir` is the torrent's own
|
||||
/// folder (`own_folder`), and it is the path returned: a file of several or one.
|
||||
///
|
||||
/// Downloading in place rather than into a staging dir is deliberate: seeding serves
|
||||
/// the files it downloaded, so moving them first would break it.
|
||||
pub async fn fetch(
|
||||
&self,
|
||||
cfg: &Config,
|
||||
client: &reqwest::Client,
|
||||
url: &str,
|
||||
feed_dir: &Path,
|
||||
enclosure: i64,
|
||||
dest_dir: &Path,
|
||||
mut on_progress: impl FnMut(u64, u64),
|
||||
) -> Result<(PathBuf, u64)> {
|
||||
let dir = own_folder(feed_dir, enclosure);
|
||||
tokio::fs::create_dir_all(&dir).await?;
|
||||
tokio::fs::create_dir_all(dest_dir).await?;
|
||||
|
||||
let limit = stall_limit(cfg);
|
||||
let tag = tag(enclosure);
|
||||
|
||||
// There already when ipx stopped while it ran (#410): taken up where qBittorrent has it.
|
||||
if self.info(cfg, &tag).await?.is_none() {
|
||||
let file = if url.starts_with("http://") || url.starts_with("https://") {
|
||||
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
|
||||
let got = tokio::time::timeout(limit, torrent_file(client, url))
|
||||
.await
|
||||
.map_err(|_| anyhow!("no .torrent after {} minutes, gave up", limit.as_secs() / 60))??;
|
||||
Some(got)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let t = &cfg.torrent;
|
||||
let save = save_path(cfg, &dir);
|
||||
let said = self
|
||||
.api(cfg, "torrents/add", |req| {
|
||||
let form = Form::new()
|
||||
.text("savepath", save.clone())
|
||||
.text("tags", tag.clone())
|
||||
// The files straight into the folder, as the path recorded says (#318).
|
||||
.text("contentLayout", "NoSubfolder")
|
||||
.text("ratioLimit", t.seed_ratio.to_string())
|
||||
.text("seedingTimeLimit", t.seed_time_mins.to_string());
|
||||
req.multipart(match &file {
|
||||
Some(b) => form.part("torrents", Part::bytes(b.clone()).file_name("episode.torrent")),
|
||||
None => form.text("urls", url.to_owned()),
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
if said.trim() == "Fails." {
|
||||
bail!("qBittorrent would not take the torrent; it may have it already");
|
||||
}
|
||||
}
|
||||
|
||||
let mut last = (-1i64, Instant::now());
|
||||
let done = loop {
|
||||
tokio::time::sleep(POLL).await;
|
||||
// A qBittorrent restarting is a pause, not a failure, until the stall limit says so.
|
||||
let info = match self.info(cfg, &tag).await {
|
||||
Ok(i) => i,
|
||||
Err(e) if last.1.elapsed() < limit => {
|
||||
tracing::debug!(error = %format!("{e:#}"), "qBittorrent did not answer");
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let Some(info) = info else { bail!("the torrent is no longer in qBittorrent") };
|
||||
if matches!(info.state.as_str(), "error" | "missingFiles") {
|
||||
self.delete(cfg, &info.hash).await;
|
||||
bail!("qBittorrent says the torrent failed ({})", info.state);
|
||||
}
|
||||
on_progress(info.completed.max(0) as u64, info.total_size.max(0) as u64);
|
||||
if info.progress >= 1.0 && info.total_size > 0 {
|
||||
break info;
|
||||
}
|
||||
if info.completed > last.0 {
|
||||
last = (info.completed, Instant::now());
|
||||
} else if last.1.elapsed() > limit {
|
||||
// Leave the partial files behind; the row records the failure.
|
||||
self.delete(cfg, &info.hash).await;
|
||||
bail!("no progress for {} minutes, gave up", limit.as_secs() / 60);
|
||||
}
|
||||
let source = if url.starts_with("http://") || url.starts_with("https://") {
|
||||
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
|
||||
let file = tokio::time::timeout(limit, torrent_file(client, url))
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("no .torrent after {} minutes, gave up", limit.as_secs() / 60))??;
|
||||
AddTorrent::from_bytes(file)
|
||||
} else {
|
||||
AddTorrent::from_url(url)
|
||||
};
|
||||
|
||||
// Resolving a magnet's metadata happens inside add_torrent, and against a dead
|
||||
// swarm it never returns. The stall budget has to cover this phase too, or a
|
||||
// torrent nobody is seeding wedges the scan forever.
|
||||
let added = tokio::time::timeout(
|
||||
limit,
|
||||
self.session.add_torrent(
|
||||
source,
|
||||
Some(AddTorrentOptions {
|
||||
output_folder: Some(dest_dir.to_string_lossy().into_owned()),
|
||||
overwrite: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("no metadata after {} minutes, gave up", limit.as_secs() / 60))?
|
||||
.context("adding the torrent")?;
|
||||
|
||||
let (id, handle) = match added {
|
||||
AddTorrentResponse::Added(id, h) | AddTorrentResponse::AlreadyManaged(id, h) => (id, h),
|
||||
AddTorrentResponse::ListOnly(_) => bail!("torrent added in list-only mode"),
|
||||
};
|
||||
|
||||
let mut last_progress = 0u64;
|
||||
let mut last_move = Instant::now();
|
||||
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let stats = handle.stats();
|
||||
|
||||
if let Some(err) = &stats.error {
|
||||
let _ = self.session.delete(id.into(), false).await;
|
||||
bail!("torrent failed: {err}");
|
||||
}
|
||||
on_progress(stats.progress_bytes, stats.total_bytes);
|
||||
|
||||
if stats.finished {
|
||||
break;
|
||||
}
|
||||
if stats.progress_bytes > last_progress {
|
||||
last_progress = stats.progress_bytes;
|
||||
last_move = Instant::now();
|
||||
} else if last_move.elapsed() > limit {
|
||||
// Leave the partial files behind; the row records the failure.
|
||||
let _ = self.session.delete(id.into(), false).await;
|
||||
bail!("no progress for {} minutes, gave up", limit.as_secs() / 60);
|
||||
}
|
||||
}
|
||||
|
||||
// The torrent's own name is the publisher's to choose, and librqbit checks it only when it
|
||||
// picks the folder itself: joined on, "/config" or ".." pointed Delete, the reaper and
|
||||
// /media at anything the daemon can reach (#318). The folder is ours, so it is the path.
|
||||
let path = dest_dir.to_owned();
|
||||
let size = handle.stats().total_bytes;
|
||||
|
||||
self.seed(cfg, &handle).await;
|
||||
self.session.delete(id.into(), false).await.context("releasing the torrent")?;
|
||||
|
||||
Ok((path, size))
|
||||
}
|
||||
|
||||
/// Seeds until the ratio or the time limit is reached, whichever comes first.
|
||||
async fn seed(&self, cfg: &Config, handle: &Arc<ManagedTorrent>) {
|
||||
if cfg.torrent.seed_ratio <= 0.0 || cfg.torrent.seed_time_mins == 0 {
|
||||
self.delete(cfg, &done.hash).await;
|
||||
return;
|
||||
}
|
||||
Ok((dir, done.total_size as u64))
|
||||
}
|
||||
|
||||
/// Takes an episode's torrent out of qBittorrent once ipx has deleted its files, so it does not
|
||||
/// stay there seeding nothing, as missing files (#495). Nothing when it is not there.
|
||||
pub async fn forget(&self, cfg: &Config, enclosure: i64) {
|
||||
match self.info(cfg, &tag(enclosure)).await {
|
||||
Ok(Some(info)) => self.delete(cfg, &info.hash).await,
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(error = %format!("{e:#}"), enclosure, "could not ask qBittorrent for the torrent"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn info(&self, cfg: &Config, tag: &str) -> Result<Option<Info>> {
|
||||
let body = self.api(cfg, "torrents/info", |req| req.form(&[("tag", tag)])).await?;
|
||||
let mut all: Vec<Info> = serde_json::from_str(&body).context("reading qBittorrent's torrent list")?;
|
||||
Ok((!all.is_empty()).then(|| all.swap_remove(0)))
|
||||
}
|
||||
|
||||
/// Takes the torrent out of qBittorrent, keeping its files. A failure is logged, not raised:
|
||||
/// what called it is already giving up, or done.
|
||||
async fn delete(&self, cfg: &Config, hash: &str) {
|
||||
let form = [("hashes", hash), ("deleteFiles", "false")];
|
||||
if let Err(e) = self.api(cfg, "torrents/delete", |req| req.form(&form)).await {
|
||||
tracing::warn!(error = %format!("{e:#}"), "could not remove the torrent from qBittorrent");
|
||||
}
|
||||
}
|
||||
|
||||
/// One call to the Web API, signing in first when a user is set, and again once if the session
|
||||
/// has expired (a 403). The answer's body.
|
||||
async fn api(
|
||||
&self,
|
||||
cfg: &Config,
|
||||
path: &str,
|
||||
body: impl Fn(reqwest::RequestBuilder) -> reqwest::RequestBuilder,
|
||||
) -> Result<String> {
|
||||
let base = cfg.torrent.qbittorrent_url.trim_end_matches('/');
|
||||
for retry in [false, true] {
|
||||
let cookie = self.cookie(cfg, retry).await?;
|
||||
let mut req = body(self.http.post(format!("{base}/api/v2/{path}")));
|
||||
if let Some(c) = cookie {
|
||||
req = req.header(COOKIE, c);
|
||||
let deadline = Instant::now() + Duration::from_secs(cfg.torrent.seed_time_mins * 60);
|
||||
loop {
|
||||
let stats = handle.stats();
|
||||
if ratio(stats.uploaded_bytes, stats.total_bytes) >= cfg.torrent.seed_ratio {
|
||||
tracing::info!(ratio = cfg.torrent.seed_ratio, "seed ratio reached");
|
||||
return;
|
||||
}
|
||||
let resp = req.send().await.with_context(|| format!("asking qBittorrent ({path})"))?;
|
||||
if resp.status() == reqwest::StatusCode::FORBIDDEN && !retry && !cfg.torrent.username.is_empty() {
|
||||
continue;
|
||||
if Instant::now() >= deadline {
|
||||
tracing::info!(mins = cfg.torrent.seed_time_mins, "seed time reached");
|
||||
return;
|
||||
}
|
||||
let resp = resp.error_for_status().with_context(|| format!("qBittorrent refused {path}"))?;
|
||||
return Ok(resp.text().await?);
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
unreachable!("the second try returns")
|
||||
}
|
||||
|
||||
async fn cookie(&self, cfg: &Config, fresh: bool) -> Result<Option<String>> {
|
||||
let t = &cfg.torrent;
|
||||
if t.username.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut held = self.cookie.lock().await;
|
||||
if fresh || held.is_none() {
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}/api/v2/auth/login", t.qbittorrent_url.trim_end_matches('/')))
|
||||
.form(&[("username", t.username.as_str()), ("password", t.password.as_str())])
|
||||
.send()
|
||||
.await
|
||||
.context("signing in to qBittorrent")?;
|
||||
let got = resp
|
||||
.headers()
|
||||
.get_all(SET_COOKIE)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok()?.split(';').next())
|
||||
.find(|c| c.split_once('=').is_some_and(|(name, _)| name.contains("SID")))
|
||||
.map(str::to_owned);
|
||||
*held = Some(got.ok_or_else(|| anyhow!("qBittorrent refused ipx's username and password"))?);
|
||||
}
|
||||
Ok(held.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// How ipx finds an enclosure's torrent in qBittorrent: by hash it cannot, since a magnet has none
|
||||
/// until its metadata has come.
|
||||
fn tag(enclosure: i64) -> String {
|
||||
format!("ipx-{enclosure}")
|
||||
}
|
||||
|
||||
/// Whether `path` is the folder `fetch` gave `enclosure`: a torrent of ours, then.
|
||||
pub fn is_own_folder(path: &Path, enclosure: i64) -> bool {
|
||||
path.file_name() == own_folder(Path::new(""), enclosure).file_name()
|
||||
}
|
||||
|
||||
/// Where qBittorrent is to write `dir`: the same path, or `save_path` in place of `download_dir`
|
||||
/// when qBittorrent's mount of it is somewhere else.
|
||||
fn save_path(cfg: &Config, dir: &Path) -> String {
|
||||
let theirs = cfg.torrent.save_path.trim();
|
||||
match dir.strip_prefix(&cfg.general.download_dir) {
|
||||
Ok(rest) if !theirs.is_empty() => Path::new(theirs).join(rest).display().to_string(),
|
||||
_ => dir.display().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,95 +175,93 @@ pub fn own_folder(feed_dir: &Path, enclosure: i64) -> PathBuf {
|
||||
feed_dir.join(format!("torrent-{enclosure}"))
|
||||
}
|
||||
|
||||
/// Uploaded over total. A zero-byte torrent counts as fully seeded rather than dividing by zero.
|
||||
pub fn ratio(uploaded: u64, total: u64) -> f64 {
|
||||
if total == 0 {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
uploaded as f64 / total as f64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A qBittorrent that wants a sign-in, and as the feed's server serves the .torrent too. A
|
||||
/// torrent added is finished at once: the file is written into its save path, as qBittorrent
|
||||
/// would. Its address, and the hashes deleted.
|
||||
async fn qbittorrent(episode: Vec<u8>) -> (std::net::SocketAddr, Arc<std::sync::Mutex<Vec<String>>>) {
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::{get, post};
|
||||
type Held = Arc<std::sync::Mutex<Vec<serde_json::Value>>>;
|
||||
let held: Held = Default::default();
|
||||
let deleted: Arc<std::sync::Mutex<Vec<String>>> = Default::default();
|
||||
let signed_in = |h: &HeaderMap| h.get("cookie").is_some_and(|c| c == "QBT_SID_8080=abc");
|
||||
// The multipart body read as text: enough to find a field's value in a test.
|
||||
let field = |body: &str, name: &str| {
|
||||
let at = body.find(&format!("name=\"{name}\"\r\n\r\n")).unwrap() + name.len() + 11;
|
||||
body[at..].split("\r\n").next().unwrap().to_owned()
|
||||
};
|
||||
let (h1, h2, d) = (held.clone(), held.clone(), deleted.clone());
|
||||
let app = axum::Router::new()
|
||||
.route("/ep.torrent", get(|| async { "d4:infode" }))
|
||||
.route(
|
||||
"/api/v2/auth/login",
|
||||
post(|body: String| async move {
|
||||
if body == "username=ipx&password=pw" {
|
||||
([("set-cookie", "QBT_SID_8080=abc; HttpOnly; path=/")], "Ok.").into_response()
|
||||
} else {
|
||||
"Fails.".into_response()
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/api/v2/torrents/add",
|
||||
post(move |h: HeaderMap, body: axum::body::Bytes| async move {
|
||||
if !signed_in(&h) {
|
||||
return (StatusCode::FORBIDDEN, "Forbidden").into_response();
|
||||
}
|
||||
let body = String::from_utf8_lossy(&body);
|
||||
assert!(body.contains("d4:infode"), "the .torrent ipx fetched");
|
||||
assert_eq!(field(&body, "contentLayout"), "NoSubfolder");
|
||||
let save = field(&body, "savepath");
|
||||
std::fs::write(Path::new(&save).join("episode.mp3"), &episode).unwrap();
|
||||
let n = episode.len();
|
||||
h1.lock().unwrap().push(serde_json::json!({"hash": "h1", "tags": field(&body, "tags"),
|
||||
"state": "uploading", "progress": 1.0, "total_size": n, "completed": n}));
|
||||
"Ok.".into_response()
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/api/v2/torrents/info",
|
||||
post(move |h: HeaderMap, body: String| async move {
|
||||
if !signed_in(&h) {
|
||||
return (StatusCode::FORBIDDEN, "Forbidden").into_response();
|
||||
}
|
||||
let tag = body.strip_prefix("tag=").unwrap().to_owned();
|
||||
let all = h2.lock().unwrap().iter().filter(|t| t["tags"] == tag).cloned().collect::<Vec<_>>();
|
||||
axum::Json(all).into_response()
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/api/v2/torrents/delete",
|
||||
post(move |body: String| async move {
|
||||
d.lock().unwrap().push(body);
|
||||
"Ok."
|
||||
}),
|
||||
);
|
||||
fn free_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
/// A swarm on 127.0.0.1: a seeding session holding `file`, and a web server answering for the
|
||||
/// .torrent (`/ep.torrent`) and as its tracker, naming the seed as the one peer. The server's
|
||||
/// address, and the seeding session, which stops seeding when dropped.
|
||||
async fn swarm(file: &Path) -> (SocketAddr, Arc<Session>) {
|
||||
let web = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let at = web.local_addr().unwrap();
|
||||
let seed_port = free_port();
|
||||
let made = librqbit::create_torrent(
|
||||
file,
|
||||
librqbit::CreateTorrentOptions {
|
||||
name: None,
|
||||
trackers: vec![format!("http://{at}/announce")],
|
||||
piece_length: Some(16 * 1024),
|
||||
},
|
||||
&librqbit::spawn_utils::BlockingSpawner::new(2),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let torrent = made.as_bytes().unwrap();
|
||||
// Compact peers: the address's four bytes, then the port's two.
|
||||
let mut peers = b"d8:intervali60e5:peers6:".to_vec();
|
||||
peers.extend_from_slice(&[127, 0, 0, 1]);
|
||||
peers.extend_from_slice(&seed_port.to_be_bytes());
|
||||
peers.push(b'e');
|
||||
let app = axum::Router::new()
|
||||
.route("/ep.torrent", axum::routing::get(move || std::future::ready(torrent.clone())))
|
||||
.route("/announce", axum::routing::get(move || std::future::ready(peers.clone())));
|
||||
tokio::spawn(async move { axum::serve(web, app).await });
|
||||
(at, deleted)
|
||||
|
||||
let seed = Session::new_with_opts(
|
||||
file.parent().unwrap().to_owned(),
|
||||
SessionOptions {
|
||||
dht: None,
|
||||
disable_local_service_discovery: true,
|
||||
listen: Some(ListenerOptions {
|
||||
listen_addr: format!("127.0.0.1:{seed_port}").parse().unwrap(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
seed.add_torrent(
|
||||
AddTorrent::from_bytes(made.as_bytes().unwrap()),
|
||||
Some(AddTorrentOptions {
|
||||
output_folder: Some(file.parent().unwrap().display().to_string()),
|
||||
overwrite: true,
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
(at, seed)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_detached_torrent_lands_in_its_own_folder_is_recorded_and_frees_its_slot() {
|
||||
let root = std::env::temp_dir().join(format!("ipx-torrent-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let downloads = root.join("downloads");
|
||||
let (seeded, downloads) = (root.join("seed"), root.join("downloads"));
|
||||
std::fs::create_dir_all(&seeded).unwrap();
|
||||
let episode: Vec<u8> = (0..200_000u32).map(|i| (i * 7 % 251) as u8).collect();
|
||||
let (at, deleted) = qbittorrent(episode.clone()).await;
|
||||
std::fs::write(seeded.join("episode.mp3"), &episode).unwrap();
|
||||
let (at, _seed) = swarm(&seeded.join("episode.mp3")).await;
|
||||
|
||||
let mut cfg = Config::default();
|
||||
cfg.general.download_dir = downloads.clone();
|
||||
cfg.general.fetch_internal = vec!["127.0.0.1".into()];
|
||||
cfg.torrent.qbittorrent_url = format!("http://{at}/");
|
||||
cfg.torrent.username = "ipx".into();
|
||||
cfg.torrent.password = "pw".into();
|
||||
cfg.torrent.enabled = true;
|
||||
let port = free_port();
|
||||
cfg.torrent.port_range = format!("{port}-{port}");
|
||||
cfg.torrent.seed_ratio = 0.0;
|
||||
let mut ctx = crate::test_util::test_ctx(cfg.clone()).await;
|
||||
ctx.detach_torrents = true;
|
||||
@@ -355,15 +274,8 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
crate::scan::spawn_torrent(
|
||||
&ctx,
|
||||
crate::download::Via::Torrent,
|
||||
"f".into(),
|
||||
9,
|
||||
url.clone(),
|
||||
downloads.join("Show"),
|
||||
);
|
||||
let row = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
crate::scan::spawn_torrent(&ctx, "f".into(), 9, url.clone(), downloads.join("Show"));
|
||||
let row = tokio::time::timeout(Duration::from_secs(90), async {
|
||||
loop {
|
||||
let row = ctx.db.enclosure(9).await.unwrap().unwrap();
|
||||
if row.state != "downloading" {
|
||||
@@ -373,45 +285,17 @@ mod tests {
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the torrent finished within 30 s");
|
||||
.expect("the torrent finished within 90 s");
|
||||
let folder = own_folder(&downloads.join("Show"), 9);
|
||||
assert_eq!((row.state.as_str(), row.last_error.as_deref()), ("done", None));
|
||||
assert_eq!(row.path.as_deref(), Some(folder.display().to_string().as_str()), "the folder is ours (#318)");
|
||||
assert_eq!(std::fs::read(folder.join("episode.mp3")).unwrap(), episode);
|
||||
assert_eq!(
|
||||
*deleted.lock().unwrap(),
|
||||
["hashes=h1&deleteFiles=false"],
|
||||
"no seeding asked for: let go, files kept"
|
||||
);
|
||||
// Its files deleted, by the reaper or Delete: out of qBittorrent too, and only a torrent (#495).
|
||||
deleted.lock().unwrap().clear();
|
||||
ctx.forget_torrent(9, &downloads.join("Show/episode.mp3").display().to_string()).await;
|
||||
assert!(deleted.lock().unwrap().is_empty(), "a file that is not a torrent's folder");
|
||||
ctx.forget_torrent(9, &folder.display().to_string()).await;
|
||||
assert_eq!(*deleted.lock().unwrap(), ["hashes=h1&deleteFiles=false"]);
|
||||
// The slot is let go once the row is written; give the task its moment.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(ctx.torrent_slots.available_permits(), 2, "the slot is free again");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_an_enclosures_own_folder_is_its_torrent() {
|
||||
assert!(is_own_folder(&own_folder(Path::new("/downloads/Show"), 9), 9));
|
||||
assert!(!is_own_folder(&own_folder(Path::new("/downloads/Show"), 9), 19));
|
||||
assert!(!is_own_folder(Path::new("/downloads/Show/episode.mp3"), 9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_path_is_where_qbittorrent_sees_the_folder() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.general.download_dir = "/downloads".into();
|
||||
let dir = Path::new("/downloads/Show/torrent-9");
|
||||
assert_eq!(save_path(&cfg, dir), "/downloads/Show/torrent-9", "the same mount");
|
||||
cfg.torrent.save_path = "/data/ipx".into();
|
||||
assert_eq!(save_path(&cfg, dir), "/data/ipx/Show/torrent-9");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_torrent_file_from_an_internal_address_is_refused_unless_allowed() {
|
||||
let app = axum::Router::new().route("/ep.torrent", axum::routing::get(|| async { "d4:infode" }));
|
||||
@@ -433,6 +317,14 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ratio_handles_the_empty_torrent() {
|
||||
assert_eq!(ratio(0, 100), 0.0);
|
||||
assert_eq!(ratio(50, 100), 0.5);
|
||||
assert_eq!(ratio(200, 100), 2.0);
|
||||
assert!(ratio(0, 0).is_infinite(), "must not divide by zero or seed forever");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_endless_torrent_file_stops_at_the_cap() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
@@ -48,57 +48,6 @@ pub struct WebState {
|
||||
pub wrong: Wrong,
|
||||
}
|
||||
|
||||
/// Each route's protobuf messages (#465), beside its JSON: what its body is and what it answers.
|
||||
const WIRE: ipx_wire::Routes = &[
|
||||
("POST", "/api/login", "ipx.Credentials", "ipx.SignedIn"),
|
||||
("GET", "/api/me", "", "ipx.Me"),
|
||||
("PATCH", "/api/me", "ipx.MePatch", ""),
|
||||
("GET", "/api/tokens", "", "ipx.ApiTokens"),
|
||||
("POST", "/api/tokens", "ipx.NewToken", "ipx.MadeToken"),
|
||||
("POST", "/api/push/devices", "ipx.PushDevice", ""),
|
||||
("GET", "/api/feeds", "", "ipx.FeedRows"),
|
||||
("POST", "/api/feeds", "ipx.NewFeed", "ipx.AddedFeed"),
|
||||
("PATCH", "/api/feeds/{id}", "ipx.FeedPatch", ""),
|
||||
("GET", "/api/feeds/{id}/entries", "", "ipx.EntryPage"),
|
||||
("GET", "/api/feeds/{id}/seasons", "", "ipx.SeasonRows"),
|
||||
("GET", "/api/entries", "", "ipx.EntryPage"),
|
||||
("GET", "/api/queue", "", "ipx.EntryPage"),
|
||||
("PUT", "/api/queue", "ipx.QueueItems", "ipx.EntryPage"),
|
||||
("GET", "/api/playlists", "", "ipx.PlaylistRows"),
|
||||
("POST", "/api/playlists", "ipx.PlaylistSpec", "ipx.PlaylistId"),
|
||||
("PATCH", "/api/playlists/{id}", "ipx.PlaylistSpec", ""),
|
||||
("GET", "/api/playlists/{id}/entries", "", "ipx.EntryPage"),
|
||||
("GET", "/api/signals", "", "ipx.SignalRows"),
|
||||
("POST", "/api/signals", "ipx.SignalBody", "ipx.SignalId"),
|
||||
("POST", "/api/signals/icon", "ipx.IconAsk", "ipx.Icon"),
|
||||
("PATCH", "/api/signals/{id}", "ipx.SignalBody", ""),
|
||||
("GET", "/api/signals/{id}/entries", "", "ipx.EntryPage"),
|
||||
("GET", "/api/entries/{feed_id}/{guid}", "", "ipx.EntryRow"),
|
||||
("POST", "/api/entries/{feed_id}/{guid}/flags", "ipx.Flags", "ipx.FeedRow"),
|
||||
("POST", "/api/entries/{feed_id}/{guid}/position", "ipx.Position", ""),
|
||||
("POST", "/api/entries/{feed_id}/{guid}/share", "ipx.ShareBody", "ipx.ShareLink"),
|
||||
("GET", "/api/enclosures/{id}/chapters", "", "ipx.Chapters"),
|
||||
("POST", "/api/feeds/{id}/read-all", "", "ipx.Marked"),
|
||||
("POST", "/api/read-all", "", "ipx.Marked"),
|
||||
("POST", "/api/feeds/{id}/download-latest", "ipx.HowMany", "ipx.Queued"),
|
||||
("POST", "/api/fetch", "ipx.FetchBody", ""),
|
||||
("POST", "/api/opml", "ipx.OpmlBody", "ipx.OpmlImported"),
|
||||
("GET", "/api/settings", "", "ipx.Settings"),
|
||||
("PATCH", "/api/settings", "ipx.SettingsPatch", ""),
|
||||
("GET", "/api/directory-status", "", "ipx.DirStatus"),
|
||||
("GET", "/api/status", "", "ipx.Status"),
|
||||
("GET", "/api/popular", "", "ipx.PopularRows"),
|
||||
("GET", "/api/directory", "", "ipx.PopularRows"),
|
||||
("GET", "/api/directory/{id}", "", "ipx.Listed"),
|
||||
("GET", "/api/directory-admin", "", "ipx.DirAdmin"),
|
||||
("POST", "/api/popular/{id}", "", "ipx.FeedId"),
|
||||
("GET", "/api/users", "", "ipx.Accounts"),
|
||||
("POST", "/api/users", "ipx.NewUser", ""),
|
||||
("PATCH", "/api/users/{id}", "ipx.UserPatch", ""),
|
||||
("GET", "/api/logs", "", "ipx.LogPage"),
|
||||
("POST", "/api/client", "ipx.ClientEvent", ""),
|
||||
];
|
||||
|
||||
pub fn router(state: WebState) -> Router {
|
||||
Router::new()
|
||||
.route("/api/me", get(me).patch(patch_me))
|
||||
@@ -110,12 +59,7 @@ pub fn router(state: WebState) -> Router {
|
||||
.route("/api/feeds", get(feeds).post(add_feed))
|
||||
.route("/api/feeds/{id}", patch(patch_feed).delete(remove_feed))
|
||||
.route("/api/feeds/{id}/entries", get(entries))
|
||||
.route("/api/feeds/{id}/seasons", get(seasons))
|
||||
.route("/api/entries", get(all_entries))
|
||||
.route("/api/queue", get(queue).put(set_queue))
|
||||
.route("/api/playlists", get(list_playlists).post(add_playlist))
|
||||
.route("/api/playlists/{id}", patch(patch_playlist).delete(remove_playlist))
|
||||
.route("/api/playlists/{id}/entries", get(playlist_entries))
|
||||
.route("/api/signals", get(list_signals).post(add_signal))
|
||||
.route("/api/signals/icon", post(pick_signal_icon))
|
||||
.route("/api/signals/{id}", patch(patch_signal).delete(remove_signal))
|
||||
@@ -129,7 +73,6 @@ pub fn router(state: WebState) -> Router {
|
||||
.route("/api/feeds/{id}/download-latest", post(download_latest))
|
||||
.route("/api/enclosures/{id}/download", post(download_now))
|
||||
.route("/api/enclosures/{id}", delete(delete_file))
|
||||
.route("/api/enclosures/{id}/chapters", get(chapters))
|
||||
.route("/api/fetch", post(fetch_now))
|
||||
.route("/api/opml", get(export_opml).post(import_opml))
|
||||
.route("/api/settings", get(get_settings).patch(patch_settings))
|
||||
@@ -159,7 +102,6 @@ pub fn router(state: WebState) -> Router {
|
||||
// Signing in cannot require being signed in, so these sit outside the auth layer.
|
||||
.route("/api/login", post(login))
|
||||
.route("/api/login-check", get(login_check))
|
||||
.route_layer(middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
|
||||
.route_layer(middleware::from_fn(name_span))
|
||||
.layer(middleware::from_fn(cross_site_refused))
|
||||
.layer(middleware::from_fn(access_log))
|
||||
@@ -1015,8 +957,6 @@ struct FeedRow {
|
||||
private: bool,
|
||||
/// Private whatever it is marked, for a login or an address with a key in it.
|
||||
private_by_address: bool,
|
||||
/// Has an audio or video file: on the Podcasts shelf (#474).
|
||||
podcast: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -1065,8 +1005,7 @@ async fn feed_rows(state: &WebState, user: &crate::db::User, only: Option<&str>)
|
||||
let up = feed.group.as_deref().and_then(|g| mine.get(g));
|
||||
let Some(mine) = mine.get(id) else { continue };
|
||||
// A feed not scanned yet has no row: blank, as feed_summary gave it.
|
||||
let crate::db::FeedListing { summary: s, ttl_mins, blocked, unread, podcast } =
|
||||
listed.remove(id).unwrap_or_default();
|
||||
let crate::db::FeedListing { summary: s, ttl_mins, blocked, unread } = listed.remove(id).unwrap_or_default();
|
||||
out.push(FeedRow {
|
||||
private: feed.private,
|
||||
private_by_address: crate::directory::looks_private(&crate::config::Feed {
|
||||
@@ -1129,7 +1068,6 @@ async fn feed_rows(state: &WebState, user: &crate::db::User, only: Option<&str>)
|
||||
kept: kept.contains(id),
|
||||
hide_from_all: hidden.contains(id),
|
||||
hide_from_signals: quiet.contains(id),
|
||||
podcast,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
@@ -1839,36 +1777,12 @@ mod tests {
|
||||
assert_eq!(image_kind("application/octet-stream", &jpeg).as_deref(), Some("image/jpeg"));
|
||||
assert_eq!(image_kind("", b"\x89PNG\r\n").as_deref(), Some("image/png"));
|
||||
assert_eq!(image_kind("", b"RIFF\0\0\0\0WEBPVP8").as_deref(), Some("image/webp"));
|
||||
assert_eq!(image_kind("application/octet-stream", b"\xff\x0a\xfa").as_deref(), Some("image/jxl"));
|
||||
assert_eq!(image_kind("", b"\0\0\0\x0cJXL \r\n\x87\n\0").as_deref(), Some("image/jxl"));
|
||||
assert_eq!(image_kind("image/avif", b"").as_deref(), Some("image/avif"));
|
||||
// A page, or an untyped SVG, stays refused.
|
||||
assert_eq!(image_kind("text/html", &jpeg), None);
|
||||
assert_eq!(image_kind("", b"<svg onload=alert(1)>"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_artwork_failure_lasts_when_the_publisher_or_ipx_refuses_it() {
|
||||
// Answers each request with the status its path names.
|
||||
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let at = l.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
|
||||
while let Ok((mut s, _)) = l.accept().await {
|
||||
let mut buf = [0; 1024];
|
||||
let n = s.read(&mut buf).await.unwrap_or(0);
|
||||
let code = String::from_utf8_lossy(&buf[..n]).split('/').nth(1).unwrap_or("500")[..3].to_owned();
|
||||
let _ = s.write_all(format!("HTTP/1.1 {code} X\r\ncontent-length: 0\r\n\r\n").as_bytes()).await;
|
||||
}
|
||||
});
|
||||
let c = reqwest::Client::new();
|
||||
for (code, want) in [(404, true), (410, true), (408, false), (429, false), (503, false)] {
|
||||
let e = c.get(format!("http://{at}/{code}")).send().await.unwrap().error_for_status().unwrap_err();
|
||||
assert_eq!(lasting(&e.into()), want, "{code}");
|
||||
}
|
||||
assert!(lasting(&anyhow::anyhow!("larger than 20971520 bytes")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signal_icon_is_a_style_and_a_plain_name() {
|
||||
assert_eq!(signal_icon(Some("solid/robot".into())).ok().flatten().as_deref(), Some("solid/robot"));
|
||||
@@ -2046,9 +1960,6 @@ struct Page {
|
||||
sort: Option<String>,
|
||||
#[serde(default)]
|
||||
dir: Option<String>,
|
||||
/// One season of a podcast's (#482): its number, or `none` for the episodes naming none.
|
||||
#[serde(default)]
|
||||
season: Option<String>,
|
||||
}
|
||||
|
||||
fn fifty() -> i64 {
|
||||
@@ -2076,30 +1987,6 @@ async fn entries(
|
||||
entry_page(&state, user.id, Some(&ids[..]), None, &page).await
|
||||
}
|
||||
|
||||
/// A season as the page sends it (#482): its number, `none` for the episodes naming none, or
|
||||
/// nothing for every season.
|
||||
fn season_of(s: Option<&str>) -> Result<db::Season, ApiError> {
|
||||
Ok(match s.map(str::trim) {
|
||||
None | Some("") => db::Season::Any,
|
||||
Some("none") => db::Season::Unnumbered,
|
||||
Some(n) => db::Season::Of(n.parse().map_err(|_| ApiError::bad_request(format!("no season {n:?}")))?),
|
||||
})
|
||||
}
|
||||
|
||||
/// A podcast's seasons, for its page to offer one at a time (#482). An OPML's are its shows'
|
||||
/// together, as its items are.
|
||||
async fn seasons(
|
||||
State(state): State<WebState>,
|
||||
Path(id): Path<String>,
|
||||
user: crate::db::User,
|
||||
) -> Result<Json<Vec<crate::db::SeasonCount>>, ApiError> {
|
||||
subscribed(&state, &user, &id).await?;
|
||||
let mut ids = state.ctx.db.group_members(user.id, &id).await?;
|
||||
ids.push(id);
|
||||
let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
|
||||
Ok(Json(state.ctx.db.seasons(user.id, &ids).await?))
|
||||
}
|
||||
|
||||
/// A feed's items and files are for the people who subscribe to it (#129). Anyone signed in
|
||||
/// could read any feed's by its id, a paid one's included, with its enclosure addresses, which
|
||||
/// can carry the subscriber's key, and fetch, queue or delete its files by theirs. A feed in
|
||||
@@ -2135,7 +2022,6 @@ async fn entry_page(
|
||||
let order =
|
||||
crate::db::order_sql(page.sort.as_deref().unwrap_or("published"), page.dir.as_deref().unwrap_or("desc"));
|
||||
let limit = page.limit.clamp(1, 200);
|
||||
let season = season_of(page.season.as_deref())?;
|
||||
// Which list, so a slow one's trace says what was asked of it (#287). The search's words stay
|
||||
// out: they are the reader's own.
|
||||
let in_list = tracing::info_span!(
|
||||
@@ -2147,32 +2033,19 @@ async fn entry_page(
|
||||
offset = page.offset,
|
||||
limit,
|
||||
search = search.is_some(),
|
||||
season = ?season,
|
||||
);
|
||||
// A season is of a podcast's own page; All Subscriptions and a Signal have none to pick.
|
||||
let in_season = feeds.filter(|_| season != db::Season::Any);
|
||||
let list = async {
|
||||
match (signal, in_season) {
|
||||
(Some(id), _) => {
|
||||
match signal {
|
||||
Some(id) => {
|
||||
db.signal_entries(user_id, id, filter, search, page.offset, limit, &order).instrument(in_list).await
|
||||
}
|
||||
(None, Some(fs)) => {
|
||||
db.season_entries(user_id, fs, season, filter, search, page.offset, limit, &order)
|
||||
.instrument(in_list)
|
||||
.await
|
||||
}
|
||||
(None, None) => {
|
||||
db.entries_of(user_id, feeds, filter, search, page.offset, limit, &order).instrument(in_list).await
|
||||
}
|
||||
None => db.entries_of(user_id, feeds, filter, search, page.offset, limit, &order).instrument(in_list).await,
|
||||
}
|
||||
};
|
||||
let count = async {
|
||||
match (signal, in_season) {
|
||||
(Some(id), _) => db.signal_count(user_id, id, filter, search).instrument(db::step("count_in")).await,
|
||||
(None, Some(fs)) => {
|
||||
db.season_count(user_id, fs, season, filter, search).instrument(db::step("count_in")).await
|
||||
}
|
||||
(None, None) => db.count_of(user_id, feeds, filter, search).instrument(db::step("count_in")).await,
|
||||
match signal {
|
||||
Some(id) => db.signal_count(user_id, id, filter, search).instrument(db::step("count_in")).await,
|
||||
None => db.count_of(user_id, feeds, filter, search).instrument(db::step("count_in")).await,
|
||||
}
|
||||
};
|
||||
// The count beside the list, not after it: each waited on the other, about 40 and 24 ms on the
|
||||
@@ -2188,132 +2061,6 @@ async fn entry_page(
|
||||
Ok(Json(EntryPage { total, entries: rows }))
|
||||
}
|
||||
|
||||
/// One of Up Next's episodes, as the page names it.
|
||||
#[derive(Deserialize)]
|
||||
struct QueueItem {
|
||||
feed_id: String,
|
||||
guid: String,
|
||||
}
|
||||
|
||||
/// Up Next (#473): the episodes lined up to play, in order, as a page of entries.
|
||||
async fn queue(State(state): State<WebState>, user: crate::db::User) -> Result<Json<EntryPage>, ApiError> {
|
||||
queue_page(&state, user.id).await
|
||||
}
|
||||
|
||||
/// Puts Up Next in the order sent, and answers with it as it now is: what was not yours to queue
|
||||
/// is left out rather than refused, so a list one device held while another unsubscribed still
|
||||
/// saves.
|
||||
async fn set_queue(
|
||||
State(state): State<WebState>,
|
||||
user: crate::db::User,
|
||||
Json(items): Json<Vec<QueueItem>>,
|
||||
) -> Result<Json<EntryPage>, ApiError> {
|
||||
if items.len() > 500 {
|
||||
return Err(ApiError::bad_request("Up Next holds at most 500 episodes"));
|
||||
}
|
||||
let items: Vec<(String, String)> = items.into_iter().map(|i| (i.feed_id, i.guid)).collect();
|
||||
state.ctx.db.set_queue(user.id, &items).await?;
|
||||
queue_page(&state, user.id).await
|
||||
}
|
||||
|
||||
async fn queue_page(state: &WebState, user_id: i64) -> Result<Json<EntryPage>, ApiError> {
|
||||
let mut rows = state.ctx.db.queue_of(user_id).await?;
|
||||
let mut sanitizer = feed_sanitizer();
|
||||
for row in &mut rows {
|
||||
clean_row(&mut sanitizer, row);
|
||||
}
|
||||
crate::deadair::for_reader(&state.ctx, user_id, &mut rows).await?;
|
||||
Ok(Json(EntryPage { total: rows.len() as i64, entries: rows }))
|
||||
}
|
||||
|
||||
/// A playlist as sent, made fit to keep: a name, the podcasts this person subscribes to, the
|
||||
/// priority ones among them.
|
||||
async fn playlist_spec(
|
||||
state: &WebState,
|
||||
user: &crate::db::User,
|
||||
mut spec: crate::db::PlaylistSpec,
|
||||
) -> Result<crate::db::PlaylistSpec, ApiError> {
|
||||
spec.name = spec.name.trim().to_owned();
|
||||
if spec.name.is_empty() || spec.name.chars().count() > 100 {
|
||||
return Err(ApiError::bad_request("a playlist needs a name of up to 100 characters"));
|
||||
}
|
||||
let mine: std::collections::HashSet<String> =
|
||||
state.ctx.db.subscriptions_for(user.id).await?.into_iter().map(|s| s.feed_id).collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
spec.feeds.retain(|f| mine.contains(f) && seen.insert(f.clone()));
|
||||
if spec.feeds.is_empty() {
|
||||
return Err(ApiError::bad_request("a playlist needs at least one podcast you subscribe to"));
|
||||
}
|
||||
spec.priority.retain(|f| spec.feeds.contains(f));
|
||||
spec.priority.dedup();
|
||||
Ok(spec)
|
||||
}
|
||||
|
||||
/// Smart playlists (#476).
|
||||
async fn list_playlists(
|
||||
State(state): State<WebState>,
|
||||
user: crate::db::User,
|
||||
) -> Result<Json<Vec<crate::db::PlaylistRow>>, ApiError> {
|
||||
Ok(Json(state.ctx.db.playlists(user.id).await?))
|
||||
}
|
||||
|
||||
async fn add_playlist(
|
||||
State(state): State<WebState>,
|
||||
user: crate::db::User,
|
||||
Json(spec): Json<crate::db::PlaylistSpec>,
|
||||
) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
let spec = playlist_spec(&state, &user, spec).await?;
|
||||
let id = state.ctx.db.save_playlist(user.id, None, &spec).await?;
|
||||
Ok(Json(serde_json::json!({ "id": id })))
|
||||
}
|
||||
|
||||
async fn patch_playlist(
|
||||
State(state): State<WebState>,
|
||||
Path(id): Path<i64>,
|
||||
user: crate::db::User,
|
||||
Json(spec): Json<crate::db::PlaylistSpec>,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let spec = playlist_spec(&state, &user, spec).await?;
|
||||
match state.ctx.db.save_playlist(user.id, Some(id), &spec).await? {
|
||||
Some(_) => Ok(StatusCode::NO_CONTENT),
|
||||
None => Err(ApiError::not_found("no such playlist")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove_playlist(
|
||||
State(state): State<WebState>,
|
||||
Path(id): Path<i64>,
|
||||
user: crate::db::User,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
if !state.ctx.db.remove_playlist(user.id, id).await? {
|
||||
return Err(ApiError::not_found("no such playlist"));
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// A playlist's episodes, in its own order: the page's sort does not apply.
|
||||
async fn playlist_entries(
|
||||
State(state): State<WebState>,
|
||||
Path(id): Path<i64>,
|
||||
user: crate::db::User,
|
||||
Query(page): Query<Page>,
|
||||
) -> Result<Json<EntryPage>, ApiError> {
|
||||
let Some(p) = state.ctx.db.playlist(user.id, id).await? else {
|
||||
return Err(ApiError::not_found("no such playlist"));
|
||||
};
|
||||
let feeds: Vec<&str> = p.spec.feeds.iter().map(String::as_str).collect();
|
||||
let filter = if p.spec.only_unplayed { crate::db::Filter::Unread } else { crate::db::Filter::All };
|
||||
let order = crate::db::playlist_order(&p.spec);
|
||||
let limit = page.limit.clamp(1, 200);
|
||||
let mut rows = state.ctx.db.entries_of(user.id, Some(&feeds), filter, None, page.offset, limit, &order).await?;
|
||||
let mut sanitizer = feed_sanitizer();
|
||||
for row in &mut rows {
|
||||
clean_row(&mut sanitizer, row);
|
||||
}
|
||||
crate::deadair::for_reader(&state.ctx, user.id, &mut rows).await?;
|
||||
Ok(Json(EntryPage { total: p.items, entries: rows }))
|
||||
}
|
||||
|
||||
/// One entry, in the clock of the file this person will play (`deadair::for_reader`).
|
||||
async fn one_entry(
|
||||
State(state): State<WebState>,
|
||||
@@ -2726,53 +2473,6 @@ struct Force {
|
||||
force: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ChaptersAsked {
|
||||
/// Played from DeadAir's shortened copy, whose clock the starts are then given in.
|
||||
#[serde(default)]
|
||||
deadair: bool,
|
||||
}
|
||||
|
||||
/// A file's chapters, for Now Playing (#477): from the file its item names, else from the file
|
||||
/// itself once downloaded. None is an empty list, as is one that could not be read: the player
|
||||
/// plays on without them, and the trace has why.
|
||||
async fn chapters(
|
||||
State(state): State<WebState>,
|
||||
Path(id): Path<i64>,
|
||||
user: crate::db::User,
|
||||
Query(q): Query<ChaptersAsked>,
|
||||
) -> Result<Json<Vec<crate::chapters::Chapter>>, ApiError> {
|
||||
let enc = state.ctx.db.enclosure(id).await?.ok_or_else(|| ApiError::not_found(format!("no file {id}")))?;
|
||||
subscribed(&state, &user, &enc.feed_id).await?;
|
||||
let mut list = Vec::new();
|
||||
if let Some(url) = state.ctx.db.chapters_url(&enc.feed_id, &enc.guid).await? {
|
||||
match crate::chapters::fetch(&state.ctx.client, &url).instrument(db::step("chapters_fetch")).await {
|
||||
Ok(l) => list = l,
|
||||
Err(e) => {
|
||||
tracing::debug!(url = %crate::feed::redact(&url), error = %format!("{e:#}"), "could not read the chapters")
|
||||
}
|
||||
}
|
||||
}
|
||||
if list.is_empty()
|
||||
&& let Some(path) = &enc.path
|
||||
{
|
||||
let file = crate::download::playable(std::path::Path::new(path));
|
||||
match crate::chapters::in_file(&file).instrument(db::step("chapters_file")).await {
|
||||
Ok(l) => list = l,
|
||||
Err(e) => tracing::debug!(error = %format!("{e:#}"), "could not read the file's chapters"),
|
||||
}
|
||||
}
|
||||
if q.deadair
|
||||
&& !list.is_empty()
|
||||
&& let Some(plan) = crate::deadair::plan_for(&state.ctx, user.id, &enc.feed_id, id).await?
|
||||
{
|
||||
for c in &mut list {
|
||||
c.start = crate::deadair::to_copy(&plan.cuts, (c.start * 1000.0) as i64) as f64 / 1000.0;
|
||||
}
|
||||
}
|
||||
Ok(Json(list))
|
||||
}
|
||||
|
||||
async fn delete_file(
|
||||
State(state): State<WebState>,
|
||||
Path(id): Path<i64>,
|
||||
@@ -2814,18 +2514,11 @@ async fn delete_file(
|
||||
{
|
||||
return Err(e.into());
|
||||
}
|
||||
if let Some(path) = &enc.path {
|
||||
state.ctx.forget_torrent(id, path).await;
|
||||
}
|
||||
// The row survives as 'reaped', which is what stops the next scan re-downloading it.
|
||||
state.ctx.db.mark_reaped(id).await?;
|
||||
state
|
||||
.events
|
||||
.send(Event::Reaped {
|
||||
path: enc.path.unwrap_or_default(),
|
||||
bytes: enc.length.unwrap_or(0).max(0) as u64,
|
||||
dry_run: false,
|
||||
})
|
||||
.send(Event::Reaped { path: enc.path.unwrap_or_default(), bytes: enc.length.unwrap_or(0).max(0) as u64 })
|
||||
.ok();
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -3040,7 +2733,7 @@ async fn serve_media(state: WebState, id: i64, user: crate::db::User, req: Reque
|
||||
}
|
||||
r.into_response()
|
||||
}
|
||||
Err(e) => match e {},
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3107,8 +2800,6 @@ async fn art(State(state): State<WebState>, Query(q): Query<ArtQuery>) -> Respon
|
||||
let mut r = state.ctx.client.get(&q.u).timeout(crate::feed::FEED_TIMEOUT).send().await?.error_for_status()?;
|
||||
let said = r.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_owned();
|
||||
anyhow::ensure!(said.starts_with("image/") || untyped(&said), "not an image: {said}");
|
||||
// Said up front, refused up front: read chunk by chunk, each was 20 MB fetched to be thrown away (#448).
|
||||
anyhow::ensure!(r.content_length().is_none_or(|n| n <= MAX as u64), "larger than {MAX} bytes");
|
||||
let mut body = Vec::new();
|
||||
while let Some(c) = r.chunk().await? {
|
||||
body.extend_from_slice(&c);
|
||||
@@ -3135,25 +2826,12 @@ async fn art(State(state): State<WebState>, Query(q): Query<ArtQuery>) -> Respon
|
||||
let why = format!("{e:#}");
|
||||
// The access line says only that it failed, not which image or why (#169).
|
||||
tracing::warn!(url = %crate::feed::redact(&q.u), error = %crate::feed::redact_text(&why), "could not fetch artwork");
|
||||
crate::art::fail(&q.u, &why, lasting(&e));
|
||||
crate::art::fail(&q.u, &why);
|
||||
(StatusCode::BAD_GATEWAY, why).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an artwork fetch failed for a reason that will still hold tomorrow: refused by the
|
||||
/// publisher (a 4xx but a timeout or too many requests), or what ipx refuses (too large, not an
|
||||
/// image), which are its own errors and not reqwest's. A timeout, a 5xx or a dropped connection
|
||||
/// may be gone in an hour.
|
||||
fn lasting(e: &anyhow::Error) -> bool {
|
||||
match e.downcast_ref::<reqwest::Error>() {
|
||||
Some(re) => re.status().is_some_and(|s| {
|
||||
s.is_client_error() && s != StatusCode::REQUEST_TIMEOUT && s != StatusCode::TOO_MANY_REQUESTS
|
||||
}),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fetches of artwork under way, by address, each a lock the requests for it take in turn.
|
||||
static ART_FETCHES: std::sync::LazyLock<
|
||||
std::sync::Mutex<std::collections::HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
|
||||
@@ -3202,8 +2880,6 @@ fn image_kind(said: &str, body: &[u8]) -> Option<String> {
|
||||
[0x89, b'P', b'N', b'G', ..] => "image/png",
|
||||
[b'G', b'I', b'F', b'8', ..] => "image/gif",
|
||||
[b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => "image/webp",
|
||||
// JPEG XL, bare or in its box, which shkspr.mobi sends as octet-stream (#448); Safari shows it.
|
||||
[0xFF, 0x0A, ..] | [0, 0, 0, 0x0C, b'J', b'X', b'L', b' ', 0x0D, 0x0A, 0x87, 0x0A, ..] => "image/jxl",
|
||||
_ => return None,
|
||||
};
|
||||
Some(kind.to_owned())
|
||||
@@ -3291,9 +2967,6 @@ async fn read_all_mine(
|
||||
struct HowMany {
|
||||
#[serde(default = "five")]
|
||||
count: i64,
|
||||
/// One season, all of it, in place of the newest `count` (#482).
|
||||
#[serde(default)]
|
||||
season: Option<String>,
|
||||
}
|
||||
|
||||
fn five() -> i64 {
|
||||
@@ -3309,10 +2982,7 @@ async fn download_latest(
|
||||
Json(body): Json<HowMany>,
|
||||
) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
subscribed(&state, &user, &id).await?;
|
||||
let season = season_of(body.season.as_deref())?;
|
||||
// A whole season, Oxide and Friends' longest 47 episodes; past 300 it is no season.
|
||||
let most = if season == db::Season::Any { body.count.clamp(1, 100) } else { 300 };
|
||||
let ids = state.ctx.db.undownloaded(&id, season, most).await?;
|
||||
let ids = state.ctx.db.undownloaded(&id, body.count.clamp(1, 100)).await?;
|
||||
for enc in &ids {
|
||||
state.ctx.db.requeue(*enc).await?;
|
||||
state
|
||||
|
||||
@@ -12,15 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- `POST /v1/shares` takes and answers protobuf (`application/x-protobuf`) as well as JSON, chosen by `Content-Type` and `Accept`. The messages are in `crates/wire/proto/play.proto`, and answers go through structs generated from them (#465, #470).
|
||||
- A page for each shared episode, at `/e/<id>`: its show, title, date, length and notes, a player that plays the publisher's own file from the time it was shared at (`?t=754` or `?t=12:34`), buttons to subscribe in Apple Podcasts, Overcast, Pocket Casts or Castro, the feed's address, and a preview where the link is pasted (#447).
|
||||
- `POST /v1/shares`, for an ipx server with a token from `ipx-play token <name>`: an episode in, its short link out, the same link however often and from whichever server it is shared. An address that looks like a private or paid feed's is refused (#447).
|
||||
- Metrics for Prometheus on a port of its own, `metrics_bind`: requests by route and status and their time, episodes shared, memory (#458).
|
||||
|
||||
[unreleased]: https://git.sdf1.net/rays/ipx/commits/main/crates/play
|
||||
|
||||
### Security
|
||||
|
||||
- Built with SQLite 3.54 (libsqlite3-sys 0.40, through sqlx 0.9.1), past an advisory on opening a crafted database (RUSTSEC-2026-0459, #467), and url 2.5.9, which a web address nested thousands of times in `blob:` can no longer crash (RUSTSEC-2026-0592, #492).
|
||||
- An episode's notes are cleaned with ammonia 4.2.5, which no longer lets SVG or MathML in a feed's HTML carry script past it (RUSTSEC-2026-0533) (#467).
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ clap.workspace = true
|
||||
# log lines as ipx and the directory.
|
||||
ipx-directory.workspace = true
|
||||
ipx-feed.workspace = true
|
||||
ipx-wire.workspace = true
|
||||
opentelemetry.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
reqwest.workspace = true
|
||||
|
||||
@@ -15,10 +15,6 @@ pub struct Config {
|
||||
/// The environment variable holding the database URL, so the file holds no secret.
|
||||
#[serde(default = "default_database_url_env")]
|
||||
pub database_url_env: String,
|
||||
/// Where to serve /metrics for Prometheus (#458), apart from `bind`, which the tunnel
|
||||
/// publishes: `0.0.0.0:9191`. Empty serves none.
|
||||
#[serde(default)]
|
||||
pub metrics_bind: String,
|
||||
/// The address people open, which the links ipx is handed begin with.
|
||||
#[serde(default = "default_public_url")]
|
||||
pub public_url: String,
|
||||
|
||||
@@ -9,11 +9,10 @@
|
||||
//! its file is, nothing more.
|
||||
|
||||
pub mod config;
|
||||
pub mod metrics;
|
||||
mod page;
|
||||
pub mod store;
|
||||
|
||||
use axum::extract::{MatchedPath, Path, Query, Request, State};
|
||||
use axum::extract::{Path, Query, Request, State};
|
||||
use axum::http::{StatusCode, header};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
@@ -108,14 +107,10 @@ pub struct Play {
|
||||
|
||||
type St = Arc<Play>;
|
||||
|
||||
/// Each route's protobuf messages (#465), beside its JSON.
|
||||
const WIRE: ipx_wire::Routes = &[("POST", "/v1/shares", "play.Episode", "play.Shared")];
|
||||
|
||||
pub fn router(play: Play) -> Router {
|
||||
let st = Arc::new(play);
|
||||
let api = Router::new()
|
||||
.route("/v1/shares", post(share))
|
||||
.route_layer(axum::middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
|
||||
.layer(axum::middleware::from_fn_with_state(st.clone(), authenticate));
|
||||
Router::new()
|
||||
.route("/healthz", get(healthz))
|
||||
@@ -165,7 +160,6 @@ async fn share(State(st): State<St>, Extension(who): Extension<Who>, Json(mut e)
|
||||
}
|
||||
match st.store.put(&who.0, &e).await {
|
||||
Ok(id) => {
|
||||
metrics::SHARES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::info!(server = %who.0, id = %id, "an episode was shared");
|
||||
Json(Shared { url: format!("{}/e/{id}", st.base), id }).into_response()
|
||||
}
|
||||
@@ -204,9 +198,6 @@ async fn healthz(State(st): State<St>) -> Response {
|
||||
/// calls here; and a line, with the server's name and never its token.
|
||||
async fn access_log(req: Request, next: Next) -> Response {
|
||||
let (method, path) = (req.method().clone(), req.uri().path().to_owned());
|
||||
// By route, not path: by path each shared episode would be a row of its own. A path no route
|
||||
// has is "", which someone trying addresses cannot multiply.
|
||||
let route = req.extensions().get::<MatchedPath>().map_or("", |r| r.as_str()).to_owned();
|
||||
let start = Instant::now();
|
||||
let span = if path == "/healthz" {
|
||||
tracing::Span::none()
|
||||
@@ -227,14 +218,6 @@ async fn access_log(req: Request, next: Next) -> Response {
|
||||
let status = resp.status().as_u16();
|
||||
span.record("http.response.status_code", status);
|
||||
if path != "/healthz" {
|
||||
metrics::REQUESTS.observe(
|
||||
&format!(
|
||||
"method=\"{}\",route=\"{}\",status=\"{status}\"",
|
||||
ipx_directory::metrics::method(method.as_str()),
|
||||
ipx_directory::metrics::label(&route)
|
||||
),
|
||||
start.elapsed().as_secs_f64(),
|
||||
);
|
||||
let _in = span.enter();
|
||||
let who = resp.extensions().get::<Who>().map_or("", |w| w.0.as_str()).to_owned();
|
||||
tracing::info!(
|
||||
@@ -318,18 +301,6 @@ mod tests {
|
||||
assert!(!html.contains("javascript:"), "a link that is not a web address is dropped");
|
||||
|
||||
assert_eq!(get(&app, "/e/nothere").await.0, StatusCode::NOT_FOUND);
|
||||
get(&app, "/no/such/page").await;
|
||||
|
||||
let mut out = String::new();
|
||||
metrics::REQUESTS.render(&mut out, "r", "");
|
||||
for row in [
|
||||
r#"r_count{method="GET",route="/e/{id}",status="200"}"#,
|
||||
r#"r_count{method="POST",route="/v1/shares",status="200"}"#,
|
||||
r#"r_count{method="GET",route="",status="404"}"#,
|
||||
] {
|
||||
assert!(out.contains(row), "requests are counted by route, not path: {row} in {out}");
|
||||
}
|
||||
assert!(!out.contains("nothere") && !out.contains("/no/such"), "{out}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -98,13 +98,6 @@ async fn serve(path: &Path) -> Result<()> {
|
||||
.with_context(|| format!("{} is not set: ipx-play needs a database URL", cfg.database_url_env))?;
|
||||
let store = Store::open(&url, true).await.context("opening the database")?;
|
||||
let listener = TcpListener::bind(&cfg.bind).await.with_context(|| format!("listening on {}", cfg.bind))?;
|
||||
if !cfg.metrics_bind.is_empty() {
|
||||
let metrics = TcpListener::bind(&cfg.metrics_bind)
|
||||
.await
|
||||
.with_context(|| format!("listening for metrics on {}", cfg.metrics_bind))?;
|
||||
tracing::info!(bind = %cfg.metrics_bind, "serving metrics for Prometheus at /metrics");
|
||||
tokio::spawn(ipx_play::metrics::serve(metrics));
|
||||
}
|
||||
tracing::info!(version = env!("CARGO_PKG_VERSION"), bind = %cfg.bind, tokens = tokens.len(), "ipx-play started");
|
||||
let app = ipx_play::router(Play { store, tokens, base: cfg.base().to_owned() });
|
||||
axum::serve(listener, app)
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
//! ipx-play's /metrics (#458), in Prometheus's text format: memory, open files, the requests it
|
||||
//! answered and the episodes it was given to share. The histogram and /proc reading are the
|
||||
//! directory's, so the two read alike on the dashboard.
|
||||
|
||||
use axum::Router;
|
||||
use ipx_directory::metrics::{Histograms, SECONDS, process};
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
use std::time::Instant;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
/// Requests answered, by method, route and status: a page opened is `route="/e/{id}"`.
|
||||
pub static REQUESTS: Histograms = Histograms::new(SECONDS);
|
||||
/// Episodes an ipx server sent to be shared, the same one again included.
|
||||
pub static SHARES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Nothing from the database, so a scrape costs nothing and answers while it is down.
|
||||
fn render(started: Instant) -> String {
|
||||
let mut out = String::new();
|
||||
let mut gauge = |name: &str, kind: &str, help: &str, labels: &str, v: f64| {
|
||||
out.push_str(&format!("# HELP {name} {help}\n# TYPE {name} {kind}\n{name}{labels} {v}\n"));
|
||||
};
|
||||
let (rss, fds) = process();
|
||||
if let Some(v) = rss {
|
||||
gauge("play_process_resident_bytes", "gauge", "Memory the process holds.", "", v);
|
||||
}
|
||||
if let Some(v) = fds {
|
||||
gauge("play_process_open_fds", "gauge", "Files and sockets the process has open.", "", v);
|
||||
}
|
||||
gauge("play_uptime_seconds", "gauge", "Seconds since ipx-play started.", "", started.elapsed().as_secs() as f64);
|
||||
gauge(
|
||||
"play_build_info",
|
||||
"gauge",
|
||||
"The version running, as a label.",
|
||||
&format!("{{version=\"{}\"}}", env!("CARGO_PKG_VERSION")),
|
||||
1.0,
|
||||
);
|
||||
gauge("play_shares_total", "counter", "Episodes ipx servers sent to be shared.", "", SHARES.load(Relaxed) as f64);
|
||||
REQUESTS.render(
|
||||
&mut out,
|
||||
"play_http_request_duration_seconds",
|
||||
"Requests answered and the seconds each took, by method, route and status.",
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
/// Serves /metrics on a listener of its own: the public port is behind the tunnel with no Access
|
||||
/// in front, and these are for the LAN.
|
||||
// ponytail: no gzip, unlike the directory's (#253): a few dozen lines a scrape. Add tower-http's
|
||||
// CompressionLayer if the routes grow.
|
||||
pub async fn serve(listener: TcpListener) {
|
||||
let started = Instant::now();
|
||||
let app = Router::new().route(
|
||||
"/metrics",
|
||||
axum::routing::get(move || async move {
|
||||
([(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4")], render(started))
|
||||
}),
|
||||
);
|
||||
if let Err(e) = axum::serve(listener, app).await {
|
||||
tracing::error!(error = %e, "metrics stopped");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_play_metric_grafana_queries_is_served() {
|
||||
// A row for each name, so a histogram's lines are there to find.
|
||||
REQUESTS.observe("method=\"GET\",route=\"/e/{id}\",status=\"200\"", 0.01);
|
||||
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let at = l.local_addr().unwrap();
|
||||
tokio::spawn(serve(l));
|
||||
let text = reqwest::get(format!("http://{at}/metrics")).await.unwrap().text().await.unwrap();
|
||||
let src = [include_str!("../../../grafana/dashboard.py"), include_str!("../../../grafana/alerts.py")].concat();
|
||||
let names: std::collections::BTreeSet<&str> = src
|
||||
.match_indices("play_")
|
||||
.filter(|(i, _)| !src[..*i].ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_'))
|
||||
.filter_map(|(i, _)| {
|
||||
let rest = &src[i..];
|
||||
let end = rest.find(|c: char| !(c.is_ascii_lowercase() || c == '_')).unwrap_or(rest.len());
|
||||
// A query names one with its labels, or the dashboard keeps it in a string; ipx's
|
||||
// events, such as play_start in a panel's description, are neither.
|
||||
rest[end..].starts_with(['{', '"']).then(|| &rest[..end])
|
||||
})
|
||||
// A histogram is queried by its series' names and served under its own.
|
||||
.map(|n| n.trim_end_matches("_bucket").trim_end_matches("_count").trim_end_matches("_sum"))
|
||||
.collect();
|
||||
assert!(names.len() >= 3, "{names:?}");
|
||||
for n in names {
|
||||
// Memory comes from /proc, which a Mac has not.
|
||||
if n.starts_with("play_process_") && process().0.is_none() {
|
||||
continue;
|
||||
}
|
||||
assert!(text.contains(&format!("# TYPE {n} ")), "{n} is queried by grafana/ but not served: {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
[package]
|
||||
name = "ipx-wire"
|
||||
version = "0.0.0"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
prost.workspace = true
|
||||
prost-reflect.workspace = true
|
||||
prost-types.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
prost.workspace = true
|
||||
prost-build.workspace = true
|
||||
prost-types.workspace = true
|
||||
protox.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio.workspace = true
|
||||
tower.workspace = true
|
||||
@@ -1,47 +0,0 @@
|
||||
//! Compiles the `.proto` files into one descriptor set the crate reads at run time, and into Rust
|
||||
//! structs (prost) that read the handlers' JSON straight into protobuf (#470). protox is a
|
||||
//! compiler in Rust, so building needs no `protoc` on the host or in the image.
|
||||
|
||||
use prost::Message as _;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
fn main() {
|
||||
let files = ["proto/ipx.proto", "proto/directory.proto", "proto/play.proto"];
|
||||
for f in files {
|
||||
println!("cargo:rerun-if-changed={f}");
|
||||
}
|
||||
let set = protox::compile(files, ["proto"]).unwrap_or_else(|e| panic!("{e:?}"));
|
||||
let out = std::path::PathBuf::from(std::env::var("OUT_DIR").expect("cargo sets OUT_DIR"));
|
||||
std::fs::write(out.join("wire.bin"), set.encode_to_vec()).expect("writing the descriptor set");
|
||||
|
||||
// Every message that reads from JSON with serde: all but the bodies holding Google's Value or
|
||||
// ListValue, whose JSON serde cannot read; those go the slow way, through prost-reflect.
|
||||
let mut config = prost_build::Config::new();
|
||||
let mut fast = String::from(
|
||||
"/// An answer's JSON as message `name` in protobuf, when `name` has a struct here.\n\
|
||||
pub fn json_to_proto(name: &str, json: &[u8]) -> Option<Result<Vec<u8>, String>> {\n match name {\n",
|
||||
);
|
||||
for file in set.file.iter().filter(|f| f.package() != "google.protobuf") {
|
||||
for m in &file.message_type {
|
||||
if m.field.iter().any(|f| f.type_name().starts_with(".google.")) {
|
||||
continue;
|
||||
}
|
||||
let path = format!(".{}.{}", file.package(), m.name());
|
||||
// A list message is the JSON array itself.
|
||||
let list = matches!(&m.field[..], [only] if only.name() == "items"
|
||||
&& only.label() == prost_types::field_descriptor_proto::Label::Repeated);
|
||||
let attrs = if list {
|
||||
"#[derive(serde::Deserialize)] #[serde(transparent)]"
|
||||
} else {
|
||||
// Debug builds refuse a field the message lacks, as the slow way does.
|
||||
"#[derive(serde::Deserialize)] #[serde(default)] #[cfg_attr(debug_assertions, serde(deny_unknown_fields))]"
|
||||
};
|
||||
config.type_attribute(&path, attrs);
|
||||
writeln!(fast, " {:?} => Some(encode::<pb::{}::{}>(json)),", &path[1..], file.package(), m.name())
|
||||
.expect("writing to a String");
|
||||
}
|
||||
}
|
||||
fast.push_str(" _ => None,\n }\n}\n");
|
||||
std::fs::write(out.join("fast.rs"), fast).expect("writing fast.rs");
|
||||
config.out_dir(&out).compile_fds(set).unwrap_or_else(|e| panic!("{e:?}"));
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
// ipx-directory's API under /v1 (crates/directory/src/wire.rs), each message named after the Rust
|
||||
// struct it mirrors. A field added there goes here too; debug builds refuse an answer with a field
|
||||
// missing here. A message whose only field is `repeated items` is a JSON array.
|
||||
syntax = "proto3";
|
||||
package directory;
|
||||
|
||||
// GET /v1/me.
|
||||
message Me {
|
||||
string name = 1;
|
||||
// "ro", "rw" or "rwa".
|
||||
string access = 2;
|
||||
}
|
||||
|
||||
message Listing {
|
||||
string id = 1;
|
||||
string url = 2;
|
||||
optional string title = 3;
|
||||
optional string image = 4;
|
||||
optional string category = 5;
|
||||
optional string subcategory = 6;
|
||||
bool podcast = 7;
|
||||
int64 subscribers = 8;
|
||||
}
|
||||
|
||||
// GET /v1/feeds, GET /v1/popular.
|
||||
message Listings {
|
||||
repeated Listing items = 1;
|
||||
}
|
||||
|
||||
message Item {
|
||||
string guid = 1;
|
||||
optional string title = 2;
|
||||
optional string link = 3;
|
||||
optional int64 published = 4;
|
||||
optional int64 duration = 5;
|
||||
optional string description = 6;
|
||||
}
|
||||
|
||||
// GET /v1/feeds/{id}, POST /v1/feeds/{id}/refresh: a Listing's fields and these.
|
||||
message FeedPage {
|
||||
string id = 1;
|
||||
string url = 2;
|
||||
optional string title = 3;
|
||||
optional string image = 4;
|
||||
optional string category = 5;
|
||||
optional string subcategory = 6;
|
||||
bool podcast = 7;
|
||||
int64 subscribers = 8;
|
||||
optional string description = 9;
|
||||
optional string failing = 10;
|
||||
repeated Item items = 11;
|
||||
}
|
||||
|
||||
message SnapshotEntry {
|
||||
string url = 1;
|
||||
int64 subscribers = 2;
|
||||
optional string category = 3;
|
||||
}
|
||||
|
||||
// POST /v1/snapshot, the body.
|
||||
message Snapshot {
|
||||
repeated SnapshotEntry items = 1;
|
||||
}
|
||||
|
||||
// POST /v1/snapshot, the answer.
|
||||
message SnapshotResult {
|
||||
uint64 accepted = 1;
|
||||
uint64 refused_private = 2;
|
||||
uint64 refused_blocked = 3;
|
||||
uint64 refused_invalid = 4;
|
||||
}
|
||||
|
||||
message Instance {
|
||||
string name = 1;
|
||||
int64 feeds = 2;
|
||||
int64 subscribers = 3;
|
||||
}
|
||||
|
||||
// GET /v1/instances.
|
||||
message Instances {
|
||||
repeated Instance items = 1;
|
||||
}
|
||||
|
||||
message Blocked {
|
||||
string id = 1;
|
||||
optional string url = 2;
|
||||
optional string title = 3;
|
||||
int64 at = 4;
|
||||
}
|
||||
|
||||
// GET /v1/blocked.
|
||||
message BlockedList {
|
||||
repeated Blocked items = 1;
|
||||
}
|
||||
@@ -1,561 +0,0 @@
|
||||
// ipx's API under /api (crates/ipx/src/web.rs), the same answers its JSON gives, each message named
|
||||
// after the Rust struct it mirrors where there is one (web/src/types.ts mirrors the same). A field
|
||||
// added in Rust goes here too: debug builds refuse an answer with a field missing here.
|
||||
//
|
||||
// How the JSON maps (crates/wire/src/lib.rs):
|
||||
// * A field name is the JSON key.
|
||||
// * A Rust Option is `optional`, or a message; so is a field with a serde default, which an absent
|
||||
// field must leave to Rust.
|
||||
// * A message whose only field is `repeated ... items` is a JSON array, top-level or as a field.
|
||||
// An Option<Vec> in a body is one (Words), so leaving a list alone and emptying it differ.
|
||||
// * A body field that takes null to clear it is a google.protobuf.Value: absent leaves it, null
|
||||
// clears it, a value sets it.
|
||||
// * An answer of JSON null stays JSON null: the empty message would be a row of defaults.
|
||||
syntax = "proto3";
|
||||
package ipx;
|
||||
|
||||
import "google/protobuf/struct.proto";
|
||||
import "directory.proto";
|
||||
|
||||
// A list of words, as an Option<Vec<String>> in a body: absent, or this.
|
||||
message Words {
|
||||
repeated string items = 1;
|
||||
}
|
||||
|
||||
// ---- signing in, and you ----
|
||||
|
||||
// POST /api/login, the body.
|
||||
message Credentials {
|
||||
string name = 1;
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
// POST /api/login, the answer.
|
||||
message SignedIn {
|
||||
string name = 1;
|
||||
bool admin = 2;
|
||||
}
|
||||
|
||||
message Theme {
|
||||
string name = 1;
|
||||
string mode = 2;
|
||||
}
|
||||
|
||||
// GET /api/me.
|
||||
message Me {
|
||||
string name = 1;
|
||||
bool admin = 2;
|
||||
optional string sign_out = 3;
|
||||
repeated string blocked = 4;
|
||||
int64 deadair_saved = 5;
|
||||
optional Theme theme = 6;
|
||||
string version = 7;
|
||||
bool typesafe_key_set = 8;
|
||||
// "server" or "own".
|
||||
string signals = 9;
|
||||
uint64 signal_days = 10;
|
||||
}
|
||||
|
||||
// PATCH /api/me, the body.
|
||||
message MePatch {
|
||||
Words blocked = 1;
|
||||
google.protobuf.Value typesafe_key = 2;
|
||||
}
|
||||
|
||||
message ApiToken {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
int64 created = 3;
|
||||
optional int64 last_used = 4;
|
||||
}
|
||||
|
||||
// GET /api/tokens.
|
||||
message ApiTokens {
|
||||
repeated ApiToken items = 1;
|
||||
}
|
||||
|
||||
// POST /api/tokens, the body.
|
||||
message NewToken {
|
||||
string name = 1;
|
||||
}
|
||||
|
||||
// POST /api/tokens, the answer: the only time the token is shown.
|
||||
message MadeToken {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
string token = 3;
|
||||
}
|
||||
|
||||
// POST /api/push/devices, the body.
|
||||
message PushDevice {
|
||||
string token = 1;
|
||||
optional bool sandbox = 2;
|
||||
}
|
||||
|
||||
// ---- feeds ----
|
||||
|
||||
message FailingRow {
|
||||
string reason = 1;
|
||||
optional string new_url = 2;
|
||||
}
|
||||
|
||||
message FeedRow {
|
||||
string id = 1;
|
||||
string url = 2;
|
||||
optional string title = 3;
|
||||
optional string image = 4;
|
||||
optional string folder = 5;
|
||||
optional string category = 6;
|
||||
optional string feed_category = 7;
|
||||
repeated string keywords = 8;
|
||||
repeated string blocked = 9;
|
||||
bool deadair = 10;
|
||||
int64 deadair_pause = 11;
|
||||
bool allow_explicit = 12;
|
||||
bool auto_download = 13;
|
||||
optional uint64 max_new_per_check = 14;
|
||||
optional string group = 15;
|
||||
bool orphaned = 16;
|
||||
bool managed = 17;
|
||||
optional string schedule = 18;
|
||||
optional uint64 schedule_mins = 19;
|
||||
uint64 every_mins = 20;
|
||||
optional int64 last_checked = 21;
|
||||
optional int64 next_check = 22;
|
||||
optional string last_error = 23;
|
||||
optional FailingRow failing = 24;
|
||||
int64 entries = 25;
|
||||
int64 downloaded = 26;
|
||||
int64 unread = 27;
|
||||
int64 subscribers = 28;
|
||||
bool pinned = 29;
|
||||
bool kept = 30;
|
||||
bool hide_from_all = 31;
|
||||
bool hide_from_signals = 32;
|
||||
bool private = 33;
|
||||
bool private_by_address = 34;
|
||||
// Has an audio or video file: on the Podcasts shelf (#474).
|
||||
bool podcast = 35;
|
||||
}
|
||||
|
||||
// GET /api/feeds.
|
||||
message FeedRows {
|
||||
repeated FeedRow items = 1;
|
||||
}
|
||||
|
||||
// POST /api/feeds, the body.
|
||||
message NewFeed {
|
||||
string url = 1;
|
||||
optional string folder = 2;
|
||||
repeated string keywords = 3;
|
||||
optional bool allow_explicit = 4;
|
||||
}
|
||||
|
||||
// POST /api/feeds, the answer.
|
||||
message AddedFeed {
|
||||
string id = 1;
|
||||
bool existing = 2;
|
||||
}
|
||||
|
||||
// PATCH /api/feeds/{id}, the body: what is there changes, what is not is left.
|
||||
message FeedPatch {
|
||||
optional string url = 1;
|
||||
google.protobuf.Value schedule = 2;
|
||||
google.protobuf.Value folder = 3;
|
||||
google.protobuf.Value category = 4;
|
||||
Words keywords = 5;
|
||||
Words blocked = 6;
|
||||
optional bool allow_explicit = 7;
|
||||
optional bool auto_download = 8;
|
||||
google.protobuf.Value max_new_per_check = 9;
|
||||
optional bool pinned = 10;
|
||||
optional bool kept = 11;
|
||||
optional bool hide_from_all = 12;
|
||||
optional bool hide_from_signals = 13;
|
||||
google.protobuf.Value deadair = 14;
|
||||
optional int64 deadair_pause = 15;
|
||||
optional bool private = 16;
|
||||
}
|
||||
|
||||
// POST /api/feeds/{id}/download-latest, the body.
|
||||
message HowMany {
|
||||
optional int64 count = 1;
|
||||
// One season, all of it (#482): its number, or "none" for the episodes naming none.
|
||||
optional string season = 2;
|
||||
}
|
||||
|
||||
// POST /api/feeds/{id}/download-latest, the answer.
|
||||
message Queued {
|
||||
uint64 queued = 1;
|
||||
}
|
||||
|
||||
// POST /api/feeds/{id}/read-all, POST /api/read-all.
|
||||
message Marked {
|
||||
uint64 marked = 1;
|
||||
}
|
||||
|
||||
// POST /api/fetch, the body.
|
||||
message FetchBody {
|
||||
optional string feed = 1;
|
||||
optional bool force = 2;
|
||||
}
|
||||
|
||||
// POST /api/opml, the body.
|
||||
message OpmlBody {
|
||||
string xml = 1;
|
||||
}
|
||||
|
||||
// POST /api/opml, the answer.
|
||||
message OpmlImported {
|
||||
uint64 added = 1;
|
||||
uint64 already = 2;
|
||||
}
|
||||
|
||||
// ---- items ----
|
||||
|
||||
message EncRow {
|
||||
int64 id = 1;
|
||||
optional int64 deadair = 2;
|
||||
optional bool deadair_pending = 3;
|
||||
string feed_id = 4;
|
||||
string guid = 5;
|
||||
string url = 6;
|
||||
optional string mime = 7;
|
||||
optional int64 length = 8;
|
||||
optional string path = 9;
|
||||
string state = 10;
|
||||
optional string last_error = 11;
|
||||
}
|
||||
|
||||
// GET /api/entries/{feed_id}/{guid}.
|
||||
message EntryRow {
|
||||
string guid = 1;
|
||||
string feed_id = 2;
|
||||
optional string title = 3;
|
||||
optional string link = 4;
|
||||
optional int64 published = 5;
|
||||
optional string description = 6;
|
||||
optional string markdown = 7;
|
||||
optional string markdown_html = 8;
|
||||
bool read = 9;
|
||||
bool flagged = 10;
|
||||
optional string image = 11;
|
||||
optional int64 duration = 12;
|
||||
optional int64 episode = 13;
|
||||
optional int64 season = 14;
|
||||
int64 position = 15;
|
||||
repeated EncRow enclosures = 16;
|
||||
}
|
||||
|
||||
// GET /api/entries, /api/feeds/{id}/entries, /api/signals/{id}/entries.
|
||||
message EntryPage {
|
||||
int64 total = 1;
|
||||
repeated EntryRow entries = 2;
|
||||
}
|
||||
|
||||
// POST /api/playlists and PATCH /api/playlists/{id}, the body: a smart playlist (#476).
|
||||
message PlaylistSpec {
|
||||
string name = 1;
|
||||
repeated string feeds = 2;
|
||||
repeated string priority = 3;
|
||||
bool only_unplayed = 4;
|
||||
bool oldest_first = 5;
|
||||
}
|
||||
|
||||
// A playlist in GET /api/playlists, with how many episodes it holds now.
|
||||
message PlaylistRow {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
repeated string feeds = 3;
|
||||
repeated string priority = 4;
|
||||
bool only_unplayed = 5;
|
||||
bool oldest_first = 6;
|
||||
int64 items = 7;
|
||||
}
|
||||
|
||||
message PlaylistRows {
|
||||
repeated PlaylistRow items = 1;
|
||||
}
|
||||
|
||||
// One season of a podcast in GET /api/feeds/{id}/seasons (#482): its number, unset for the
|
||||
// episodes that name none, how many episodes it has and how many are unread.
|
||||
message SeasonRow {
|
||||
optional int64 season = 1;
|
||||
int64 episodes = 2;
|
||||
int64 unread = 3;
|
||||
}
|
||||
|
||||
message SeasonRows {
|
||||
repeated SeasonRow items = 1;
|
||||
}
|
||||
|
||||
// One chapter of a file in GET /api/enclosures/{id}/chapters (#477): its start in seconds, in
|
||||
// the clock of what plays, and its title, which may be empty.
|
||||
message Chapter {
|
||||
double start = 1;
|
||||
string title = 2;
|
||||
}
|
||||
|
||||
message Chapters {
|
||||
repeated Chapter items = 1;
|
||||
}
|
||||
|
||||
// POST /api/playlists, the answer.
|
||||
message PlaylistId {
|
||||
int64 id = 1;
|
||||
}
|
||||
|
||||
// One of Up Next's episodes (#473).
|
||||
message QueueItem {
|
||||
string feed_id = 1;
|
||||
string guid = 2;
|
||||
}
|
||||
|
||||
// PUT /api/queue, the body: Up Next in its new order. The answer is it as saved, an EntryPage.
|
||||
message QueueItems {
|
||||
repeated QueueItem items = 1;
|
||||
}
|
||||
|
||||
// POST /api/entries/{feed_id}/{guid}/flags, the body. The answer is the feed's FeedRow, or JSON
|
||||
// null when the feed is not yours.
|
||||
message Flags {
|
||||
optional bool read = 1;
|
||||
optional bool flagged = 2;
|
||||
}
|
||||
|
||||
// POST /api/entries/{feed_id}/{guid}/position, the body.
|
||||
message Position {
|
||||
int64 secs = 1;
|
||||
optional int64 duration = 2;
|
||||
optional int64 deadair = 3;
|
||||
}
|
||||
|
||||
// POST /api/entries/{feed_id}/{guid}/share, the body.
|
||||
message ShareBody {
|
||||
optional int64 enc = 1;
|
||||
}
|
||||
|
||||
// POST /api/entries/{feed_id}/{guid}/share, the answer.
|
||||
message ShareLink {
|
||||
optional string url = 1;
|
||||
optional string why = 2;
|
||||
}
|
||||
|
||||
// ---- Signals ----
|
||||
|
||||
message SignalRow {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
repeated string keywords = 3;
|
||||
optional string description = 4;
|
||||
optional string icon = 5;
|
||||
int64 items = 6;
|
||||
int64 unread = 7;
|
||||
}
|
||||
|
||||
// GET /api/signals.
|
||||
message SignalRows {
|
||||
repeated SignalRow items = 1;
|
||||
}
|
||||
|
||||
// POST /api/signals and PATCH /api/signals/{id}, the body.
|
||||
message SignalBody {
|
||||
optional string name = 1;
|
||||
Words keywords = 2;
|
||||
google.protobuf.Value description = 3;
|
||||
google.protobuf.Value icon = 4;
|
||||
}
|
||||
|
||||
// POST /api/signals, the answer.
|
||||
message SignalId {
|
||||
int64 id = 1;
|
||||
}
|
||||
|
||||
// POST /api/signals/icon, the body. Each candidate is [icon, label].
|
||||
message IconAsk {
|
||||
string name = 1;
|
||||
repeated string keywords = 2;
|
||||
optional string description = 3;
|
||||
repeated google.protobuf.ListValue candidates = 4;
|
||||
}
|
||||
|
||||
// POST /api/signals/icon, the answer.
|
||||
message Icon {
|
||||
string icon = 1;
|
||||
}
|
||||
|
||||
// ---- the directory ----
|
||||
|
||||
message PopularRow {
|
||||
string id = 1;
|
||||
optional string title = 2;
|
||||
optional string image = 3;
|
||||
int64 subscribers = 4;
|
||||
bool subscribed = 5;
|
||||
optional string feed = 6;
|
||||
optional string category = 7;
|
||||
optional string subcategory = 8;
|
||||
bool podcast = 9;
|
||||
}
|
||||
|
||||
// GET /api/popular, GET /api/directory.
|
||||
message PopularRows {
|
||||
repeated PopularRow items = 1;
|
||||
}
|
||||
|
||||
message ListedItem {
|
||||
string guid = 1;
|
||||
optional string title = 2;
|
||||
optional string link = 3;
|
||||
optional int64 published = 4;
|
||||
optional int64 duration = 5;
|
||||
optional string description = 6;
|
||||
}
|
||||
|
||||
// GET /api/directory/{id}.
|
||||
message Listed {
|
||||
optional string description = 1;
|
||||
optional string failing = 2;
|
||||
repeated ListedItem items = 3;
|
||||
bool can_admin = 4;
|
||||
}
|
||||
|
||||
// POST /api/popular/{id}, the answer.
|
||||
message FeedId {
|
||||
string id = 1;
|
||||
}
|
||||
|
||||
message BlockedRow {
|
||||
string id = 1;
|
||||
optional string title = 2;
|
||||
int64 at = 3;
|
||||
}
|
||||
|
||||
// GET /api/directory-admin.
|
||||
message DirAdmin {
|
||||
repeated directory.Instance instances = 1;
|
||||
repeated BlockedRow blocked = 2;
|
||||
}
|
||||
|
||||
// When the snapshot last went: a SnapshotResult's fields when it was taken, the error when not.
|
||||
message Shared {
|
||||
int64 at = 1;
|
||||
optional uint64 accepted = 2;
|
||||
optional uint64 refused_private = 3;
|
||||
optional uint64 refused_blocked = 4;
|
||||
optional uint64 refused_invalid = 5;
|
||||
optional string error = 6;
|
||||
}
|
||||
|
||||
// GET /api/directory-status.
|
||||
message DirStatus {
|
||||
bool configured = 1;
|
||||
optional string name = 2;
|
||||
optional string access = 3;
|
||||
optional string error = 4;
|
||||
optional Shared shared = 5;
|
||||
}
|
||||
|
||||
// ---- the server ----
|
||||
|
||||
// GET /api/status.
|
||||
message Status {
|
||||
uint64 feeds = 1;
|
||||
int64 pending = 2;
|
||||
int64 downloaded = 3;
|
||||
string version = 4;
|
||||
}
|
||||
|
||||
// GET /api/settings.
|
||||
message Settings {
|
||||
string schedule = 1;
|
||||
uint64 every_mins = 2;
|
||||
uint64 max_new_per_check = 3;
|
||||
repeated string media_types = 4;
|
||||
string download_dir = 5;
|
||||
double max_total_gb = 6;
|
||||
uint64 max_age_days = 7;
|
||||
uint64 art_cache_mb = 8;
|
||||
string directory_url = 9;
|
||||
bool directory_token_set = 10;
|
||||
bool directory_share = 11;
|
||||
string play_url = 12;
|
||||
bool play_token_set = 13;
|
||||
bool signals_on_server = 14;
|
||||
uint64 signal_days = 15;
|
||||
bool typesafe_server_key = 16;
|
||||
}
|
||||
|
||||
// PATCH /api/settings, the body.
|
||||
message SettingsPatch {
|
||||
optional string schedule = 1;
|
||||
optional uint64 max_new_per_check = 2;
|
||||
Words media_types = 3;
|
||||
optional double max_total_gb = 4;
|
||||
optional uint64 max_age_days = 5;
|
||||
optional uint64 art_cache_mb = 6;
|
||||
optional string directory_url = 7;
|
||||
optional string directory_token = 8;
|
||||
optional bool directory_share = 9;
|
||||
optional string play_url = 10;
|
||||
optional string play_token = 11;
|
||||
optional bool signals_on_server = 12;
|
||||
optional uint64 signal_days = 13;
|
||||
}
|
||||
|
||||
message Account {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
bool admin = 3;
|
||||
bool password = 4;
|
||||
optional int64 created = 5;
|
||||
optional int64 last_login = 6;
|
||||
}
|
||||
|
||||
// GET /api/users.
|
||||
message Accounts {
|
||||
repeated Account items = 1;
|
||||
}
|
||||
|
||||
// POST /api/users, the body.
|
||||
message NewUser {
|
||||
string name = 1;
|
||||
optional string password = 2;
|
||||
optional bool admin = 3;
|
||||
}
|
||||
|
||||
// PATCH /api/users/{id}, the body.
|
||||
message UserPatch {
|
||||
bool admin = 1;
|
||||
}
|
||||
|
||||
message LogLine {
|
||||
uint64 seq = 1;
|
||||
int64 ts = 2;
|
||||
string level = 3;
|
||||
string target = 4;
|
||||
string msg = 5;
|
||||
}
|
||||
|
||||
// GET /api/logs.
|
||||
message LogPage {
|
||||
repeated LogLine lines = 1;
|
||||
uint64 latest = 2;
|
||||
}
|
||||
|
||||
// POST /api/client, the body.
|
||||
message ClientEvent {
|
||||
string ev = 1;
|
||||
optional string msg = 2;
|
||||
optional string src = 3;
|
||||
optional uint32 line = 4;
|
||||
optional string feed = 5;
|
||||
optional int64 enclosure = 6;
|
||||
optional bool deadair = 7;
|
||||
optional uint64 ms = 8;
|
||||
optional string filter = 9;
|
||||
optional string trace = 10;
|
||||
optional string span = 11;
|
||||
optional uint64 start = 12;
|
||||
optional string state = 13;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// ipx-play's API (crates/play/src/lib.rs), each message named after the Rust struct it mirrors.
|
||||
// A field added there goes here too; debug builds refuse an answer with a field missing here.
|
||||
syntax = "proto3";
|
||||
package play;
|
||||
|
||||
// POST /v1/shares, the body.
|
||||
message Episode {
|
||||
string feed_url = 1;
|
||||
string guid = 2;
|
||||
optional string feed_title = 3;
|
||||
optional string feed_image = 4;
|
||||
optional string title = 5;
|
||||
optional string description = 6;
|
||||
optional string link = 7;
|
||||
optional int64 published = 8;
|
||||
optional int64 duration = 9;
|
||||
string audio_url = 10;
|
||||
optional string mime = 11;
|
||||
}
|
||||
|
||||
// POST /v1/shares, the answer.
|
||||
message Shared {
|
||||
string id = 1;
|
||||
string url = 2;
|
||||
}
|
||||
@@ -1,345 +0,0 @@
|
||||
//! Protobuf beside JSON (#465). The handlers speak JSON, as they always have; a route's
|
||||
//! messages in `proto/` say what the same answer is in protobuf, and `negotiate` converts at the
|
||||
//! edge: a request body sent as `application/x-protobuf` becomes the JSON the handler reads, and
|
||||
//! an answer becomes protobuf for a client whose `Accept` asks for it. Anyone not asking gets JSON
|
||||
//! exactly as before.
|
||||
//!
|
||||
//! How a message stands for JSON is said at the top of `proto/ipx.proto`: names as in JSON, an
|
||||
//! Option `optional`, a message of only `repeated items` an array, null-to-clear a
|
||||
//! `google.protobuf.Value`.
|
||||
//!
|
||||
//! Debug builds convert every JSON answer of a route in the table, asked for or not, refusing
|
||||
//! fields the message lacks, and answer 500 when a route has no message: the cargo tests and the
|
||||
//! browser suite, which run debug builds, then fail on a field added in Rust and not in `proto/`.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use axum::body::{Body, to_bytes};
|
||||
use axum::extract::{MatchedPath, Request, State};
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use prost_reflect::{DescriptorPool, DeserializeOptions, DynamicMessage, Kind, MessageDescriptor, SerializeOptions};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
pub const PROTOBUF: &str = "application/x-protobuf";
|
||||
|
||||
/// For a client to encode and decode the structs in `pb` without naming prost itself.
|
||||
pub use prost::Message;
|
||||
|
||||
/// The messages as Rust structs, which the answers go into from their JSON and which a client
|
||||
/// in Rust reads and writes (#470): prost's own encoding, several times faster than going through
|
||||
/// the descriptors at run time.
|
||||
#[allow(clippy::all, clippy::pedantic, missing_docs)]
|
||||
pub mod pb {
|
||||
pub mod directory {
|
||||
include!(concat!(env!("OUT_DIR"), "/directory.rs"));
|
||||
}
|
||||
pub mod ipx {
|
||||
include!(concat!(env!("OUT_DIR"), "/ipx.rs"));
|
||||
}
|
||||
pub mod play {
|
||||
include!(concat!(env!("OUT_DIR"), "/play.rs"));
|
||||
}
|
||||
}
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/fast.rs"));
|
||||
|
||||
/// The JSON an answer was into its struct, and that into protobuf.
|
||||
fn encode<T: DeserializeOwned + prost::Message>(json: &[u8]) -> Result<Vec<u8>, String> {
|
||||
Ok(serde_json::from_slice::<T>(json).map_err(|e| e.to_string())?.encode_to_vec())
|
||||
}
|
||||
|
||||
/// The most read of a body either way: axum's own limit for `Json`.
|
||||
const LIMIT: usize = 2 << 20;
|
||||
|
||||
static POOL: LazyLock<DescriptorPool> = LazyLock::new(|| {
|
||||
DescriptorPool::decode(include_bytes!(concat!(env!("OUT_DIR"), "/wire.bin")).as_slice())
|
||||
.expect("build.rs wrote a valid descriptor set")
|
||||
});
|
||||
|
||||
/// Each route's method, its path as the router has it, the message its body is and the message
|
||||
/// it answers, by full name; "" where it takes or answers no JSON.
|
||||
pub type Routes = &'static [(&'static str, &'static str, &'static str, &'static str)];
|
||||
|
||||
/// A message by full name (`ipx.Feed`).
|
||||
pub fn message(name: &str) -> Option<MessageDescriptor> {
|
||||
POOL.get_message_by_name(name)
|
||||
}
|
||||
|
||||
fn is_list(d: &MessageDescriptor) -> bool {
|
||||
let mut f = d.fields();
|
||||
matches!((f.next(), f.next()), (Some(only), None) if only.name() == "items" && only.is_list())
|
||||
}
|
||||
|
||||
/// Each message field of `d` in `v`, with its descriptor, for `wrap` and `unwrap` to go down.
|
||||
/// Not maps, and not Google's own types, whose JSON is theirs.
|
||||
fn children<'a>(d: &MessageDescriptor, v: &'a mut Value) -> Vec<(MessageDescriptor, &'a mut Value)> {
|
||||
let Some(obj) = v.as_object_mut() else { return vec![] };
|
||||
let mut out = Vec::new();
|
||||
for (key, val) in obj.iter_mut() {
|
||||
let Some(f) = d.get_field_by_name(key) else { continue };
|
||||
let Kind::Message(m) = f.kind() else { continue };
|
||||
if f.is_map() || m.package_name() == "google.protobuf" {
|
||||
continue;
|
||||
}
|
||||
if f.is_list() {
|
||||
out.extend(val.as_array_mut().into_iter().flatten().map(|i| (m.clone(), i)));
|
||||
} else {
|
||||
out.push((m, val));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON array where a list message is, made that message.
|
||||
fn wrap(d: &MessageDescriptor, v: &mut Value) {
|
||||
if v.is_array() && is_list(d) {
|
||||
*v = serde_json::json!({ "items": v.take() });
|
||||
}
|
||||
for (m, c) in children(d, v) {
|
||||
wrap(&m, c);
|
||||
}
|
||||
}
|
||||
|
||||
/// A list message made the array it stands for; none sent is an empty one.
|
||||
fn unwrap(d: &MessageDescriptor, v: &mut Value) {
|
||||
for (m, c) in children(d, v) {
|
||||
unwrap(&m, c);
|
||||
}
|
||||
if is_list(d) {
|
||||
*v = match v["items"].take() {
|
||||
Value::Null => Value::Array(vec![]),
|
||||
items => items,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON to protobuf. `strict` refuses a field the message does not have, where otherwise it is
|
||||
/// left out, as a newer server's field is for an older client. JSON null is the empty message.
|
||||
pub fn to_proto(d: &MessageDescriptor, mut v: Value, strict: bool) -> Result<Vec<u8>, String> {
|
||||
if v.is_null() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
wrap(d, &mut v);
|
||||
let opts = DeserializeOptions::new().deny_unknown_fields(strict);
|
||||
let msg =
|
||||
DynamicMessage::deserialize_with_options(d.clone(), v, &opts).map_err(|e| format!("{}: {e}", d.full_name()))?;
|
||||
Ok(msg.encode_to_vec())
|
||||
}
|
||||
|
||||
/// Protobuf to the JSON the same struct reads: field names as written, 64-bit numbers as numbers,
|
||||
/// a field without presence always, so a default value reads as itself, and an `optional` or a
|
||||
/// message only when sent, so an absent one reads as None.
|
||||
pub fn from_proto(d: &MessageDescriptor, bytes: &[u8]) -> Result<Value, String> {
|
||||
let msg = DynamicMessage::decode(d.clone(), bytes).map_err(|e| format!("{}: {e}", d.full_name()))?;
|
||||
let opts =
|
||||
SerializeOptions::new().use_proto_field_name(true).stringify_64_bit_integers(false).skip_default_fields(false);
|
||||
let mut v = msg.serialize_with_options(serde_json::value::Serializer, &opts).map_err(|e| e.to_string())?;
|
||||
unwrap(d, &mut v);
|
||||
whole(&mut v);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// A whole number as an integer: a google.protobuf.Value holds every number as a double, and
|
||||
/// `3.0` does not read as a usize where `3` reads as an f64 too.
|
||||
fn whole(v: &mut Value) {
|
||||
match v {
|
||||
Value::Number(n) => {
|
||||
if let Some(f) = n.as_f64().filter(|f| n.is_f64() && f.fract() == 0.0 && f.abs() < 9e15) {
|
||||
*v = Value::from(f as i64);
|
||||
}
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(whole),
|
||||
Value::Object(o) => o.values_mut().for_each(whole),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn is(headers: &HeaderMap, name: header::HeaderName, mime: &str) -> bool {
|
||||
// shortcut: a substring, not a parsed Accept, so `q=0` still counts; parse it if a client sends one.
|
||||
headers.get(name).and_then(|v| v.to_str().ok()).is_some_and(|v| v.contains(mime))
|
||||
}
|
||||
|
||||
fn refuse(code: StatusCode, msg: String) -> Response {
|
||||
(code, axum::Json(serde_json::json!({ "error": msg }))).into_response()
|
||||
}
|
||||
|
||||
/// The layer, as `route_layer(from_fn_with_state(ROUTES, ipx_wire::negotiate))`, inside any
|
||||
/// request decompression so it reads the body unpacked.
|
||||
pub async fn negotiate(State(routes): State<Routes>, path: MatchedPath, req: Request, next: Next) -> Response {
|
||||
let method = req.method().as_str().to_owned();
|
||||
let (takes, answers) =
|
||||
routes.iter().find(|r| r.0 == method && r.1 == path.as_str()).map(|r| (r.2, r.3)).unwrap_or(("", ""));
|
||||
|
||||
let req = if is(req.headers(), header::CONTENT_TYPE, PROTOBUF) {
|
||||
let Some(d) = message(takes) else {
|
||||
return refuse(StatusCode::UNSUPPORTED_MEDIA_TYPE, format!("{method} {} takes no protobuf", path.as_str()));
|
||||
};
|
||||
let (mut parts, body) = req.into_parts();
|
||||
let Ok(bytes) = to_bytes(body, LIMIT).await else {
|
||||
return refuse(StatusCode::PAYLOAD_TOO_LARGE, "the body is too large".into());
|
||||
};
|
||||
let json = match from_proto(&d, &bytes) {
|
||||
Ok(v) => v.to_string(),
|
||||
Err(e) => return refuse(StatusCode::BAD_REQUEST, format!("the body did not read as {e}")),
|
||||
};
|
||||
parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
parts.headers.remove(header::CONTENT_LENGTH);
|
||||
Request::from_parts(parts, Body::from(json))
|
||||
} else {
|
||||
req
|
||||
};
|
||||
|
||||
let wants = is(req.headers(), header::ACCEPT, PROTOBUF);
|
||||
let mut resp = next.run(req).await;
|
||||
if !answers.is_empty() {
|
||||
resp.headers_mut().append(header::VARY, HeaderValue::from_static("accept"));
|
||||
}
|
||||
let json = resp.status().is_success() && is(resp.headers(), header::CONTENT_TYPE, "application/json");
|
||||
if !json || !(wants || cfg!(debug_assertions)) {
|
||||
return resp;
|
||||
}
|
||||
let Some(d) = message(answers) else {
|
||||
if cfg!(debug_assertions) {
|
||||
return refuse(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("{method} {} answers JSON with no message for it in ipx-wire", path.as_str()),
|
||||
);
|
||||
}
|
||||
return resp;
|
||||
};
|
||||
let (mut parts, body) = resp.into_parts();
|
||||
let Ok(bytes) = to_bytes(body, usize::MAX).await else {
|
||||
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
|
||||
};
|
||||
// None stays JSON null: as protobuf it would be the empty message, which is also every field
|
||||
// at its default, and a client could not tell "no feed row" from a blank one.
|
||||
if bytes.trim_ascii() == b"null" {
|
||||
return Response::from_parts(parts, Body::from(bytes));
|
||||
}
|
||||
let converted = json_to_proto(answers, &bytes).unwrap_or_else(|| {
|
||||
serde_json::from_slice(&bytes).map_err(|e| e.to_string()).and_then(|v| to_proto(&d, v, cfg!(debug_assertions)))
|
||||
});
|
||||
match converted {
|
||||
Ok(pb) if wants => {
|
||||
// Which message it is, for a client with no table of routes (the page).
|
||||
let ct = format!("{PROTOBUF}; messageType={answers}");
|
||||
parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_str(&ct).expect("a message name is ASCII"));
|
||||
parts.headers.remove(header::CONTENT_LENGTH);
|
||||
Response::from_parts(parts, Body::from(pb))
|
||||
}
|
||||
Err(e) if cfg!(debug_assertions) => refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("not as protobuf: {e}")),
|
||||
// Asked for protobuf and it would not convert: the JSON, which says what it is.
|
||||
Err(e) => {
|
||||
tracing::warn!(route = path.as_str(), error = %e, "answer did not convert to protobuf");
|
||||
Response::from_parts(parts, Body::from(bytes))
|
||||
}
|
||||
Ok(_) => Response::from_parts(parts, Body::from(bytes)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::routing::post;
|
||||
use serde_json::json;
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
fn round(name: &str, v: Value) -> Value {
|
||||
let d = message(name).unwrap();
|
||||
from_proto(&d, &to_proto(&d, v, true).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_message_named_in_a_table_exists() {
|
||||
// The tables live in the services; these are the names that would break a client first.
|
||||
for m in ["ipx.FeedRows", "ipx.EntryPage", "ipx.Me", "ipx.Position", "directory.Snapshot", "play.Shared"] {
|
||||
assert!(message(m).is_some(), "{m}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_and_lists_come_back_as_they_went() {
|
||||
let ep = json!({ "feed_url": "https://a/f", "guid": "g", "title": "T", "published": 1_700_000_000_000_i64,
|
||||
"audio_url": "https://a/1.mp3" });
|
||||
let back = round("play.Episode", ep.clone());
|
||||
assert_eq!(back, ep, "absent optionals stay absent, 64-bit numbers stay numbers");
|
||||
|
||||
let rows = json!([{ "id": "a", "url": "u", "subscribers": 2, "podcast": true }]);
|
||||
let back = round("directory.Listings", rows);
|
||||
assert_eq!(back[0]["id"], "a");
|
||||
assert_eq!(back[0]["subscribers"], 2);
|
||||
assert_eq!(round("directory.Listings", json!([])), json!([]), "an empty list is an empty array");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_patch_tells_absent_from_empty_and_from_null() {
|
||||
assert_eq!(round("ipx.MePatch", json!({})), json!({}), "nothing sent changes nothing");
|
||||
assert_eq!(round("ipx.MePatch", json!({ "blocked": [] })), json!({ "blocked": [] }), "emptied");
|
||||
assert_eq!(round("ipx.MePatch", json!({ "typesafe_key": null })), json!({ "typesafe_key": null }), "cleared");
|
||||
assert_eq!(
|
||||
round("ipx.FeedPatch", json!({ "max_new_per_check": 3, "pinned": false })),
|
||||
json!({
|
||||
"max_new_per_check": 3, "pinned": false })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_structs_encode_as_the_descriptors_do() {
|
||||
let feeds = json!([{ "id": "a", "url": "u", "title": null, "keywords": ["k"], "every_mins": 60,
|
||||
"failing": { "reason": "gone", "new_url": null }, "subscribers": 2, "private": true }]);
|
||||
let slow = to_proto(&message("ipx.FeedRows").unwrap(), feeds.clone(), false).unwrap();
|
||||
let fast = json_to_proto("ipx.FeedRows", feeds.to_string().as_bytes()).unwrap().unwrap();
|
||||
assert_eq!(fast, slow);
|
||||
assert!(json_to_proto("ipx.FeedPatch", b"{}").is_none(), "a body with a Value goes the slow way");
|
||||
if cfg!(debug_assertions) {
|
||||
assert!(json_to_proto("play.Shared", br#"{"id":"x","url":"u","new":1}"#).unwrap().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_refuses_a_field_the_message_lacks() {
|
||||
let d = message("play.Shared").unwrap();
|
||||
assert!(to_proto(&d, json!({ "id": "x", "url": "u", "new": 1 }), true).is_err());
|
||||
assert!(to_proto(&d, json!({ "id": "x", "url": "u", "new": 1 }), false).is_ok());
|
||||
assert_eq!(to_proto(&message("ipx.FeedRow").unwrap(), Value::Null, true).unwrap(), Vec::<u8>::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_layer_converts_only_for_who_asks() {
|
||||
const ROUTES: Routes = &[("POST", "/v1/shares", "play.Episode", "play.Shared")];
|
||||
let app =
|
||||
axum::Router::new()
|
||||
.route(
|
||||
"/v1/shares",
|
||||
post(|axum::Json(e): axum::Json<Value>| async move {
|
||||
axum::Json(json!({ "id": e["guid"], "url": "u" }))
|
||||
}),
|
||||
)
|
||||
.route_layer(axum::middleware::from_fn_with_state(ROUTES, negotiate));
|
||||
let ep =
|
||||
pb::play::Episode { feed_url: "f".into(), guid: "g1".into(), audio_url: "a".into(), ..Default::default() };
|
||||
let body = ep.encode_to_vec();
|
||||
let ask = |accept: &'static str| {
|
||||
Request::post("/v1/shares")
|
||||
.header(header::CONTENT_TYPE, PROTOBUF)
|
||||
.header(header::ACCEPT, accept)
|
||||
.body(Body::from(body.clone()))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let resp = app.clone().oneshot(ask(PROTOBUF)).await.unwrap();
|
||||
assert_eq!(resp.headers()[header::CONTENT_TYPE], "application/x-protobuf; messageType=play.Shared");
|
||||
let got = pb::play::Shared::decode(to_bytes(resp.into_body(), LIMIT).await.unwrap()).unwrap();
|
||||
assert_eq!((got.id.as_str(), got.url.as_str()), ("g1", "u"));
|
||||
|
||||
let resp = app.clone().oneshot(ask("application/json")).await.unwrap();
|
||||
assert_eq!(resp.headers()[header::CONTENT_TYPE], "application/json");
|
||||
|
||||
let bad =
|
||||
Request::post("/v1/shares").header(header::CONTENT_TYPE, PROTOBUF).body(Body::from("\u{ff}")).unwrap();
|
||||
assert_eq!(app.oneshot(bad).await.unwrap().status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@ targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[advisories]
|
||||
ignore = [
|
||||
# chrono is unmaintained, every version, and no vulnerability is known. rss and atom_syndication
|
||||
# depend on it, so ipx's own code moving off it would not take it out (#493).
|
||||
{ id = "RUSTSEC-2026-0543", reason = "unmaintained, not vulnerable; the feed parsers depend on it (#493)" },
|
||||
# ringbuf 0.4's double free needs an element whose Drop panics; librqbit-utp's buffer holds
|
||||
# only u8, which has no Drop. Its fix is ringbuf 0.5, which librqbit 9.0.1 cannot take (#281).
|
||||
{ id = "RUSTSEC-2026-0293", reason = "librqbit-utp's ring buffer holds u8: no Drop to panic" },
|
||||
]
|
||||
|
||||
[licenses]
|
||||
|
||||
@@ -16,6 +16,9 @@ services:
|
||||
# For Postgres instead of SQLite:
|
||||
# IPX_DATABASE_URL: "postgres://ipx:password@db-host:5432/ipx"
|
||||
# No web port of its own: ipx-web is the way in, and passes the API on to it.
|
||||
ports:
|
||||
- "6881:6881/tcp" # BitTorrent peers
|
||||
- "6881:6881/udp" # DHT
|
||||
volumes:
|
||||
- ./config:/config # config.toml, written on first start
|
||||
- ./data:/data # state.db
|
||||
|
||||
@@ -1,369 +0,0 @@
|
||||
# The iPX style guide
|
||||
|
||||
How iPX looks, behaves and reads: the page (`web/`), the admin page, sign-in, the iOS app's own
|
||||
alerts (`ios/`) and the directory's and ipx-play's pages. The first half is design: principles,
|
||||
layout, controls, dialogs, keyboard, feedback, safety and accessibility. The second half is
|
||||
writing: every string a person sees.
|
||||
|
||||
iPX is a web page in English, used with a mouse and keyboard in a desktop browser, by touch on a
|
||||
phone's home screen, and inside the iOS app, by people who run their own server or were given an
|
||||
account on one. They know what a podcast and a feed are; they do not know what a guid, a scan job
|
||||
or a 304 is. Where a browser or iOS has a convention of its own, it wins over this guide.
|
||||
|
||||
The rules were chosen against forty years of interface guides (Apple 1987-2014, Windows 1995 and
|
||||
2010, NeXTSTEP, GNOME, KDE, Android and others); the reasons for the disputed ones are in the two
|
||||
decision logs.
|
||||
|
||||
# Design
|
||||
|
||||
## Principles
|
||||
|
||||
| Principle | For iPX | ✅ | ❌ |
|
||||
|---|---|---|---|
|
||||
| The person is in control | iPX acts on its own only where it was asked to (downloads by a feed's settings, checks on the schedule), and each can be turned off | A feed downloads its newest five because its settings say so | Marking an item read because it scrolled past |
|
||||
| See and point | Every action is on screen somewhere; a key or a swipe is a quicker way to it, never the only one | On a phone a swipe goes to the next item; so do the reader's arrow and `j` | An action only on a long-press |
|
||||
| Consistency | The same thing looks and works the same on every screen, on a phone and a desktop, as it did in the last release | Every dialog has Cancel on the left and its action on the right | A Save at the top of one dialog and the bottom of the next |
|
||||
| Stability | Things stay where they were: the list keeps its place, a dialog closes back to the control that opened it, a reader keeps its scroll when it redraws | A button that cannot act now is dimmed in place | A toolbar whose buttons come and go with the selection |
|
||||
| Feedback | Every action shows a result where it happened, within a tenth of a second | The row's dot empties as it is marked read | A spinner in the corner for a change to one row |
|
||||
| Forgiveness | What can be taken back is taken back easily; what cannot is asked about first | Unsubscribe asks, and says what goes | Delete a file at one tap |
|
||||
| Accessible from the start | A screen reader, a keyboard alone, zoom, reduced motion and high contrast all work, in every theme | An icon button with a tooltip and a matching `aria-label` | An icon button with only its icon |
|
||||
|
||||
## Layout and visual system
|
||||
|
||||
**Two layouts, one breakpoint.** Wider than 820 px: the feed list, the item list and the reader
|
||||
side by side. 820 px or narrower: one column, the feed list as a drawer, the reader as a sheet. No
|
||||
third layout for a tablet; a breakpoint is added only with a test that fails without it. (The
|
||||
admin page wraps its tabs at 600 px, its one exception.)
|
||||
|
||||
**Spacing** comes from one scale: 2, 4, 6, 8, 10, 12, 14 px, the gaps the stylesheet already uses.
|
||||
✅ `gap:8px` · ❌ `gap:9px`. Within a group the smaller steps, between groups the larger.
|
||||
|
||||
**Corners**: 6-10 px on controls and rows, 14 px on cards and sheets, round (`999px`) on pills and
|
||||
chips, `50%` on round buttons and art. Not a new radius for one component.
|
||||
|
||||
**Type**: 13 px is the body of the interface; 11-12.5 px for secondary lines (dates, counts), 14-17
|
||||
px for headings and the reader's text, 26 px only for a sheet's title. The fonts are the person's
|
||||
choice in Settings (interface and reading separately), so a component never names a font: it uses
|
||||
`--f-*` through the theme. Numbers that are compared (times, counts, sizes) use tabular figures and
|
||||
line up on the right.
|
||||
|
||||
**Colour** is by role, never by value: `--bg`, `--panel`, `--panel2`, `--raise` for surfaces;
|
||||
`--fg`, `--dim`, `--faint` for text by importance; `--accent`, `--accent2` for the selection and
|
||||
the primary action; `--good`, `--warn`, `--bad` for state; `--line` for rules. ✅
|
||||
`color:var(--bad)` · ❌ `color:#d33`. Every palette defines every role, and
|
||||
`node tests/contrast.ts` checks each against WCAG AA; a new role needs a value in every palette and a
|
||||
contrast check. Working on a component never changes a theme's colours.
|
||||
|
||||
**Colour is never the only signal.** An unread item has its dot and its weight; a failing feed has
|
||||
its icon and its label; a pressed toggle has its shape and `aria-pressed`. ✅ the pin's outline
|
||||
fills in · ❌ the pin turns green.
|
||||
|
||||
**Icons** are Font Awesome Free, embedded as SVG through `ICON`, only those used; nothing is
|
||||
fetched from another site. One icon means one thing everywhere: the plus adds, the check saves,
|
||||
the cross cancels or closes. An icon that toggles changes shape (pin, pin-on), not colour.
|
||||
|
||||
**Touch targets** are at least 44 by 44 px on a phone, 40 px where a row is dense, as the player's
|
||||
and toolbar's buttons are. Hover effects sit inside `@media (hover:hover)`, so a phone never keeps
|
||||
one stuck after a tap.
|
||||
|
||||
**The phone's edges**: the page is `viewport-fit=cover` and pads itself by the safe-area insets
|
||||
(`--safe-*`), on the home screen and in the app alike.
|
||||
|
||||
## Controls
|
||||
|
||||
| Control | Use for | Not for |
|
||||
|---|---|---|
|
||||
| Button | An action now | A setting that stays: that is a toggle or a select |
|
||||
| Icon button | A frequent action whose icon is unambiguous: play, close, add, delete | Anything needing a word to tell it apart; give it a label |
|
||||
| Toggle button (`aria-pressed`) | A state of the thing in view: pinned, DeadAir on, read | A choice among three or more |
|
||||
| Checkbox | An on-or-off setting in a form | An action |
|
||||
| Select | One of four or more fixed choices | Two choices (a toggle), or a list to search (a filter box) |
|
||||
| Tabs (Unread, All, In progress) | Views of the same list | Steps of a task |
|
||||
| Chips | Words someone types: keywords, hidden words | A fixed set of choices |
|
||||
| Search box | A list longer than a screen; it gets a clear button once something is typed | A list of five |
|
||||
|
||||
Every control has hover (only where there is hover), focus, pressed and disabled states, drawn
|
||||
from the theme's roles. Focus is always visible: ✅ the theme's focus ring · ❌ `outline:none`
|
||||
with nothing in its place.
|
||||
|
||||
A control that cannot act now is **dimmed in place**, with a tooltip saying why, not removed:
|
||||
✅ Play, dimmed, "Nothing to play in this item" · ❌ Play missing from items without a file. Remove
|
||||
it only where it can never apply, as the file buttons on an item with no file.
|
||||
|
||||
## Dialogs and sheets
|
||||
|
||||
* **Modal only when iPX needs an answer first**: adding a feed, a feed's settings, a confirmation.
|
||||
Everything else is in place: the reader, the player, Now Playing.
|
||||
* **One purpose, short.** A dialog that scrolls on a desktop is two dialogs, or a page.
|
||||
* **Buttons** go at the bottom right: Cancel on the left, the action on the right, as `cardacts`
|
||||
draws them. ✅ *Cancel* *Unsubscribe* · ❌ *Unsubscribe* *Cancel*. Two buttons is the norm; three
|
||||
at most.
|
||||
* **The action is named**, not OK: ✅ *Add feed*, *Download*, *Make playlist*. An icon button
|
||||
names it in its tooltip and `aria-label`.
|
||||
* **A destructive action is red** (`danger`) and is never the default: Enter in a box does not
|
||||
unsubscribe.
|
||||
* **Escape, a tap outside, and Cancel all close** without changing anything. Focus goes back to
|
||||
the control that opened the dialog.
|
||||
* **A confirmation is the page's own dialog**: `ask()`, or a dialog of its own when it has more
|
||||
than a sentence to say, as Unsubscribe does. Never `confirm()`, which the iOS app answered
|
||||
Cancel without showing (#453).
|
||||
* **When changes apply**: how iPX looks (theme, fonts, light or dark) applies as it is chosen; what
|
||||
changes what the server does (a feed's settings, a signal, a playlist) applies on Save, since
|
||||
it costs a check or a download.
|
||||
* **On a phone** a dialog is a sheet from the bottom edge, its buttons within reach of a thumb.
|
||||
|
||||
## Commands and menus
|
||||
|
||||
* **No menu bar.** Commands are in the toolbar of what they act on: the feed's header for the
|
||||
feed, the reader's bar for the item, the player for what plays. A row's less frequent commands
|
||||
are in its More menu.
|
||||
* **Every command has one visible home**; a key, a swipe or a context menu is a quicker way to it.
|
||||
* **Toggles change their name**: ✅ Pin, Unpin · ❌ two buttons, one always dimmed.
|
||||
* **Frequent first**: within a menu, the commands used most at the top, the destructive ones last,
|
||||
after a separator.
|
||||
|
||||
## Keyboard
|
||||
|
||||
The page uses single keys, like Feedly's, and `?` lists them all. The list in `keysModal()` is
|
||||
the table; a new key goes there in the same change.
|
||||
|
||||
| Rule | ✅ | ❌ |
|
||||
|---|---|---|
|
||||
| Never take a key the browser or the system has: anything with Ctrl, Cmd or Alt | `r` reloads the lists | Ctrl+R reloads the lists |
|
||||
| A key does nothing while typing in a box, except Escape | `j` in the search box types a j | `j` in the search box moves the selection |
|
||||
| Escape always closes the top thing: a confirmation, then a dialog, then the drawer, then Now Playing | | |
|
||||
| One key, one meaning, in every view | `s` pins the selected item | `s` saving settings in one view |
|
||||
| Pairs go by `g` + a letter, within a second and a half | `g u` Up Next | |
|
||||
| Every key's action has a button too | | A key with no button |
|
||||
|
||||
**Focus order** follows reading order: the toolbar, the feed list, the item list, the reader, the
|
||||
player. A row in a list is reached with Tab and opened with Enter or Space. Opening a dialog puts
|
||||
focus in it; closing it puts focus back.
|
||||
|
||||
## Feedback and timing
|
||||
|
||||
| Wait | What shows |
|
||||
|---|---|
|
||||
| Under 0.1 s | The result, in place: the row changes, the button presses |
|
||||
| 0.1-1 s | Nothing extra; the result arrives |
|
||||
| Over 1 s | A spinner where the result will appear, not over the whole page |
|
||||
| Over 5 s, or a download | Progress with an amount: "Downloading *file*: 52%", a bar on the row |
|
||||
| Over 10 s | Progress and a way to stop it |
|
||||
|
||||
* **Motion** is short: 120-250 ms for a press, a fade or a sheet, never over 450 ms, starting at
|
||||
once. With reduced motion asked for, nothing moves; spinners pulse instead of turning, sheets
|
||||
and toasts fade instead of sliding.
|
||||
* **Toasts** confirm what just happened, at the bottom, for 3.2 s. An error toast stays until it is
|
||||
dismissed, and a run of them does not stack up the screen.
|
||||
* **Sound and haptics** are never the only feedback; on the phone an error toast also gives a
|
||||
warning tap.
|
||||
|
||||
## Errors, undo and safety
|
||||
|
||||
* **Prevent before reporting**: Save is dimmed until the form can be saved; a number box has its
|
||||
limits (`min`, `max`); an address is checked when it is added, not on every key.
|
||||
* **Validate on Save**, not on each keystroke and not on leaving a field.
|
||||
* **Ask only before what cannot be taken back**: unsubscribing, marking a whole list read,
|
||||
deleting a playlist or a signal, removing an account. Not before marking one item read, pinning
|
||||
or queueing, which a second tap undoes.
|
||||
* **Offline is not an error**: what was kept still opens, and reads, pins and places are sent when
|
||||
the connection is back.
|
||||
* **A failure keeps what the person typed**: a dialog whose Save fails stays open with the message
|
||||
in it.
|
||||
|
||||
## Accessibility checklist
|
||||
|
||||
* Every icon-only control has a tooltip and an `aria-label` saying the same thing.
|
||||
* Every toggle has `aria-pressed`; every dialog `aria-labelledby` its title; a dialog makes the
|
||||
page behind it `inert`.
|
||||
* Every pointer action has a keyboard path, and every swipe a button.
|
||||
* Contrast passes WCAG AA in every palette (`node tests/contrast.ts`), for text and for icons.
|
||||
* Nothing relies on colour alone, on hover alone, or on sound alone.
|
||||
* Reduced motion, reduced transparency and more contrast are honoured
|
||||
(`prefers-reduced-motion`, `prefers-reduced-transparency`, `prefers-contrast`).
|
||||
* Text zooms to 200% without a horizontal scroll at 320 px wide.
|
||||
* Touch targets are at least 44 px, 40 in a dense row.
|
||||
* The page's language is set (`lang="en"`).
|
||||
|
||||
## Design decision log
|
||||
|
||||
| Decision | Choice | Why |
|
||||
|---|---|---|
|
||||
| Dialog button order | Cancel left, action right, bottom right | What every iPX dialog already does, and Apple's order since 1987, which the iOS app's users see in every other app; Windows 2010 has the reverse. One order, never mixed |
|
||||
| Default button | None for a destructive action; otherwise the action, never Cancel | Mac 1992, Windows 1995 and 2010 agree a dangerous action is never the default |
|
||||
| Menus | No menu bar; toolbars on what they act on, a More menu per row | A web page in a browser and an app on a phone have no menu bar of their own; Windows 2010 drops one with three categories or fewer |
|
||||
| Modal or in place | In place by default; modal only for an answer iPX needs first | Mac 1992 and Windows 1995: modal only when the program cannot go on without it |
|
||||
| Dim or hide | Dim in place, with the reason as a tooltip; hide only what can never apply | Apple 1987-2009 and Windows 1995: dimming keeps the screen stable |
|
||||
| When a change applies | Appearance at once; what the server does on Save | Windows 2010's live preview for what is cheap to try; Save for what costs a check or a download |
|
||||
| Shortcuts | Single keys and `g` pairs, as Feedly's, never a modifier | A reader's keys are used a hundred times a session; Apple 2009 and Windows 1995 say not to take the system's keys, which any modifier risks in a browser |
|
||||
| Confirm or undo | Ask before what cannot be taken back; what a second tap undoes is not asked | Apple 1987: alerts should be rare. iPX has no undo, so what cannot be reversed is asked about instead |
|
||||
| Breakpoints | One, at 820 px | Two layouts are tested; a third doubles the testing for a tablet that does well with either |
|
||||
|
||||
# Writing
|
||||
|
||||
## Voice and tone
|
||||
|
||||
| Be | This | Not that |
|
||||
|---|---|---|
|
||||
| Plain | Nothing in progress. Episodes you start and do not finish show up here. | No in-progress entries found. |
|
||||
| Direct, to "you" | Choose at least one podcast. | The user must select one or more podcasts. |
|
||||
| Calm | Unable to reach iPX. Check your connection and try again. | Error! Network request failed! |
|
||||
| Brief | Link copied | The link has been successfully copied to your clipboard. |
|
||||
| Honest about what happens next | Saved. It applies from the next check. | Saved. |
|
||||
|
||||
Signals and DeadAir have their own voice, radio's signal against noise; see
|
||||
[signals.md](signals.md). Everything else is the plain voice above.
|
||||
|
||||
## Capitalization
|
||||
|
||||
Sentence case everywhere: capitalize the first word and proper nouns, nothing else.
|
||||
|
||||
| Element | ✅ | ❌ |
|
||||
|---|---|---|
|
||||
| Heading, dialog title | Add a feed | Add a Feed |
|
||||
| Button | Copy link | Copy Link |
|
||||
| Menu item, tab | Show notes | Show Notes |
|
||||
| Label, checkbox | Media types to download | Media Types To Download |
|
||||
| Tooltip | Check every feed for new items | Check Every Feed For New Items |
|
||||
| Placeholder | Filter feeds… | FILTER FEEDS… |
|
||||
|
||||
Names of iPX's own features are proper nouns and keep their capitals: **iPX, Up Next, Now Playing,
|
||||
Currently Listening, All Subscriptions, Signals, DeadAir, Admin, Directory**. The filters Unread, All and In progress
|
||||
are tab labels, so only their first word is capitalized. Write other products as they write
|
||||
themselves: TypeSafe, Patreon, OPML, CarPlay.
|
||||
|
||||
## Punctuation
|
||||
|
||||
* **Ellipsis**: the one character `…` (U+2026), never three periods, which screen readers read
|
||||
out. Use it on a command that needs more from the person before it runs (✅ Import…), on a
|
||||
placeholder that invites typing (✅ Filter…), and on work in progress (✅ Loading…). Not on a
|
||||
command that only opens something: ✅ Settings, ❌ Settings….
|
||||
* **Periods**: a complete sentence ends with one; a fragment does not. ✅ Link copied ·
|
||||
✅ There is nothing to play in this item. ❌ Link copied. Two sentences both end with periods.
|
||||
* **No exclamation marks**, anywhere.
|
||||
* **Colons** after a label only when what follows completes it in the same line:
|
||||
✅ Downloading: *episode title*. Not after a form label.
|
||||
* **Quotation marks**: curly double quotes around what the person typed: ✅ No podcast is
|
||||
called “f1”.
|
||||
* **No symbols for words**: ✅ light or dark, ❌ light/dark · ✅ and, ❌ & · ✅ number of
|
||||
episodes, ❌ # of episodes.
|
||||
* **No dashes to join clauses**; two sentences instead. ❌ Could not copy automatically — select
|
||||
the URL… ✅ Unable to copy the link. Select it and copy it yourself.
|
||||
|
||||
## Elements
|
||||
|
||||
**Buttons** start with a verb and are four words at most, with no closing punctuation:
|
||||
✅ Use the new address · ✅ Share link · ❌ New address · ❌ Initials. An icon-only button has a
|
||||
tooltip and an `aria-label` that say the same thing. A link or button inside a sentence takes the sentence's case: ✅ Get one at typesafe.ai,
|
||||
then add it in Settings. A button that toggles changes its verb:
|
||||
✅ Pin / Unpin · ❌ Pin: on.
|
||||
|
||||
**Paired commands** match: Subscribe / Unsubscribe, Keep / Remove (an episode on this device),
|
||||
Mark read / Mark unread, Show / Hide.
|
||||
|
||||
**Tooltips** say what the control does, in more words than its label, and name its key when it has
|
||||
one: ✅ Back 15 seconds (←) · ✅ Play the next in Up Next. No closing period. Not a repeat of the
|
||||
label: ❌ title="Clear" on a button reading Clear.
|
||||
|
||||
**Labels** are nouns or short questions: ✅ Feed address · ✅ How many of the newest
|
||||
undownloaded items? Not instructions.
|
||||
|
||||
**Placeholders** show the form of an answer or invite a search, never replace the label:
|
||||
✅ https://example.com/rss · ✅ Morning commute · ❌ Enter the feed URL here. A field that holds a
|
||||
secret says whether one is set: ✅ Set. Paste a new one to replace it.
|
||||
|
||||
**Hints** under a control say what the person would not otherwise know: its effect, not how to use
|
||||
it. ✅ Only items matching a keyword are downloaded. ❌ Type keywords into the box above. If a
|
||||
control needs a paragraph, change the control.
|
||||
|
||||
**Empty lists** say what is missing and how it fills: ✅ No podcasts yet. Add a feed with episodes
|
||||
in it, and it shows here. ❌ No results.
|
||||
|
||||
**Toasts** confirm something that just happened, or say why it did not. One line; the subject is
|
||||
what changed, not iPX: ✅ Removed from Up Next · ❌ iPX has removed the episode from Up Next.
|
||||
|
||||
## Errors, warnings and confirmations
|
||||
|
||||
An error says **what did not happen, and what to do now**, with the why between them when it
|
||||
helps. The form is `Unable to <what>. <What to do>.`
|
||||
|
||||
| ✅ | ❌ |
|
||||
|---|---|
|
||||
| Unable to play this file. Try again, or download it again. | Playback error. |
|
||||
| Unable to reach iPX just now. Try again in a minute. | Request failed (502). |
|
||||
| Unable to keep it on this device. Try again. | Error: QuotaExceededError |
|
||||
|
||||
* Never "error", "failed" or "invalid" as the message, and nothing that blames the person.
|
||||
* No codes, status numbers, exception names or paths in the message. They go to the log, which
|
||||
the admin page shows.
|
||||
* Before writing an error, ask whether it can be prevented: a Save button stays disabled until the
|
||||
form is complete, rather than "Name is required" after the click.
|
||||
* When iPX can fix the problem, the message offers the fix as a button: ✅ Add it in Settings.
|
||||
* One message per problem; never one alert after another.
|
||||
|
||||
A **confirmation** asks only before something that cannot be undone. Its title is a question; its
|
||||
buttons name the action, the destructive one not the default.
|
||||
|
||||
| ✅ | ❌ |
|
||||
|---|---|
|
||||
| Unsubscribe? · *Cancel* · *Unsubscribe* | Are you sure? · *OK* · *Cancel* |
|
||||
|
||||
Cancel means nothing happened. If the action cannot be taken back halfway, the button is Stop.
|
||||
The page's `confirm()` (and the iOS app's answer to it) can only offer Cancel and OK, so its
|
||||
question names the action in full: ✅ Delete this file from the server?
|
||||
|
||||
**please** only when the person has to wait or do something because of iPX: ✅ Please wait while
|
||||
iPX imports 214 feeds. **sorry** only when something is lost or cannot go on. Neither as filler.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
One word for each thing, everywhere.
|
||||
|
||||
| Use | Not | Meaning |
|
||||
|---|---|---|
|
||||
| podcast | show, talk show, channel | a feed with audio or video in it |
|
||||
| episode | track, file (as the thing played) | an item of a podcast |
|
||||
| item | entry, post, article | anything a feed publishes; an episode is an item |
|
||||
| feed | RSS, source, channel | what someone subscribes to |
|
||||
| address | URL, link (for a feed) | where a feed or server is; "link" is what is shared |
|
||||
| subscribe, unsubscribe | follow, add/remove (for feeds) | |
|
||||
| download | fetch, grab | the server saving an episode's file |
|
||||
| keep on this device | download, save offline, cache | the phone or browser holding a copy |
|
||||
| check | scan, poll, refresh | the server reading a feed for new items |
|
||||
| read, unread | seen, new, viewed | |
|
||||
| pin | star, favorite, protect | an item kept from being deleted |
|
||||
| sign in, sign out | log in, log out, login | |
|
||||
| server | backend, instance, daemon | the iPX someone signs in to |
|
||||
| token | API key, secret | what a script or another server signs in with |
|
||||
| Up Next | queue, playlist | the episodes lined up to play |
|
||||
| playlist | smart list, collection | a list made from chosen podcasts |
|
||||
|
||||
Never in the interface: guid, enclosure, entry, scan job, worker, cache, 304, ETag, OPML child,
|
||||
widget, payload, and the names of the people who use iPX (no character speaks, waiting is a
|
||||
spinner). OPML stays: people exporting a list meet the word in other apps.
|
||||
|
||||
## Localization
|
||||
|
||||
iPX ships in English only, and its strings live in the code, not in a resource file. Write as if
|
||||
that will change: no sentence built from fragments joined in code (✅ `Kept on this device, to
|
||||
play offline: ${title}` keeps the variable at the end), plurals handled as a whole sentence, not
|
||||
with "(s)", dates and numbers through `toLocaleString` and the page's date helpers, and room for
|
||||
half again as much text in every label.
|
||||
|
||||
## Writing decision log
|
||||
|
||||
| Decision | Choice | Why |
|
||||
|---|---|---|
|
||||
| Title or sentence case for buttons and menus | Sentence case for everything | The web has no platform rule; Windows 2010 moved everything but titles to sentence case, and iPX's strings already are. One rule, no list of words to keep lowercase |
|
||||
| Case for labels, checkboxes, tooltips | Sentence case | Follows from the above; Windows 1995, Apple 2009, GNOME and KDE agree |
|
||||
| Lowercase words in title case | None needed | Nothing is in title case |
|
||||
| Contractions | Never: do not, cannot, it is | iPX's house style already spells them out, and KDE 2021 and GEM agree. Android and Windows 2010 use them for friendliness; iPX finds it in plain words instead |
|
||||
| Failure wording | "Unable to …" | Most of the page's errors already say it; one form, not "Could not", "Cannot" and "Unable to" side by side |
|
||||
| Ellipsis character | `…` | Apple 2009 and KDE: three periods break screen readers |
|
||||
| Ellipsis on Settings | No | Windows' test: an ellipsis means more input is needed, not that something opens; GNOME agrees, Apple 2009 differs |
|
||||
| Room for translation | Half again | KDE's 50% over GNOME's 30%; short labels grow most |
|
||||
| Exclamation marks | Never | House style; KDE and GEM keep them out of errors |
|
||||
| OK and Cancel | Specific verbs; OK only to acknowledge or where `confirm()` allows nothing else; Cancel only when nothing changed, otherwise Stop | Mac 1992, Windows 1995 and Apple 2009 over Motif's standard pair |
|
||||
| Button length | Four words at most | Mac 1992 says three; "Use the new address" needs four and is clearer than any three |
|
||||
| Tone | Plain and friendly, second person, never jokey in errors | Android 2012 and Windows 2010; Signals keeps its own radio voice |
|
||||
| please and sorry | The Windows 2010 rule: please when the person is put out, sorry when something is lost | Avoids the filler apology Android 2012 warns against |
|
||||
@@ -53,8 +53,7 @@ id, and Caddy's request lines theirs. ipx also serves Prometheus metrics (`[web]
|
||||
| `crates/feed/src/jev.rs` | Jev's pick of a category | — |
|
||||
| `crates/feed/src/guard.rs` | The connection guard against internal addresses (#320) | — |
|
||||
| `crates/ipx/src/download.rs` | Streaming download, naming, type sniffing, placement | `iPXDownloader.getFile` |
|
||||
| `crates/ipx/src/torrent.rs` | Hands torrents to qBittorrent's Web API and watches them to the end, stall abort | vendored BitTorrent 4.2.1 |
|
||||
| `crates/ipx/src/nzb.rs` | Hands NZBs to SABnzbd's API, watches them through post-processing, moves the finished folder in | |
|
||||
| `crates/ipx/src/torrent.rs` | librqbit session, seeding limits, stall abort | vendored BitTorrent 4.2.1 |
|
||||
| `crates/ipx/src/retention.rs` | Quota and age sweeps | `iPXQuotaManager.py` |
|
||||
| `crates/ipx/src/ipc.rs` | Event and command types, the socket server | `printMSG` on stdout |
|
||||
| `crates/ipx/src/auth.rs` | Argon2id hashing, session tokens, header names | — |
|
||||
@@ -103,7 +102,7 @@ and the files, and no page.
|
||||
a reason. What a filter skipped is judged again every scan, so a change of settings brings it
|
||||
back. A feed in a group takes your settings on the group for anything you have not set on it.
|
||||
7. Download what is still pending, newest first, up to the per-scan cap. A `.torrent` body goes to
|
||||
qBittorrent and an `.nzb` body to SABnzbd whatever its advertised type; an HTML body is a failed download — a login wall
|
||||
the torrent path whatever its advertised type; an HTML body is a failed download — a login wall
|
||||
or an error page — and is deleted.
|
||||
|
||||
## Data model
|
||||
@@ -209,20 +208,6 @@ else a `401`. A feed's items and files (its entries, `download-latest`, `/api/en
|
||||
| `GET /api/logs` | admin-only; the ring buffer, with a sequence cursor |
|
||||
| `GET /media/{id}` | the file, with Range support so seeking works |
|
||||
|
||||
Every route that takes or answers JSON also speaks protobuf (#465): `Content-Type:
|
||||
application/x-protobuf` for a body, `Accept: application/x-protobuf` for an answer, JSON
|
||||
otherwise. The messages are in `crates/wire/proto/` (ipx, directory and play), and the handlers do
|
||||
not know: `ipx_wire::negotiate`, a layer on each service's routes, converts the JSON at the edge
|
||||
by its table of each route's messages (`WIRE` in `web.rs`, `api.rs` and play's `lib.rs`). A route
|
||||
added to a router goes in its table. Debug builds convert every JSON answer strictly, so the cargo
|
||||
tests and the browser suite answer `500` for a field missing from the `.proto` or a route missing
|
||||
from the table. Errors stay JSON, and so does an answer of null. An answer goes into a struct
|
||||
generated from its message (prost, in `crates/wire/build.rs`) and out as protobuf, named in its
|
||||
`Content-Type` (`application/x-protobuf; messageType=ipx.FeedRows`); the page reads it with
|
||||
`web/src/wire.ts`, a decoder of its own driven by the same `.proto` files, which `web/build.mts`
|
||||
reads into the page and the offline worker (#470). The iOS app's own calls go in protobuf (#469), from Swift
|
||||
generated off the same files: a change to them is `sh ios/scripts/proto.sh` too.
|
||||
|
||||
Show notes are feed-supplied HTML from an untrusted source, sanitized with `ammonia` server-side
|
||||
before they reach the page.
|
||||
|
||||
|
||||
@@ -89,41 +89,15 @@ database as described above; `download_dir`, `socket`, `organize` and `fetch_int
|
||||
|
||||
```toml
|
||||
[torrent]
|
||||
enabled = true
|
||||
qbittorrent_url = "http://qbittorrent:8080" # its Web UI; empty holds torrents back
|
||||
username = "ipx" # empty when qBittorrent lets ipx's address in without one
|
||||
password = ""
|
||||
save_path = "" # where qBittorrent sees download_dir, if not at the same path
|
||||
seed_ratio = 1.0 # qBittorrent stops seeding at this ratio ...
|
||||
seed_time_mins = 60 # ... or after this long, whichever comes first
|
||||
stall_mins = 30 # give up on a torrent making no progress
|
||||
enabled = true
|
||||
seed_ratio = 1.0 # stop seeding at this ratio ...
|
||||
seed_time_mins = 60 # ... or after this long, whichever comes first
|
||||
port_range = "6881-6889"
|
||||
stall_mins = 30 # give up on a torrent making no progress
|
||||
```
|
||||
|
||||
Torrents go to [qBittorrent](https://www.qbittorrent.org/) through its Web API: ipx fetches the
|
||||
`.torrent` (or passes on the magnet link), adds it with the episode's own folder as its save path,
|
||||
and records the episode once qBittorrent has all of it. qBittorrent does the seeding. It has to be
|
||||
able to write to `download_dir`: mount the same folder into its container, and if the path is not
|
||||
the same as in ipx's, say where in `save_path`. A `.torrent` body is handed to qBittorrent whatever
|
||||
MIME type it was advertised as. Torrents are watched on their own tasks (two at a time) so a slow
|
||||
swarm never blocks a scan.
|
||||
|
||||
```toml
|
||||
[nzb]
|
||||
enabled = true
|
||||
sabnzbd_url = "http://sabnzbd:8080" # empty holds NZBs back
|
||||
api_key = "" # SABnzbd's API key (Config, General)
|
||||
category = "ipx" # the category jobs are added under
|
||||
save_path = "" # where SABnzbd sees download_dir, if not at the same path
|
||||
stall_mins = 30 # give up on an NZB making no progress
|
||||
```
|
||||
|
||||
NZBs go to [SABnzbd](https://sabnzbd.org/) the same way (#496): ipx fetches the `.nzb`, adds it
|
||||
under `category` named `nzb-<id>`, follows it through the queue and post-processing, then moves the
|
||||
finished folder into the episode's own and takes the job out of SABnzbd's history. SABnzbd takes no
|
||||
folder for a job, only for its category, so give the category a folder inside `download_dir` as
|
||||
SABnzbd sees it (for example `/ipx-downloads/.sabnzbd`), on the same disk, since the move is a
|
||||
rename. An `.nzb` body is handed to SABnzbd whatever MIME type it was advertised as, and NZBs share
|
||||
the torrents' two slots.
|
||||
A `.torrent` body is handed to the torrent path whatever MIME type it was advertised as. Torrents
|
||||
run on their own tasks (two at a time) so a slow swarm never blocks a scan.
|
||||
|
||||
## `[web]`
|
||||
|
||||
|
||||
@@ -162,9 +162,6 @@ blocks it, so no snapshot brings it back.
|
||||
| `DELETE /v1/instances/{name}` | rwa | drop one token's snapshot, its counts with it |
|
||||
| `POST /v1/feeds/{id}/refresh` | rwa | fetch the feed now, answering with its page |
|
||||
|
||||
Each also speaks protobuf, by `Accept` and `Content-Type: application/x-protobuf` (#465), in the
|
||||
messages of `crates/wire/proto/directory.proto`; ipx asks for it.
|
||||
|
||||
A feed's `id` is the first 64 bits of the SHA-256 of its address, normalised (scheme and host in
|
||||
lower case, no default port or fragment), so every server arrives at the same id. `subscribers`
|
||||
is the sum over every token's latest snapshot. A feed is listed once the directory has read it as
|
||||
|
||||
27
docs/play.md
27
docs/play.md
@@ -32,13 +32,10 @@ The compose service, beside `ipx-directory`:
|
||||
environment:
|
||||
PLAY_LOG_FORMAT: json
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://192.168.1.130:4318 # Tempo is not on this network
|
||||
# The dashboard's trace panels show only spans with this tag, as the others' are.
|
||||
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=production
|
||||
volumes:
|
||||
- /mnt/fast/appdata/ipx-play:/config
|
||||
ports:
|
||||
- "8102:8102"
|
||||
- "9191:9191" # /metrics, for Prometheus on the LAN; not in the tunnel
|
||||
```
|
||||
|
||||
Its config, `/mnt/fast/appdata/ipx-play/play.toml`:
|
||||
@@ -46,9 +43,6 @@ Its config, `/mnt/fast/appdata/ipx-play/play.toml`:
|
||||
```toml
|
||||
bind = "0.0.0.0:8102"
|
||||
public_url = "https://play.ipxreader.app"
|
||||
# Prometheus metrics, on a port of their own and not the one the tunnel publishes. Empty, or
|
||||
# left out, serves none.
|
||||
metrics_bind = "0.0.0.0:9191"
|
||||
|
||||
# One for each ipx server allowed to make links; `ipx-play token <name>` prints the lines.
|
||||
[[tokens]]
|
||||
@@ -66,27 +60,6 @@ The tunnel publishes `play.ipxreader.app` to `http://192.168.1.130:8102` with no
|
||||
the pages are anyone's. cloudflared is not on the project's network, so not `ipx-play:8102`, as
|
||||
the directory's route is the host's port too. `/v1` takes a token for everything.
|
||||
|
||||
## Watching it
|
||||
|
||||
Its traces go to Tempo as service `ipx-play`: a span a request, a child of ipx's when ipx shared
|
||||
an episode, so one trace runs from the page's Share through ipx to here. Its log is a JSON line a
|
||||
request (`target` `ipx_play::http`: `method`, `path`, `status`, `duration_ms`, `token`, the
|
||||
server's name and never its token) and one a share (`an episode was shared`: `server`, `id`).
|
||||
|
||||
Its metrics (#458), on `metrics_bind`, scraped as `job="ipx-play"`, beside the directory's job in
|
||||
Prometheus's config:
|
||||
|
||||
```yaml
|
||||
- job_name: ipx-play
|
||||
static_configs:
|
||||
- targets: ["192.168.1.130:9191"]
|
||||
```
|
||||
|
||||
`play_http_request_duration_seconds{method,route,status}` (a page opened is `route="/e/{id}"`, an
|
||||
address no route has `route=""`), `play_shares_total`, `play_process_resident_bytes`,
|
||||
`play_process_open_fds`, `play_uptime_seconds` and `play_build_info`. The iPX dashboard's
|
||||
`ipx-play` row draws them, and the alert `ipx-play is down` fires when Prometheus cannot reach it.
|
||||
|
||||
## Setting up ipx
|
||||
|
||||
In Admin, Directory, Sharing episodes: the address ipx reaches it at, `http://ipx-play:8102`
|
||||
|
||||
@@ -41,8 +41,6 @@ rules = [
|
||||
"Prometheus cannot reach ipx's /metrics: the iPX container is down or restarting.", no_data="Alerting"),
|
||||
rule("directory-down", "ipx-directory is down", 'up{job="ipx-directory"}', "lt", 1, "5m",
|
||||
"Prometheus cannot reach the directory's /metrics.", no_data="Alerting"),
|
||||
rule("play-down", "ipx-play is down", 'up{job="ipx-play"}', "lt", 1, "5m",
|
||||
"Prometheus cannot reach ipx-play's /metrics: shared links are likely not opening.", no_data="Alerting"),
|
||||
rule("web-down", "ipx-web is down", 'up{job="ipx-web"}', "lt", 1, "5m",
|
||||
"Prometheus cannot reach Caddy's /metrics: the page is likely down too.", no_data="Alerting"),
|
||||
# The worker: the daemon answers `ipxd status` while it is stuck, so only these say so.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""The iPX dashboard in Grafana: the four containers of the Arcane project ipx (ipx, ipx-web,
|
||||
ipx-directory, ipx-play) and Tower under them, from Prometheus, Loki (their logs, shipped by Alloy) and Tempo.
|
||||
"""The iPX dashboard in Grafana: the three containers of the Arcane project ipx (ipx, ipx-web,
|
||||
ipx-directory) and Tower under them, from Prometheus, Loki (their logs, shipped by Alloy) and Tempo.
|
||||
|
||||
python3 grafana/dashboard.py > /mnt/fast/arcane/projects/monitoring/grafana-provisioning/dashboards/ipx.json
|
||||
|
||||
Grafana reads that file on its own within a minute; edits made in Grafana are refused. Rows go
|
||||
top-down as a request does: an overview, Tower, then each container (ipx-web, ipx's API, its
|
||||
worker and its process, the directory, ipx-play), then traces and logs. Prometheus scrapes ipx's /metrics
|
||||
worker and its process, the directory), then traces and logs. Prometheus scrapes ipx's /metrics
|
||||
(job ipx, #194) and Tower's node exporter (job node); nothing scrapes the containers themselves,
|
||||
so ipx-web and the directory are read from their logs. The log panels read fields: ipx's
|
||||
(ipc.rs log_event), ipx's metrics (metrics.rs), the directory's and Caddy's; renaming one has to be
|
||||
@@ -41,9 +41,7 @@ WEB = ('{container="ipx-web"} |= "http.log.access" | json | __error__=""'
|
||||
' | request_uri !~ "/(api|media)/.*" | request_remote_ip != "127.0.0.1"') # not its healthcheck
|
||||
# Less what Caddy says at every start, by design: no admin endpoint, and no HTTPS or HTTP/3
|
||||
# behind the tunnel; and its goodbye on a restart.
|
||||
# ipx-play's (#447): a line a request (method, path, status, duration_ms, token), and one a share.
|
||||
PLAY_REQ = "play_http_request_duration_seconds"
|
||||
OTHERS_BAD = ('{container=~"ipx-web|ipx-directory|ipx-play"} | json | __error__="" | level =~ "(?i)warn|error"'
|
||||
OTHERS_BAD = ('{container=~"ipx-web|ipx-directory"} | json | __error__="" | level =~ "(?i)warn|error"'
|
||||
' | msg !~ "admin endpoint disabled|automatic HTTPS is completely disabled|HTTP/[23] skipped.*|exiting; byeee.*"')
|
||||
|
||||
|
||||
@@ -151,7 +149,7 @@ stat("Page and API errors", loki(f'sum(count_over_time({WEB_ALL} | status >= 500
|
||||
thresholds=GOOD_BAD, desc="Answers of 500 and up from ipx-web, for the page or passed on from ipx: 502 is ipx not answering.")
|
||||
stat("Warnings and errors", loki(f'sum(count_over_time({BAD} [$__range])) + sum(count_over_time({OTHERS_BAD} [$__range])) or vector(0)', instant=True), 20,
|
||||
thresholds=[{"color": "green", "value": None}, {"color": "orange", "value": 1}, {"color": "red", "value": 50}],
|
||||
desc="All four containers, in the time range.")
|
||||
desc="All three containers, in the time range.")
|
||||
y += 4
|
||||
stat("Feed failures", loki(f'sum(count_over_time({EV} | ev="feed_error" [$__range])) or vector(0)', instant=True), 0,
|
||||
thresholds=GOOD_BAD, desc="Failed feed checks in the time range.")
|
||||
@@ -396,33 +394,7 @@ ts("Feed bytes fetched", [prom('rate(ipx_feed_bytes_total{job="ipx"}[$__rate_int
|
||||
12, unit="Bps", desc="Feeds are read whole, so this is what scans and checks allocate; set it beside memory.")
|
||||
y += 8
|
||||
|
||||
# ---- ipx-play: the page a shared episode opens, public at play.ipxreader.app (#447), from its
|
||||
# /metrics on a port apart from the tunnel's (#458)
|
||||
row("ipx-play")
|
||||
stat("ipx-play", prom('max(up{job="ipx-play"})'), 0, thresholds=[{"color": "red", "value": None}, {"color": "green", "value": 1}],
|
||||
desc="Prometheus reaching ipx-play's /metrics: 1 is up.")["fieldConfig"]["defaults"]["mappings"] = [
|
||||
{"type": "value", "options": {"0": {"text": "down"}, "1": {"text": "up"}}}]
|
||||
stat("Episodes shared", prom('sum(increase(play_shares_total{job="ipx-play"}[$__range])) or vector(0)', instant=True), 4,
|
||||
desc="Links ipx servers asked for, the same episode again included.")
|
||||
stat("Pages opened", prom(f'sum(increase({PLAY_REQ}_count{{job="ipx-play",route="/e/{{id}}",status="200"}}[$__range])) or vector(0)', instant=True), 8,
|
||||
desc="Shared episodes someone opened, a link preview's fetch included.")
|
||||
stat("Links not found", prom(f'sum(increase({PLAY_REQ}_count{{job="ipx-play",status="404"}}[$__range])) or vector(0)', instant=True), 12,
|
||||
desc="A link mistyped, or someone trying addresses.")
|
||||
stat("Server errors", prom(f'sum(increase({PLAY_REQ}_count{{job="ipx-play",status=~"5.."}}[$__range])) or vector(0)', instant=True), 16,
|
||||
thresholds=GOOD_BAD, desc="Mostly its database not answering; its log has an error for each.")
|
||||
stat("Requests refused", prom(f'sum(increase({PLAY_REQ}_count{{job="ipx-play",status=~"401|422"}}[$__range])) or vector(0)', instant=True), 20,
|
||||
thresholds=GOOD_BAD, desc="A share without a valid token (401), or of an episode that looked private (422): ipx's own check should have kept it.")
|
||||
y += 4
|
||||
ts("Requests by route", [prom(f'sum by (route, status) (increase({PLAY_REQ}_count{{job="ipx-play"}}[$__interval]))', legend="{{status}} {{route}}")],
|
||||
0, w=8, bars=True, stack=True, desc="An empty route is an address no route has.")
|
||||
ts("Response time", [prom(f'histogram_quantile(0.5, sum by (le) (rate({PLAY_REQ}_bucket{{job="ipx-play"}}[$__rate_interval])))', legend="median"),
|
||||
prom(f'histogram_quantile(0.95, sum by (le) (rate({PLAY_REQ}_bucket{{job="ipx-play"}}[$__rate_interval])))', ref="B", legend="95th percentile")],
|
||||
8, w=8, unit="s")
|
||||
ts("ipx-play memory", [prom('play_process_resident_bytes{job="ipx-play"}', legend="resident")], 16, w=8, unit="bytes",
|
||||
desc="mimalloc, as the directory's: a rise that never comes down is a leak.")
|
||||
y += 8
|
||||
|
||||
# ---- Traces: all four send them to Tempo (#213)
|
||||
# ---- Traces: all three send them to Tempo (#213)
|
||||
row("Traces")
|
||||
for x, title, q in [(0, "Recent", TRACES + "}"),
|
||||
(8, "Slow (over 2s)", TRACES + " && duration > 2s}"),
|
||||
@@ -436,7 +408,7 @@ y += 10
|
||||
# ---- Logs
|
||||
row("Logs")
|
||||
panel("logs", "ipx: warnings and errors", 12, 10, 0, [loki(BAD + TEXT)], options=LOG_OPTS)
|
||||
panel("logs", "ipx-web, ipx-directory and ipx-play: warnings and errors", 12, 10, 12,
|
||||
panel("logs", "ipx-web and ipx-directory: warnings and errors", 12, 10, 12,
|
||||
[loki(OTHERS_BAD + ' | line_format "{{.container}} {{.level}}: {{.message}}{{.msg}}"')], options=LOG_OPTS)
|
||||
y += 10
|
||||
panel("logs", "ipx log", 24, 12, 0,
|
||||
|
||||
@@ -6,7 +6,6 @@ The iOS app, `ios/`. Format: [Keep a Changelog](https://keepachangelog.com/en/1.
|
||||
|
||||
### Added
|
||||
|
||||
- Up Next plays on with the screen locked: the app is told what follows and starts it when an episode ends, without waiting for the page (#473).
|
||||
- iPX on the iPhone: the page in an app, playing through the phone's own player, so an episode plays on with the screen locked and the lock screen, Control Center and a car's buttons drive it (#418).
|
||||
- Player token (Settings, This device): an ipx API token, kept in the keychain, which the player, the badge and CarPlay send to `https://ipxapi.sdf1.net` instead of using the page's sign-in cookie, so playback does not stop when that cookie expires (#419).
|
||||
- The icon shows All Subscriptions' unread count, as the page's badge does: set when the app comes forward, after an item is marked read, and by a refresh iOS runs now and then while the app is closed, so it can be hours behind (#421). Reading in the app and new items arriving while it is open set it at once, and while an episode plays it is checked every quarter of an hour.
|
||||
@@ -20,13 +19,3 @@ The iOS app, `ios/`. Format: [Keep a Changelog](https://keepachangelog.com/en/1.
|
||||
- A widget for the home screen and lock screen: the unread count, and the episode you were on with a button to resume or pause it (#428).
|
||||
- The icon's count stays right with the app closed: ipx sends it to the phone when it changes, once its `[push]` is set up, in place of waiting for iOS's background refresh (#433).
|
||||
- Presses are felt: a light tap on play, pause, flag and pull to refresh, a success on marking read, a warning with an error (#430).
|
||||
|
||||
### Changed
|
||||
|
||||
- The alert for a server out of reach reads "Unable to reach", with its buttons in sentence case, as the page writes (#507).
|
||||
- The player, the badge and CarPlay talk to ipx in protobuf rather than JSON, which is smaller and quicker to read; they need an ipx with protobuf (#465), and a place saved offline by an older build is still sent (#469).
|
||||
|
||||
### Fixed
|
||||
|
||||
- The app opens with no connection instead of saying it cannot reach the server: a load that fails for want of a connection is tried again from what the app last loaded (#506).
|
||||
- A question the page asks before going ahead (deleting a file, sharing an address that carries your access) is shown with Cancel and OK, rather than answered Cancel at once with nothing shown (#453).
|
||||
|
||||
@@ -74,7 +74,6 @@ on the `sdf1.net` zone) blocks every request to it except a bearer-token one for
|
||||
| `Sources/CookieBridge.swift` | the web view's cookies into `HTTPCookieStorage.shared`, for the player |
|
||||
| `Sources/Server.swift` | which server |
|
||||
| `Sources/Intents.swift`, `Shared/PlayPauseIntent.swift` | Siri and Shortcuts (#427) |
|
||||
| `Sources/API.swift`, `Sources/Wire` | ipx's API without the page, in protobuf (#469): `Wire` is generated from `crates/wire/proto` by `scripts/proto.sh`, and committed |
|
||||
| `Sources/LastPlayed.swift` | the last episode and its place, so Resume works with the app closed |
|
||||
| `Widgets/`, `Shared/Snapshot.swift`, `Sources/WidgetFeed.swift` | the widget (#428), and what the app writes for it |
|
||||
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import Foundation
|
||||
import SwiftProtobuf
|
||||
|
||||
/// Reading ipx without the page: the badge and CarPlay (#420), which has no web view. Signed in
|
||||
/// as the player is, by the credentials or else the cookies the web view left (CookieBridge).
|
||||
enum API {
|
||||
/// What ipx answers and reads in protobuf rather than JSON (#465, #469). The messages are
|
||||
/// `Sources/Wire`, generated from ipx's own `.proto` files by `scripts/proto.sh`.
|
||||
static let protobuf = "application/x-protobuf"
|
||||
|
||||
private static let session: URLSession = {
|
||||
let cfg = URLSessionConfiguration.default
|
||||
cfg.httpCookieStorage = .shared
|
||||
@@ -16,25 +11,13 @@ enum API {
|
||||
}()
|
||||
|
||||
/// The body of a 200, or nil: not signed in, no server, no connection.
|
||||
static func get(_ path: String, accept: String? = nil) async -> Data? {
|
||||
guard let (data, resp) = await fetch(path, accept: accept), resp.statusCode == 200 else { return nil }
|
||||
return data
|
||||
}
|
||||
|
||||
/// A 200's body as message `M`, or nil. Nil too for an answer not in protobuf: a server from
|
||||
/// before #465 answers JSON whatever it is asked, and JSON can read as a message of nothing.
|
||||
static func get<M: SwiftProtobuf.Message>(_ type: M.Type, _ path: String) async -> M? {
|
||||
guard let (data, resp) = await fetch(path, accept: protobuf), resp.statusCode == 200,
|
||||
resp.value(forHTTPHeaderField: "Content-Type")?.hasPrefix(protobuf) == true else { return nil }
|
||||
return try? M(serializedBytes: data)
|
||||
}
|
||||
|
||||
private static func fetch(_ path: String, accept: String?) async -> (Data, HTTPURLResponse)? {
|
||||
static func get(_ path: String) async -> Data? {
|
||||
guard let url = Server.resolveForPlayer(path) else { return nil }
|
||||
var req = URLRequest(url: url)
|
||||
if let accept { req.setValue(accept, forHTTPHeaderField: "Accept") }
|
||||
req.setValue("application/json", forHTTPHeaderField: "Accept")
|
||||
Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) }
|
||||
guard let (data, resp) = try? await session.data(for: req), let http = resp as? HTTPURLResponse else { return nil }
|
||||
return (data, http)
|
||||
guard let (data, resp) = try? await session.data(for: req),
|
||||
(resp as? HTTPURLResponse)?.statusCode == 200 else { return nil }
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,22 @@ import UserNotifications
|
||||
enum Badge {
|
||||
static let taskId = "net.sdf1.ipx.refresh"
|
||||
|
||||
private struct Row: Decodable {
|
||||
let id: String
|
||||
let group: String?
|
||||
let unread: Int?
|
||||
let hide_from_all: Bool?
|
||||
}
|
||||
|
||||
/// web/src/feeds.ts `unreadInAll`: a feed counts unless it, or the OPML it came from, is
|
||||
/// hidden from All Subscriptions.
|
||||
static func unread(inAll rows: [Ipx_FeedRow]) -> Int {
|
||||
let hidden = Set(rows.filter(\.hideFromAll).map(\.id))
|
||||
/// hidden from All Subscriptions. Nil when the body is not a feed list, so an error page
|
||||
/// does not turn the badge to zero.
|
||||
static func unread(inAll body: Data) -> Int? {
|
||||
guard let rows = try? JSONDecoder().decode([Row].self, from: body) else { return nil }
|
||||
let hidden = Set(rows.filter { $0.hide_from_all == true }.map(\.id))
|
||||
return rows.reduce(0) { n, f in
|
||||
if f.hideFromAll || (f.hasGroup && hidden.contains(f.group)) { return n }
|
||||
return n + max(0, Int(f.unread))
|
||||
if f.hide_from_all == true || f.group.map(hidden.contains) == true { return n }
|
||||
return n + max(0, f.unread ?? 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,11 +69,10 @@ enum Badge {
|
||||
return true
|
||||
}
|
||||
|
||||
/// All Subscriptions' unread count from ipx, or nil when it cannot be had: an answer that is
|
||||
/// not a feed list leaves the badge as it was rather than turning it to zero.
|
||||
/// All Subscriptions' unread count from ipx, or nil when it cannot be had.
|
||||
static func fetch() async -> Int? {
|
||||
guard let feeds = await API.get(Ipx_FeedRows.self, "/api/feeds") else { return nil }
|
||||
return unread(inAll: feeds.items)
|
||||
guard let data = await API.get("/api/feeds") else { return nil }
|
||||
return unread(inAll: data)
|
||||
}
|
||||
|
||||
// MARK: - while the app is closed
|
||||
|
||||
@@ -122,7 +122,7 @@ final class Bridge: NSObject, WKScriptMessageHandler {
|
||||
if let r = m["rate"] as? Double { playback.setRate(Float(r)) }
|
||||
if let v = m["volume"] as? Double { playback.setVolume(Float(v)) }
|
||||
// What this build can do, so a newer page offers nothing it would ask for in vain.
|
||||
send(["t": "host", "can": ["sleep", "route", "settings", "next"]])
|
||||
send(["t": "host", "can": ["sleep", "route", "settings"]])
|
||||
sendAppSettings()
|
||||
// A page reloaded while the timer runs is told how long is left.
|
||||
if let at = playback.sleepAt { send(["t": "sleep", "left": max(0, at.timeIntervalSinceNow)]) }
|
||||
@@ -139,21 +139,6 @@ final class Bridge: NSObject, WKScriptMessageHandler {
|
||||
feedTitle: m["feedTitle"] as? String ?? "",
|
||||
artwork: m["artwork"] as? String,
|
||||
duration: m["duration"] as? Int))
|
||||
case "next":
|
||||
// Without an episode it says nothing follows.
|
||||
guard let path = m["url"] as? String, let url = Server.resolveForPlayer(path),
|
||||
let enc = m["enc"] as? Int,
|
||||
let feedId = m["feedId"] as? String, let guid = m["guid"] as? String else {
|
||||
playback.next = nil
|
||||
return
|
||||
}
|
||||
let at = m["position"] as? Double ?? 0
|
||||
playback.next = (.init(
|
||||
url: url, enc: enc, feedId: feedId, guid: guid,
|
||||
title: m["title"] as? String ?? "",
|
||||
feedTitle: m["feedTitle"] as? String ?? "",
|
||||
artwork: m["artwork"] as? String,
|
||||
duration: m["duration"] as? Int), at > 5 ? at : nil)
|
||||
case "play": playback.play()
|
||||
case "pause": playback.pause()
|
||||
case "stop": playback.stop()
|
||||
|
||||
@@ -7,22 +7,14 @@ import UIKit
|
||||
// does. Now Playing is the system's, fed by Playback's now-playing info and remote commands.
|
||||
|
||||
/// An item as a car's list needs it: db.rs EntryRow, the fields used.
|
||||
struct CarEpisode {
|
||||
struct Enclosure {
|
||||
struct CarEpisode: Decodable {
|
||||
struct Enclosure: Decodable {
|
||||
let id: Int
|
||||
let url: String
|
||||
let mime: String?
|
||||
let deadair: Double?
|
||||
/// Set once ipx has the file; `/media/{id}` answers 404 before that.
|
||||
let path: String?
|
||||
|
||||
init(_ e: Ipx_EncRow) {
|
||||
id = Int(e.id)
|
||||
url = e.url
|
||||
mime = e.hasMime ? e.mime : nil
|
||||
deadair = e.hasDeadair ? Double(e.deadair) : nil
|
||||
path = e.hasPath ? e.path : nil
|
||||
}
|
||||
}
|
||||
|
||||
let guid: String
|
||||
@@ -33,16 +25,6 @@ struct CarEpisode {
|
||||
let position: Double
|
||||
let enclosures: [Enclosure]
|
||||
|
||||
init(_ e: Ipx_EntryRow) {
|
||||
guid = e.guid
|
||||
feed_id = e.feedID
|
||||
title = e.hasTitle ? e.title : nil
|
||||
image = e.hasImage ? e.image : nil
|
||||
duration = e.hasDuration ? Double(e.duration) : nil
|
||||
position = Double(e.position)
|
||||
enclosures = e.enclosures.map(Enclosure.init)
|
||||
}
|
||||
|
||||
/// The file to play: the first downloaded one that is sound (items.ts isPlayable, less video,
|
||||
/// which a car would play the sound of with nothing to say so). An item with none is not listed
|
||||
/// (#443): a post's picture or a file still to come is nothing a car can play.
|
||||
@@ -87,7 +69,7 @@ struct CarEpisode {
|
||||
}
|
||||
|
||||
/// A subscription, from `/api/feeds`.
|
||||
struct CarFeed {
|
||||
struct CarFeed: Decodable {
|
||||
let id: String
|
||||
let title: String?
|
||||
let image: String?
|
||||
@@ -98,16 +80,10 @@ struct CarFeed {
|
||||
let group: String?
|
||||
|
||||
var name: String { title ?? id }
|
||||
}
|
||||
|
||||
init(_ f: Ipx_FeedRow) {
|
||||
id = f.id
|
||||
title = f.hasTitle ? f.title : nil
|
||||
image = f.hasImage ? f.image : nil
|
||||
unread = Int(f.unread)
|
||||
entries = Int(f.entries)
|
||||
downloaded = Int(f.downloaded)
|
||||
group = f.hasGroup ? f.group : nil
|
||||
}
|
||||
private struct CarPage: Decodable {
|
||||
let entries: [CarEpisode]
|
||||
}
|
||||
|
||||
final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate {
|
||||
@@ -167,18 +143,19 @@ final class CarScreen: NSObject, CPTabBarTemplateDelegate {
|
||||
}
|
||||
|
||||
private func loadFeeds() async {
|
||||
guard let rows = await API.get(Ipx_FeedRows.self, "/api/feeds")?.items.map(CarFeed.init) else { return }
|
||||
guard let data = await API.get("/api/feeds"),
|
||||
let rows = try? JSONDecoder().decode([CarFeed].self, from: data) else { return }
|
||||
feeds = Dictionary(rows.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
|
||||
}
|
||||
|
||||
private func episodes(in list: CPListTemplate, from path: String, empty: String, oneFeed: Bool = false) async {
|
||||
guard let page = await API.get(Ipx_EntryPage.self, path) else {
|
||||
guard let data = await API.get(path), let page = try? JSONDecoder().decode(CarPage.self, from: data) else {
|
||||
unreachable(list)
|
||||
return
|
||||
}
|
||||
let kept = Set(Offline.shared.store.paths)
|
||||
let playing = Playback.shared.current
|
||||
let rows: [CPListItem] = page.entries.map(CarEpisode.init).compactMap { e in
|
||||
let rows: [CPListItem] = page.entries.compactMap { e in
|
||||
let feed = feeds[e.feed_id]
|
||||
guard let item = e.item(feedTitle: feed?.name ?? e.feed_id, feedImage: feed?.image, kept: kept) else {
|
||||
return nil
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import Foundation
|
||||
import Network
|
||||
import SwiftProtobuf
|
||||
|
||||
/// Writes the player made with no connection, sent when there is one (#425): where you got to in
|
||||
/// an episode, and that you finished it. In a browser the page's service worker holds these; the
|
||||
@@ -11,13 +10,7 @@ import SwiftProtobuf
|
||||
enum Outbox {
|
||||
struct Write: Codable, Equatable {
|
||||
var path: String
|
||||
var body: Data
|
||||
/// The body is protobuf (#469). Nil in a write queued by a build before it, whose body is
|
||||
/// JSON, and is sent as JSON.
|
||||
var protobuf: Bool?
|
||||
|
||||
// `json` was the body's name when it could only be JSON; kept, so those writes still read.
|
||||
enum CodingKeys: String, CodingKey { case path, body = "json", protobuf }
|
||||
var json: Data
|
||||
}
|
||||
|
||||
private static let key = "ipx.outbox"
|
||||
@@ -31,11 +24,11 @@ enum Outbox {
|
||||
|
||||
/// A write that never arrived. Only the player's own two kinds are kept: anything else, such
|
||||
/// as adding a feed, fails offline as it always has.
|
||||
static func add(path: String, _ body: any SwiftProtobuf.Message) {
|
||||
static func add(path: String, json: [String: Any]) {
|
||||
guard path.hasSuffix("/position") || path.hasSuffix("/flags"),
|
||||
let data = try? body.serializedData() else { return }
|
||||
let data = try? JSONSerialization.data(withJSONObject: json, options: [.sortedKeys]) else { return }
|
||||
var all = pending.filter { $0.path != path }
|
||||
all.append(Write(path: path, body: data, protobuf: true))
|
||||
all.append(Write(path: path, json: data))
|
||||
pending = all
|
||||
}
|
||||
|
||||
@@ -53,9 +46,9 @@ enum Outbox {
|
||||
guard let url = Server.resolveForPlayer(w.path) else { return }
|
||||
var req = URLRequest(url: url)
|
||||
req.httpMethod = "POST"
|
||||
req.setValue(w.protobuf == true ? API.protobuf : "application/json", forHTTPHeaderField: "Content-Type")
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) }
|
||||
req.httpBody = w.body
|
||||
req.httpBody = w.json
|
||||
guard (try? await session.data(for: req)) != nil else { return }
|
||||
// Removed by what it is, not where it was: a newer write may have replaced it while
|
||||
// this one was on its way.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import AVFoundation
|
||||
import MediaPlayer
|
||||
import SwiftProtobuf
|
||||
import UIKit
|
||||
|
||||
/// The phone's player: the one that plays on with the screen locked, and the one the lock screen
|
||||
@@ -32,9 +31,6 @@ final class Playback: NSObject {
|
||||
var onSlept: (() -> Void)?
|
||||
/// Something the page did not choose is loaded now: the car's pick (#420).
|
||||
var onChosen: (() -> Void)?
|
||||
/// What plays when this one ends: the first in Up Next (#473), and where in it to start, as
|
||||
/// the page last said. Here, not in the page, which is frozen while the screen is locked.
|
||||
var next: (item: Item, startAt: Double?)?
|
||||
|
||||
private let session: URLSession = {
|
||||
let cfg = URLSessionConfiguration.default
|
||||
@@ -273,15 +269,14 @@ final class Playback: NSObject {
|
||||
s.position = Double(secs)
|
||||
if let d = duration { s.duration = d }
|
||||
}
|
||||
var body = Ipx_Position()
|
||||
body.secs = Int64(secs)
|
||||
if let d = duration { body.duration = Int64(d.rounded()) }
|
||||
var body: [String: Any] = ["secs": secs]
|
||||
if let d = duration { body["duration"] = Int(d.rounded()) }
|
||||
// DeadAir's copy runs on a shorter clock; the server has to know which one this is.
|
||||
if item.url.path.contains("/deadair") { body.deadair = Int64(item.enc) }
|
||||
if item.url.path.contains("/deadair") { body["deadair"] = item.enc }
|
||||
let path = entryPath(item, "position")
|
||||
// Not arrived, kept for when the connection is back: offline, the ten-second retry would
|
||||
// only fail again, and the place reached on the last pause would be lost.
|
||||
Task { if await request("POST", path, body) == nil { Outbox.add(path: path, body) } }
|
||||
Task { if await request("POST", path, body) == nil { Outbox.add(path: path, json: body) } }
|
||||
}
|
||||
|
||||
// MARK: - as it plays
|
||||
@@ -309,12 +304,6 @@ final class Playback: NSObject {
|
||||
s.playing = false
|
||||
}
|
||||
markRead()
|
||||
// Up Next goes on, and the page takes it up from nowPlaying as it does the car's pick.
|
||||
if let n = next {
|
||||
next = nil
|
||||
playChosen(n.item, startAt: n.startAt)
|
||||
return
|
||||
}
|
||||
onState?(false)
|
||||
onEnded?()
|
||||
updateNowPlaying()
|
||||
@@ -325,9 +314,7 @@ final class Playback: NSObject {
|
||||
markedRead = true
|
||||
let path = entryPath(item, "flags")
|
||||
Task {
|
||||
var read = Ipx_Flags()
|
||||
read.read = true
|
||||
if await request("POST", path, read) == nil { Outbox.add(path: path, read) }
|
||||
if await request("POST", path, ["read": true]) == nil { Outbox.add(path: path, json: ["read": true]) }
|
||||
await Badge.refresh()
|
||||
}
|
||||
}
|
||||
@@ -419,14 +406,14 @@ final class Playback: NSObject {
|
||||
/// One call to ipx, signed in by the credentials or else the web view's cookies; its status, or nil if it never
|
||||
/// arrived. A position that does not save is saved again ten seconds on.
|
||||
@discardableResult
|
||||
private func request(_ method: String, _ path: String, _ body: (any SwiftProtobuf.Message)? = nil) async -> Int? {
|
||||
private func request(_ method: String, _ path: String, _ json: [String: Any]? = nil) async -> Int? {
|
||||
guard let url = Server.resolveForPlayer(path) else { return nil }
|
||||
var req = URLRequest(url: url)
|
||||
req.httpMethod = method
|
||||
Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) }
|
||||
if let body {
|
||||
req.setValue(API.protobuf, forHTTPHeaderField: "Content-Type")
|
||||
req.httpBody = try? body.serializedData()
|
||||
if let json {
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
req.httpBody = try? JSONSerialization.data(withJSONObject: json)
|
||||
}
|
||||
guard let (_, resp) = try? await session.data(for: req) else { return nil }
|
||||
return (resp as? HTTPURLResponse)?.statusCode
|
||||
|
||||
@@ -122,48 +122,15 @@ final class WebViewController: UIViewController, WKNavigationDelegate, WKUIDeleg
|
||||
decisionHandler(.cancel)
|
||||
}
|
||||
|
||||
/// The page's confirm(): without this WebKit answers Cancel at once and shows nothing, so
|
||||
/// anything that asked first (deleting a file, sharing a Patreon address) could not go ahead
|
||||
/// in the app (#453). The page uses no alert() or prompt().
|
||||
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String,
|
||||
initiatedByFrame frame: WKFrameInfo,
|
||||
completionHandler: @escaping @MainActor (Bool) -> Void) {
|
||||
// Another alert already up cannot have this one over it: answered as before, Cancel.
|
||||
guard presentedViewController == nil else { return completionHandler(false) }
|
||||
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(false) })
|
||||
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(true) })
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
/// The load from the web view's own cache has been tried since the last that worked.
|
||||
private var triedCache = false
|
||||
|
||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
triedCache = false
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!,
|
||||
withError error: Error) {
|
||||
// No connection: the page as last loaded, from the web view's cache, which then reads
|
||||
// what the service worker kept. The app's own load may not go through the worker, so
|
||||
// offline it failed and said the server could not be reached (#506).
|
||||
let offline: Set<URLError.Code> = [.notConnectedToInternet, .cannotConnectToHost, .cannotFindHost,
|
||||
.timedOut, .networkConnectionLost, .dnsLookupFailed,
|
||||
.dataNotAllowed, .internationalRoamingOff]
|
||||
if !triedCache, let code = (error as? URLError)?.code, offline.contains(code), let url = Server.url {
|
||||
triedCache = true
|
||||
webView.load(URLRequest(url: url, cachePolicy: .returnCacheDataDontLoad))
|
||||
return
|
||||
}
|
||||
triedCache = false
|
||||
let host = Server.url?.host ?? "the server"
|
||||
let alert = UIAlertController(title: "Unable to reach \(host)",
|
||||
let alert = UIAlertController(title: "Cannot reach \(host)",
|
||||
message: error.localizedDescription, preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "Try again", style: .default) { [weak self] _ in
|
||||
alert.addAction(UIAlertAction(title: "Try Again", style: .default) { [weak self] _ in
|
||||
if let url = Server.url { self?.webView.load(URLRequest(url: url)) }
|
||||
})
|
||||
alert.addAction(UIAlertAction(title: "Change server", style: .default) { [weak self] _ in
|
||||
alert.addAction(UIAlertAction(title: "Change Server", style: .default) { [weak self] _ in
|
||||
self?.askForServer()
|
||||
})
|
||||
if presentedViewController == nil { present(alert, animated: true) }
|
||||
|
||||
@@ -1,941 +0,0 @@
|
||||
// DO NOT EDIT.
|
||||
// swift-format-ignore-file
|
||||
// swiftlint:disable all
|
||||
//
|
||||
// Generated by the Swift generator plugin for the protocol buffer compiler.
|
||||
// Source: directory.proto
|
||||
//
|
||||
// For information on using the generated types, please see the documentation:
|
||||
// https://github.com/apple/swift-protobuf/
|
||||
|
||||
/// ipx-directory's API under /v1 (crates/directory/src/wire.rs), each message named after the Rust
|
||||
/// struct it mirrors. A field added there goes here too; debug builds refuse an answer with a field
|
||||
/// missing here. A message whose only field is `repeated items` is a JSON array.
|
||||
|
||||
import SwiftProtobuf
|
||||
|
||||
// If the compiler emits an error on this type, it is because this file
|
||||
// was generated by a version of the `protoc` Swift plug-in that is
|
||||
// incompatible with the version of SwiftProtobuf to which you are linking.
|
||||
// Please ensure that you are building against the same version of the API
|
||||
// that was used to generate this file.
|
||||
fileprivate nonisolated struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
|
||||
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
|
||||
typealias Version = _2
|
||||
}
|
||||
|
||||
/// GET /v1/me.
|
||||
nonisolated struct Directory_Me: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var name: String = String()
|
||||
|
||||
/// "ro", "rw" or "rwa".
|
||||
var access: String = String()
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
}
|
||||
|
||||
nonisolated struct Directory_Listing: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var id: String = String()
|
||||
|
||||
var url: String = String()
|
||||
|
||||
var title: String {
|
||||
get {_title ?? String()}
|
||||
set {_title = newValue}
|
||||
}
|
||||
/// Returns true if `title` has been explicitly set.
|
||||
var hasTitle: Bool {self._title != nil}
|
||||
/// Clears the value of `title`. Subsequent reads from it will return its default value.
|
||||
mutating func clearTitle() {self._title = nil}
|
||||
|
||||
var image: String {
|
||||
get {_image ?? String()}
|
||||
set {_image = newValue}
|
||||
}
|
||||
/// Returns true if `image` has been explicitly set.
|
||||
var hasImage: Bool {self._image != nil}
|
||||
/// Clears the value of `image`. Subsequent reads from it will return its default value.
|
||||
mutating func clearImage() {self._image = nil}
|
||||
|
||||
var category: String {
|
||||
get {_category ?? String()}
|
||||
set {_category = newValue}
|
||||
}
|
||||
/// Returns true if `category` has been explicitly set.
|
||||
var hasCategory: Bool {self._category != nil}
|
||||
/// Clears the value of `category`. Subsequent reads from it will return its default value.
|
||||
mutating func clearCategory() {self._category = nil}
|
||||
|
||||
var subcategory: String {
|
||||
get {_subcategory ?? String()}
|
||||
set {_subcategory = newValue}
|
||||
}
|
||||
/// Returns true if `subcategory` has been explicitly set.
|
||||
var hasSubcategory: Bool {self._subcategory != nil}
|
||||
/// Clears the value of `subcategory`. Subsequent reads from it will return its default value.
|
||||
mutating func clearSubcategory() {self._subcategory = nil}
|
||||
|
||||
var podcast: Bool = false
|
||||
|
||||
var subscribers: Int64 = 0
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
|
||||
fileprivate var _title: String? = nil
|
||||
fileprivate var _image: String? = nil
|
||||
fileprivate var _category: String? = nil
|
||||
fileprivate var _subcategory: String? = nil
|
||||
}
|
||||
|
||||
/// GET /v1/feeds, GET /v1/popular.
|
||||
nonisolated struct Directory_Listings: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var items: [Directory_Listing] = []
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
}
|
||||
|
||||
nonisolated struct Directory_Item: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var guid: String = String()
|
||||
|
||||
var title: String {
|
||||
get {_title ?? String()}
|
||||
set {_title = newValue}
|
||||
}
|
||||
/// Returns true if `title` has been explicitly set.
|
||||
var hasTitle: Bool {self._title != nil}
|
||||
/// Clears the value of `title`. Subsequent reads from it will return its default value.
|
||||
mutating func clearTitle() {self._title = nil}
|
||||
|
||||
var link: String {
|
||||
get {_link ?? String()}
|
||||
set {_link = newValue}
|
||||
}
|
||||
/// Returns true if `link` has been explicitly set.
|
||||
var hasLink: Bool {self._link != nil}
|
||||
/// Clears the value of `link`. Subsequent reads from it will return its default value.
|
||||
mutating func clearLink() {self._link = nil}
|
||||
|
||||
var published: Int64 {
|
||||
get {_published ?? 0}
|
||||
set {_published = newValue}
|
||||
}
|
||||
/// Returns true if `published` has been explicitly set.
|
||||
var hasPublished: Bool {self._published != nil}
|
||||
/// Clears the value of `published`. Subsequent reads from it will return its default value.
|
||||
mutating func clearPublished() {self._published = nil}
|
||||
|
||||
var duration: Int64 {
|
||||
get {_duration ?? 0}
|
||||
set {_duration = newValue}
|
||||
}
|
||||
/// Returns true if `duration` has been explicitly set.
|
||||
var hasDuration: Bool {self._duration != nil}
|
||||
/// Clears the value of `duration`. Subsequent reads from it will return its default value.
|
||||
mutating func clearDuration() {self._duration = nil}
|
||||
|
||||
var description_p: String {
|
||||
get {_description_p ?? String()}
|
||||
set {_description_p = newValue}
|
||||
}
|
||||
/// Returns true if `description_p` has been explicitly set.
|
||||
var hasDescription_p: Bool {self._description_p != nil}
|
||||
/// Clears the value of `description_p`. Subsequent reads from it will return its default value.
|
||||
mutating func clearDescription_p() {self._description_p = nil}
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
|
||||
fileprivate var _title: String? = nil
|
||||
fileprivate var _link: String? = nil
|
||||
fileprivate var _published: Int64? = nil
|
||||
fileprivate var _duration: Int64? = nil
|
||||
fileprivate var _description_p: String? = nil
|
||||
}
|
||||
|
||||
/// GET /v1/feeds/{id}, POST /v1/feeds/{id}/refresh: a Listing's fields and these.
|
||||
nonisolated struct Directory_FeedPage: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var id: String = String()
|
||||
|
||||
var url: String = String()
|
||||
|
||||
var title: String {
|
||||
get {_title ?? String()}
|
||||
set {_title = newValue}
|
||||
}
|
||||
/// Returns true if `title` has been explicitly set.
|
||||
var hasTitle: Bool {self._title != nil}
|
||||
/// Clears the value of `title`. Subsequent reads from it will return its default value.
|
||||
mutating func clearTitle() {self._title = nil}
|
||||
|
||||
var image: String {
|
||||
get {_image ?? String()}
|
||||
set {_image = newValue}
|
||||
}
|
||||
/// Returns true if `image` has been explicitly set.
|
||||
var hasImage: Bool {self._image != nil}
|
||||
/// Clears the value of `image`. Subsequent reads from it will return its default value.
|
||||
mutating func clearImage() {self._image = nil}
|
||||
|
||||
var category: String {
|
||||
get {_category ?? String()}
|
||||
set {_category = newValue}
|
||||
}
|
||||
/// Returns true if `category` has been explicitly set.
|
||||
var hasCategory: Bool {self._category != nil}
|
||||
/// Clears the value of `category`. Subsequent reads from it will return its default value.
|
||||
mutating func clearCategory() {self._category = nil}
|
||||
|
||||
var subcategory: String {
|
||||
get {_subcategory ?? String()}
|
||||
set {_subcategory = newValue}
|
||||
}
|
||||
/// Returns true if `subcategory` has been explicitly set.
|
||||
var hasSubcategory: Bool {self._subcategory != nil}
|
||||
/// Clears the value of `subcategory`. Subsequent reads from it will return its default value.
|
||||
mutating func clearSubcategory() {self._subcategory = nil}
|
||||
|
||||
var podcast: Bool = false
|
||||
|
||||
var subscribers: Int64 = 0
|
||||
|
||||
var description_p: String {
|
||||
get {_description_p ?? String()}
|
||||
set {_description_p = newValue}
|
||||
}
|
||||
/// Returns true if `description_p` has been explicitly set.
|
||||
var hasDescription_p: Bool {self._description_p != nil}
|
||||
/// Clears the value of `description_p`. Subsequent reads from it will return its default value.
|
||||
mutating func clearDescription_p() {self._description_p = nil}
|
||||
|
||||
var failing: String {
|
||||
get {_failing ?? String()}
|
||||
set {_failing = newValue}
|
||||
}
|
||||
/// Returns true if `failing` has been explicitly set.
|
||||
var hasFailing: Bool {self._failing != nil}
|
||||
/// Clears the value of `failing`. Subsequent reads from it will return its default value.
|
||||
mutating func clearFailing() {self._failing = nil}
|
||||
|
||||
var items: [Directory_Item] = []
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
|
||||
fileprivate var _title: String? = nil
|
||||
fileprivate var _image: String? = nil
|
||||
fileprivate var _category: String? = nil
|
||||
fileprivate var _subcategory: String? = nil
|
||||
fileprivate var _description_p: String? = nil
|
||||
fileprivate var _failing: String? = nil
|
||||
}
|
||||
|
||||
nonisolated struct Directory_SnapshotEntry: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var url: String = String()
|
||||
|
||||
var subscribers: Int64 = 0
|
||||
|
||||
var category: String {
|
||||
get {_category ?? String()}
|
||||
set {_category = newValue}
|
||||
}
|
||||
/// Returns true if `category` has been explicitly set.
|
||||
var hasCategory: Bool {self._category != nil}
|
||||
/// Clears the value of `category`. Subsequent reads from it will return its default value.
|
||||
mutating func clearCategory() {self._category = nil}
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
|
||||
fileprivate var _category: String? = nil
|
||||
}
|
||||
|
||||
/// POST /v1/snapshot, the body.
|
||||
nonisolated struct Directory_Snapshot: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var items: [Directory_SnapshotEntry] = []
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
}
|
||||
|
||||
/// POST /v1/snapshot, the answer.
|
||||
nonisolated struct Directory_SnapshotResult: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var accepted: UInt64 = 0
|
||||
|
||||
var refusedPrivate: UInt64 = 0
|
||||
|
||||
var refusedBlocked: UInt64 = 0
|
||||
|
||||
var refusedInvalid: UInt64 = 0
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
}
|
||||
|
||||
nonisolated struct Directory_Instance: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var name: String = String()
|
||||
|
||||
var feeds: Int64 = 0
|
||||
|
||||
var subscribers: Int64 = 0
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
}
|
||||
|
||||
/// GET /v1/instances.
|
||||
nonisolated struct Directory_Instances: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var items: [Directory_Instance] = []
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
}
|
||||
|
||||
nonisolated struct Directory_Blocked: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var id: String = String()
|
||||
|
||||
var url: String {
|
||||
get {_url ?? String()}
|
||||
set {_url = newValue}
|
||||
}
|
||||
/// Returns true if `url` has been explicitly set.
|
||||
var hasURL: Bool {self._url != nil}
|
||||
/// Clears the value of `url`. Subsequent reads from it will return its default value.
|
||||
mutating func clearURL() {self._url = nil}
|
||||
|
||||
var title: String {
|
||||
get {_title ?? String()}
|
||||
set {_title = newValue}
|
||||
}
|
||||
/// Returns true if `title` has been explicitly set.
|
||||
var hasTitle: Bool {self._title != nil}
|
||||
/// Clears the value of `title`. Subsequent reads from it will return its default value.
|
||||
mutating func clearTitle() {self._title = nil}
|
||||
|
||||
var at: Int64 = 0
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
|
||||
fileprivate var _url: String? = nil
|
||||
fileprivate var _title: String? = nil
|
||||
}
|
||||
|
||||
/// GET /v1/blocked.
|
||||
nonisolated struct Directory_BlockedList: Sendable {
|
||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
||||
// methods supported on all messages.
|
||||
|
||||
var items: [Directory_Blocked] = []
|
||||
|
||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
||||
|
||||
init() {}
|
||||
}
|
||||
|
||||
// MARK: - Code below here is support for the SwiftProtobuf runtime.
|
||||
|
||||
fileprivate nonisolated let _protobuf_package = "directory"
|
||||
|
||||
nonisolated extension Directory_Me: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".Me"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}name\0\u{1}access\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeSingularStringField(value: &self.name) }()
|
||||
case 2: try { try decoder.decodeSingularStringField(value: &self.access) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
if !self.name.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
|
||||
}
|
||||
if !self.access.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.access, fieldNumber: 2)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_Me, rhs: Directory_Me) -> Bool {
|
||||
if lhs.name != rhs.name {return false}
|
||||
if lhs.access != rhs.access {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_Listing: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".Listing"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}url\0\u{1}title\0\u{1}image\0\u{1}category\0\u{1}subcategory\0\u{1}podcast\0\u{1}subscribers\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
|
||||
case 2: try { try decoder.decodeSingularStringField(value: &self.url) }()
|
||||
case 3: try { try decoder.decodeSingularStringField(value: &self._title) }()
|
||||
case 4: try { try decoder.decodeSingularStringField(value: &self._image) }()
|
||||
case 5: try { try decoder.decodeSingularStringField(value: &self._category) }()
|
||||
case 6: try { try decoder.decodeSingularStringField(value: &self._subcategory) }()
|
||||
case 7: try { try decoder.decodeSingularBoolField(value: &self.podcast) }()
|
||||
case 8: try { try decoder.decodeSingularInt64Field(value: &self.subscribers) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every if/case branch local when no optimizations
|
||||
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
|
||||
// https://github.com/apple/swift-protobuf/issues/1182
|
||||
if !self.id.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
|
||||
}
|
||||
if !self.url.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.url, fieldNumber: 2)
|
||||
}
|
||||
try { if let v = self._title {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
|
||||
} }()
|
||||
try { if let v = self._image {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 4)
|
||||
} }()
|
||||
try { if let v = self._category {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 5)
|
||||
} }()
|
||||
try { if let v = self._subcategory {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 6)
|
||||
} }()
|
||||
if self.podcast != false {
|
||||
try visitor.visitSingularBoolField(value: self.podcast, fieldNumber: 7)
|
||||
}
|
||||
if self.subscribers != 0 {
|
||||
try visitor.visitSingularInt64Field(value: self.subscribers, fieldNumber: 8)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_Listing, rhs: Directory_Listing) -> Bool {
|
||||
if lhs.id != rhs.id {return false}
|
||||
if lhs.url != rhs.url {return false}
|
||||
if lhs._title != rhs._title {return false}
|
||||
if lhs._image != rhs._image {return false}
|
||||
if lhs._category != rhs._category {return false}
|
||||
if lhs._subcategory != rhs._subcategory {return false}
|
||||
if lhs.podcast != rhs.podcast {return false}
|
||||
if lhs.subscribers != rhs.subscribers {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_Listings: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".Listings"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
if !self.items.isEmpty {
|
||||
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_Listings, rhs: Directory_Listings) -> Bool {
|
||||
if lhs.items != rhs.items {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_Item: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".Item"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}guid\0\u{1}title\0\u{1}link\0\u{1}published\0\u{1}duration\0\u{1}description\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeSingularStringField(value: &self.guid) }()
|
||||
case 2: try { try decoder.decodeSingularStringField(value: &self._title) }()
|
||||
case 3: try { try decoder.decodeSingularStringField(value: &self._link) }()
|
||||
case 4: try { try decoder.decodeSingularInt64Field(value: &self._published) }()
|
||||
case 5: try { try decoder.decodeSingularInt64Field(value: &self._duration) }()
|
||||
case 6: try { try decoder.decodeSingularStringField(value: &self._description_p) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every if/case branch local when no optimizations
|
||||
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
|
||||
// https://github.com/apple/swift-protobuf/issues/1182
|
||||
if !self.guid.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.guid, fieldNumber: 1)
|
||||
}
|
||||
try { if let v = self._title {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
|
||||
} }()
|
||||
try { if let v = self._link {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
|
||||
} }()
|
||||
try { if let v = self._published {
|
||||
try visitor.visitSingularInt64Field(value: v, fieldNumber: 4)
|
||||
} }()
|
||||
try { if let v = self._duration {
|
||||
try visitor.visitSingularInt64Field(value: v, fieldNumber: 5)
|
||||
} }()
|
||||
try { if let v = self._description_p {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 6)
|
||||
} }()
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_Item, rhs: Directory_Item) -> Bool {
|
||||
if lhs.guid != rhs.guid {return false}
|
||||
if lhs._title != rhs._title {return false}
|
||||
if lhs._link != rhs._link {return false}
|
||||
if lhs._published != rhs._published {return false}
|
||||
if lhs._duration != rhs._duration {return false}
|
||||
if lhs._description_p != rhs._description_p {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_FeedPage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".FeedPage"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}url\0\u{1}title\0\u{1}image\0\u{1}category\0\u{1}subcategory\0\u{1}podcast\0\u{1}subscribers\0\u{1}description\0\u{1}failing\0\u{1}items\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
|
||||
case 2: try { try decoder.decodeSingularStringField(value: &self.url) }()
|
||||
case 3: try { try decoder.decodeSingularStringField(value: &self._title) }()
|
||||
case 4: try { try decoder.decodeSingularStringField(value: &self._image) }()
|
||||
case 5: try { try decoder.decodeSingularStringField(value: &self._category) }()
|
||||
case 6: try { try decoder.decodeSingularStringField(value: &self._subcategory) }()
|
||||
case 7: try { try decoder.decodeSingularBoolField(value: &self.podcast) }()
|
||||
case 8: try { try decoder.decodeSingularInt64Field(value: &self.subscribers) }()
|
||||
case 9: try { try decoder.decodeSingularStringField(value: &self._description_p) }()
|
||||
case 10: try { try decoder.decodeSingularStringField(value: &self._failing) }()
|
||||
case 11: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every if/case branch local when no optimizations
|
||||
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
|
||||
// https://github.com/apple/swift-protobuf/issues/1182
|
||||
if !self.id.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
|
||||
}
|
||||
if !self.url.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.url, fieldNumber: 2)
|
||||
}
|
||||
try { if let v = self._title {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
|
||||
} }()
|
||||
try { if let v = self._image {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 4)
|
||||
} }()
|
||||
try { if let v = self._category {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 5)
|
||||
} }()
|
||||
try { if let v = self._subcategory {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 6)
|
||||
} }()
|
||||
if self.podcast != false {
|
||||
try visitor.visitSingularBoolField(value: self.podcast, fieldNumber: 7)
|
||||
}
|
||||
if self.subscribers != 0 {
|
||||
try visitor.visitSingularInt64Field(value: self.subscribers, fieldNumber: 8)
|
||||
}
|
||||
try { if let v = self._description_p {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 9)
|
||||
} }()
|
||||
try { if let v = self._failing {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 10)
|
||||
} }()
|
||||
if !self.items.isEmpty {
|
||||
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 11)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_FeedPage, rhs: Directory_FeedPage) -> Bool {
|
||||
if lhs.id != rhs.id {return false}
|
||||
if lhs.url != rhs.url {return false}
|
||||
if lhs._title != rhs._title {return false}
|
||||
if lhs._image != rhs._image {return false}
|
||||
if lhs._category != rhs._category {return false}
|
||||
if lhs._subcategory != rhs._subcategory {return false}
|
||||
if lhs.podcast != rhs.podcast {return false}
|
||||
if lhs.subscribers != rhs.subscribers {return false}
|
||||
if lhs._description_p != rhs._description_p {return false}
|
||||
if lhs._failing != rhs._failing {return false}
|
||||
if lhs.items != rhs.items {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_SnapshotEntry: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".SnapshotEntry"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}url\0\u{1}subscribers\0\u{1}category\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeSingularStringField(value: &self.url) }()
|
||||
case 2: try { try decoder.decodeSingularInt64Field(value: &self.subscribers) }()
|
||||
case 3: try { try decoder.decodeSingularStringField(value: &self._category) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every if/case branch local when no optimizations
|
||||
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
|
||||
// https://github.com/apple/swift-protobuf/issues/1182
|
||||
if !self.url.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.url, fieldNumber: 1)
|
||||
}
|
||||
if self.subscribers != 0 {
|
||||
try visitor.visitSingularInt64Field(value: self.subscribers, fieldNumber: 2)
|
||||
}
|
||||
try { if let v = self._category {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
|
||||
} }()
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_SnapshotEntry, rhs: Directory_SnapshotEntry) -> Bool {
|
||||
if lhs.url != rhs.url {return false}
|
||||
if lhs.subscribers != rhs.subscribers {return false}
|
||||
if lhs._category != rhs._category {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_Snapshot: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".Snapshot"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
if !self.items.isEmpty {
|
||||
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_Snapshot, rhs: Directory_Snapshot) -> Bool {
|
||||
if lhs.items != rhs.items {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_SnapshotResult: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".SnapshotResult"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}accepted\0\u{3}refused_private\0\u{3}refused_blocked\0\u{3}refused_invalid\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeSingularUInt64Field(value: &self.accepted) }()
|
||||
case 2: try { try decoder.decodeSingularUInt64Field(value: &self.refusedPrivate) }()
|
||||
case 3: try { try decoder.decodeSingularUInt64Field(value: &self.refusedBlocked) }()
|
||||
case 4: try { try decoder.decodeSingularUInt64Field(value: &self.refusedInvalid) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
if self.accepted != 0 {
|
||||
try visitor.visitSingularUInt64Field(value: self.accepted, fieldNumber: 1)
|
||||
}
|
||||
if self.refusedPrivate != 0 {
|
||||
try visitor.visitSingularUInt64Field(value: self.refusedPrivate, fieldNumber: 2)
|
||||
}
|
||||
if self.refusedBlocked != 0 {
|
||||
try visitor.visitSingularUInt64Field(value: self.refusedBlocked, fieldNumber: 3)
|
||||
}
|
||||
if self.refusedInvalid != 0 {
|
||||
try visitor.visitSingularUInt64Field(value: self.refusedInvalid, fieldNumber: 4)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_SnapshotResult, rhs: Directory_SnapshotResult) -> Bool {
|
||||
if lhs.accepted != rhs.accepted {return false}
|
||||
if lhs.refusedPrivate != rhs.refusedPrivate {return false}
|
||||
if lhs.refusedBlocked != rhs.refusedBlocked {return false}
|
||||
if lhs.refusedInvalid != rhs.refusedInvalid {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_Instance: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".Instance"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}name\0\u{1}feeds\0\u{1}subscribers\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeSingularStringField(value: &self.name) }()
|
||||
case 2: try { try decoder.decodeSingularInt64Field(value: &self.feeds) }()
|
||||
case 3: try { try decoder.decodeSingularInt64Field(value: &self.subscribers) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
if !self.name.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
|
||||
}
|
||||
if self.feeds != 0 {
|
||||
try visitor.visitSingularInt64Field(value: self.feeds, fieldNumber: 2)
|
||||
}
|
||||
if self.subscribers != 0 {
|
||||
try visitor.visitSingularInt64Field(value: self.subscribers, fieldNumber: 3)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_Instance, rhs: Directory_Instance) -> Bool {
|
||||
if lhs.name != rhs.name {return false}
|
||||
if lhs.feeds != rhs.feeds {return false}
|
||||
if lhs.subscribers != rhs.subscribers {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_Instances: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".Instances"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
if !self.items.isEmpty {
|
||||
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_Instances, rhs: Directory_Instances) -> Bool {
|
||||
if lhs.items != rhs.items {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_Blocked: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".Blocked"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}url\0\u{1}title\0\u{1}at\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
|
||||
case 2: try { try decoder.decodeSingularStringField(value: &self._url) }()
|
||||
case 3: try { try decoder.decodeSingularStringField(value: &self._title) }()
|
||||
case 4: try { try decoder.decodeSingularInt64Field(value: &self.at) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every if/case branch local when no optimizations
|
||||
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
|
||||
// https://github.com/apple/swift-protobuf/issues/1182
|
||||
if !self.id.isEmpty {
|
||||
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
|
||||
}
|
||||
try { if let v = self._url {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
|
||||
} }()
|
||||
try { if let v = self._title {
|
||||
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
|
||||
} }()
|
||||
if self.at != 0 {
|
||||
try visitor.visitSingularInt64Field(value: self.at, fieldNumber: 4)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_Blocked, rhs: Directory_Blocked) -> Bool {
|
||||
if lhs.id != rhs.id {return false}
|
||||
if lhs._url != rhs._url {return false}
|
||||
if lhs._title != rhs._title {return false}
|
||||
if lhs.at != rhs.at {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Directory_BlockedList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
||||
static let protoMessageName: String = _protobuf_package + ".BlockedList"
|
||||
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0")
|
||||
|
||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
||||
// The use of inline closures is to circumvent an issue where the compiler
|
||||
// allocates stack space for every case branch when no optimizations are
|
||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
||||
switch fieldNumber {
|
||||
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
||||
if !self.items.isEmpty {
|
||||
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1)
|
||||
}
|
||||
try unknownFields.traverse(visitor: &visitor)
|
||||
}
|
||||
|
||||
static func ==(lhs: Directory_BlockedList, rhs: Directory_BlockedList) -> Bool {
|
||||
if lhs.items != rhs.items {return false}
|
||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
||||
return true
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -13,12 +13,6 @@ settings:
|
||||
SWIFT_VERSION: "5.9"
|
||||
TARGETED_DEVICE_FAMILY: "1,2"
|
||||
CODE_SIGN_STYLE: Automatic
|
||||
packages:
|
||||
# The app's half of ipx's protobuf (#469). The same version as the protoc-gen-swift that made
|
||||
# Sources/Wire (scripts/proto.sh), whose code refuses another.
|
||||
SwiftProtobuf:
|
||||
url: https://github.com/apple/swift-protobuf
|
||||
exactVersion: 1.41.0
|
||||
targets:
|
||||
iPX:
|
||||
type: application
|
||||
@@ -29,13 +23,12 @@ targets:
|
||||
- Resources/Assets.xcassets
|
||||
dependencies:
|
||||
- target: iPXWidgets
|
||||
- package: SwiftProtobuf
|
||||
info:
|
||||
path: Resources/Info.plist
|
||||
properties:
|
||||
CFBundleDisplayName: iPX
|
||||
CFBundleShortVersionString: $(MARKETING_VERSION)
|
||||
CFBundleVersion: "15"
|
||||
CFBundleVersion: "14"
|
||||
# Playing on with the screen locked. A plist key, not a signed entitlement.
|
||||
UIBackgroundModes: [audio, fetch, remote-notification]
|
||||
# The unread badge's refresh while the app is closed (#421).
|
||||
@@ -114,7 +107,7 @@ targets:
|
||||
properties:
|
||||
CFBundleDisplayName: iPX
|
||||
CFBundleShortVersionString: $(MARKETING_VERSION)
|
||||
CFBundleVersion: "15"
|
||||
CFBundleVersion: "14"
|
||||
NSExtension:
|
||||
NSExtensionPointIdentifier: com.apple.widgetkit-extension
|
||||
entitlements:
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/bin/sh
|
||||
# The app's protobuf messages (#469), generated from the .proto files ipx serves them by
|
||||
# (crates/wire/proto) into Sources/Wire, which is committed: XcodeGen and Xcode build it as it is,
|
||||
# with no protoc in the build. Run again after a change to those files. Needs protoc and
|
||||
# protoc-gen-swift, the generator at the version of the SwiftProtobuf package in project.yml, which
|
||||
# refuses code from another: on a Mac `brew install protobuf swift-protobuf`, here /src/install.sh.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
proto=../crates/wire/proto
|
||||
rm -f Sources/Wire/*.pb.swift
|
||||
protoc -I "$proto" --swift_out=Sources/Wire --swift_opt=Visibility=Internal "$proto/ipx.proto" "$proto/directory.proto"
|
||||
protoc-gen-swift --version
|
||||
@@ -12,7 +12,7 @@ set -eu
|
||||
|
||||
MEM=6g # the builder's memory cap (Tower has no swap to spill into)
|
||||
CPUS=0-5 # six of twelve threads; cargo inside sees six and runs six jobs
|
||||
NEED_KB=$((6 * 1024 * 1024)) # the cap; the cgroup kills a build that outgrows it
|
||||
NEED_KB=$((9 * 1024 * 1024)) # the cap plus 3 GB for everything else
|
||||
MAX_LOAD=12
|
||||
BUILDER=ipx-capped
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ function makeContext(html: string, script: string, { media = false } = {}) {
|
||||
localStorage: { getItem: () => null, setItem(){}, removeItem(){} },
|
||||
navigator: { clipboard: undefined, sendBeacon(){}, mediaSession: undefined },
|
||||
fetch: (url: unknown) => Promise.resolve({
|
||||
ok: true, status: 200, headers: new Headers({ 'Content-Type': 'application/json' }), text: () => Promise.resolve(''),
|
||||
ok: true, status: 200, text: () => Promise.resolve(''),
|
||||
json: () => Promise.resolve(
|
||||
String(url).includes('/api/settings')
|
||||
? { schedule: 'every 60m', every_mins: 60, download_dir: '/tmp', max_total_gb: 0, max_age_days: 0 }
|
||||
@@ -75,7 +75,7 @@ function makeContext(html: string, script: string, { media = false } = {}) {
|
||||
: /\/api\/(popular|directory)/.test(String(url))
|
||||
? [{ id: 'f', title: 'A Feed', image: null, subscribers: 2, subscribed: true },
|
||||
{ id: 'g', title: null, image: null, subscribers: 1, subscribed: false }]
|
||||
: /entries|\/api\/queue/.test(String(url)) ? { total: 0, entries: [] } : []),
|
||||
: /entries/.test(String(url)) ? { total: 0, entries: [] } : []),
|
||||
}),
|
||||
EventSource: class { close() {} },
|
||||
MediaMetadata: class {},
|
||||
|
||||
@@ -230,21 +230,6 @@ ctx.window.ipxNative.on({ t: 'nowPlaying', feedId: 'f', guid: 'g2', enc: 7, titl
|
||||
playing: false, cur: 130 });
|
||||
ok(audio.paused === true && audio.currentTime === 130, 'told again on coming forward, the bar did not follow');
|
||||
|
||||
// Up Next (#473): the app is told what follows, to play it with the screen locked, and taking it
|
||||
// up from nowPlaying takes it out of Up Next.
|
||||
const queued = { feed_id: 'f', guid: 'n1', title: 'Next One', position: 0, duration: 60, image: null,
|
||||
enclosures: [{ id: 9, mime: 'audio/mpeg', path: '/n.mp3', url: 'http://x/n.mp3' }] };
|
||||
since();
|
||||
vm.runInContext(`upNext=[${JSON.stringify(queued)}]; hostNext()`, ctx);
|
||||
ok(!last('next'), 'an app that never said it can was told what follows');
|
||||
ctx.window.ipxNative.on({ t: 'host', can: ['next'] });
|
||||
ok(last('next')?.guid === 'n1' && last('next')?.enc === 9 && last('next')?.url === '/media/9', 'the app was not told what plays next');
|
||||
ctx.window.ipxNative.on({ t: 'nowPlaying', feedId: 'f', guid: 'n1', enc: 9, title: 'Next One', feedTitle: 'A Feed',
|
||||
playing: true, cur: 0, dur: 60 });
|
||||
ok(vm.runInContext('player.guid', ctx) === 'n1', 'the bar did not take up the next one');
|
||||
ok(vm.runInContext('upNext.length', ctx) === 0, 'the one under way is still in Up Next');
|
||||
ok(!!last('next') && !last('next')?.guid, 'the app was not told nothing follows');
|
||||
|
||||
if (failed) { console.error(`\n${failed} failed`); process.exit(1); }
|
||||
console.log('OK: native-bridge: the host takes playback, keeping, the sleep timer, haptics and Up Next, and the page follows it');
|
||||
console.log('OK: native-bridge: the host takes playback, keeping, the sleep timer and haptics, and the page follows it');
|
||||
process.exit(0);
|
||||
|
||||
@@ -28,28 +28,6 @@ test('esc makes text safe to put in markup and attributes', () => {
|
||||
assert.equal(run('esc(undefined)'), '');
|
||||
});
|
||||
|
||||
test('names sort as a shelf files them, a leading The, A or An aside (#481)', () => {
|
||||
const names = ['The Rest Is Science', 'science weekly', 'Theory of Everything', 'Episode 10', 'Episode 2', 'the Daily', 'Radiolab',
|
||||
'A Question of Science', 'An Hour', 'Anchor', 'Abba'];
|
||||
// As JSON: an array from the page's VM is of another realm, which deepEqual tells apart.
|
||||
assert.deepEqual(JSON.parse(run(`JSON.stringify(${JSON.stringify(names)}.sort(nameOrder))`)),
|
||||
['Abba', 'Anchor', 'the Daily', 'Episode 2', 'Episode 10', 'An Hour', 'A Question of Science', 'Radiolab',
|
||||
'The Rest Is Science', 'science weekly', 'Theory of Everything']);
|
||||
});
|
||||
|
||||
test('a podcast gets its seasons only when most of it is in two or more (#482)', () => {
|
||||
const shown = (list: object) => run(`seasonsShown(${JSON.stringify(list)})`);
|
||||
const s = (season: number | null, episodes: number) => ({ season, episodes, unread: 0 });
|
||||
assert.equal(shown([s(6, 25), s(5, 40), s(1, 30)]), true, 'Oxide and Friends');
|
||||
assert.equal(shown([s(7, 40), s(1, 30), s(null, 3)]), true, 'a few trailers aside');
|
||||
assert.equal(shown([s(232, 1), s(225, 1), s(null, 364)]), false, 'two numbered of 366');
|
||||
assert.equal(shown([s(2023, 150), s(12026, 44), s(null, 573)]), false, 'years on a quarter of them');
|
||||
assert.equal(shown([s(1, 40)]), false, 'one season is no choice');
|
||||
assert.equal(shown([{ episodes: 3, unread: 0 }, s(2, 2), s(1, 2)]), true, 'none sent as absent, as protobuf does');
|
||||
assert.equal(run('seasonName(null)'), 'Other episodes');
|
||||
assert.equal(run('seasonName(3)'), 'Season 3');
|
||||
});
|
||||
|
||||
test('webUrl keeps only web addresses from a feed', () => {
|
||||
assert.equal(run(`webUrl('https://example.com/a')`), 'https://example.com/a');
|
||||
assert.equal(run(`webUrl('HTTP://example.com/')`), 'HTTP://example.com/');
|
||||
@@ -86,15 +64,6 @@ test('ago says how long since, and never for nothing', () => {
|
||||
assert.match(run(`ago(${NOW - 90 * 86400})`), /2026/);
|
||||
});
|
||||
|
||||
test('a row date is short: the time today, the day this year, the month before (#508)', () => {
|
||||
const now = 'new Date(2026, 11, 3, 15, 0)';
|
||||
assert.match(run(`rowDate(new Date(2026, 11, 3, 9, 36).getTime()/1000, ${now})`), /9:36/);
|
||||
const day = run(`rowDate(new Date(2026, 10, 20).getTime()/1000, ${now})`);
|
||||
assert.match(day, /20/); assert.doesNotMatch(day, /2026/);
|
||||
assert.match(run(`rowDate(new Date(2025, 4, 2).getTime()/1000, ${now})`), /2025/);
|
||||
assert.equal(run('rowDate(null)'), '');
|
||||
});
|
||||
|
||||
test('due says how long until a feed is checked', () => {
|
||||
assert.equal(run(`due(${NOW - 1})`), 'due now');
|
||||
assert.equal(run(`due(${NOW + 10})`), 'in 1m');
|
||||
@@ -150,15 +119,6 @@ test('an item without a title is named by its file', () => {
|
||||
assert.deepEqual({ ...name({ enclosures: [{ url: 'https://x/100%.mp3' }] }) }, { text: '100%', derived: true });
|
||||
});
|
||||
|
||||
test('a title that only opens the text is not shown above it again (#502)', () => {
|
||||
const echoes = (e: object, words: string) => run(`titleEchoes(${JSON.stringify(e)}, ${JSON.stringify(words)})`);
|
||||
assert.equal(echoes({ title: 'Hello there' }, 'Hello there'), true);
|
||||
assert.equal(echoes({ title: 'A long post cut\u2026' }, 'A long post cut short here'), true);
|
||||
assert.equal(echoes({ title: 'Episode 1' }, 'In this episode we talk'), false);
|
||||
assert.equal(echoes({ title: 'Anything' }, ''), false);
|
||||
assert.equal(echoes({}, 'Words'), false);
|
||||
});
|
||||
|
||||
test('the directory sorts by name as people read, and by subscribers', () => {
|
||||
const sorted = (list: object[], by: string) => run(`${JSON.stringify(list)}.sort(${by}).map(p => p.title)`);
|
||||
assert.deepEqual([...sorted([{ title: 'ep 10' }, { title: 'Ep 2' }, { title: 'ep 1' }], 'byName')], ['ep 1', 'Ep 2', 'ep 10']);
|
||||
@@ -279,7 +239,7 @@ test('Signals are everyone\'s on the server\'s key, and yours on your own once a
|
||||
});
|
||||
|
||||
test('a tap is its trace\'s root span, reported with its ids once it has an answer (#376)', () => {
|
||||
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
|
||||
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
|
||||
run(`newTrace('pointerdown'); traceAt = Date.now()`);
|
||||
const [, trace, parent] = run('traceparent()').split('-');
|
||||
assert.equal(parent, run('rootId'), 'requests hang from the tap');
|
||||
@@ -293,7 +253,7 @@ test('a tap is its trace\'s root span, reported with its ids once it has an answ
|
||||
});
|
||||
|
||||
test('a request begun long after a tap\'s last answer does not stretch the tap (#379)', async () => {
|
||||
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
|
||||
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
|
||||
run(`newTrace('pointerdown'); traceAt = Date.now()`);
|
||||
await run(`api('/api/a')`);
|
||||
const answered = run('answeredAt');
|
||||
@@ -306,7 +266,7 @@ test('a request begun long after a tap\'s last answer does not stretch the tap (
|
||||
});
|
||||
|
||||
test('a tap ended over a minute after its last request reports once, without recursing (#378)', () => {
|
||||
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
|
||||
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
|
||||
run(`newTrace('pointerdown'); answeredAt = rootAt + 100; traceAt = Date.now() - 120_000`);
|
||||
run('endTap()');
|
||||
assert.equal(run(`sent.filter(([u, o]) => JSON.parse(o.body).ev === 'tap').length`), 1);
|
||||
@@ -376,7 +336,7 @@ test('Share says why an episode gets no page anyone can play, and warns of a key
|
||||
const note = (why: string | null, url: string) => run(`noLinkNote(${JSON.stringify(why)}, ${JSON.stringify(url)})`) as string;
|
||||
const paid = 'https://c10.patreonusercdn.com/ep.mp3?token-hash=abc';
|
||||
assert.match(note('private', paid), /private to you.*includes your own access/s);
|
||||
assert.match(note('failed', 'https://example.com/ep.mp3'), /Unable to make a page anyone can play just now/);
|
||||
assert.match(note('failed', 'https://example.com/ep.mp3'), /could not be made just now/);
|
||||
assert.doesNotMatch(note('failed', 'https://example.com/ep.mp3'), /own access/);
|
||||
// A server with no ipx-play shares as it always has, with no reason to give.
|
||||
assert.equal(note('not_set_up', 'https://example.com/ep.mp3'), '');
|
||||
@@ -397,7 +357,7 @@ test('a file\'s box says where it is: the publisher, on its way, iPX, this devic
|
||||
const where = (x: object) => run(`whereText(${JSON.stringify({ id: 7, deadair: 0, path: null, state: 'held', ...x })})`) as string;
|
||||
assert.equal(where({}), 'Publisher only');
|
||||
assert.equal(where({ state: 'pending' }), 'Queued for iPX');
|
||||
assert.equal(where({ state: 'error' }), 'Unable to download to iPX');
|
||||
assert.equal(where({ state: 'error' }), 'iPX could not download it');
|
||||
run(`want(7, 'Ep')`);
|
||||
assert.equal(where({ state: 'pending' }), 'Downloading to iPX, then this device');
|
||||
run('unwant(7)');
|
||||
@@ -408,34 +368,3 @@ test('a file\'s box says where it is: the publisher, on its way, iPX, this devic
|
||||
assert.equal(where({ state: 'reaped' }), 'On this device');
|
||||
run('kept.clear()');
|
||||
});
|
||||
|
||||
test('wireDecode reads protobuf into what the JSON would have been (#470)', () => {
|
||||
// A browser has TextDecoder; the stub's sandbox does not, and the page makes one only to decode.
|
||||
ctx.TextDecoder = TextDecoder;
|
||||
const dec = (type: string, bytes: number[]) => run(`wireDecode(${JSON.stringify(type)}, new Uint8Array(${JSON.stringify(bytes)}))`);
|
||||
assert.deepEqual({ ...dec('ipx.Marked', [0x08, 0xac, 0x02]) }, { marked: 300 }, 'a varint over a byte');
|
||||
assert.equal(dec('ipx.SignalId', [0x08, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1]).id, -1, 'a negative int64');
|
||||
assert.equal(dec('ipx.Marked', []).marked, 0, 'a field at its default is not sent');
|
||||
// A field this page does not know, as from a newer server, is passed over.
|
||||
assert.equal(dec('ipx.Marked', [0x4a, 0x01, 0x78, 0x08, 0x05]).marked, 5);
|
||||
const rows = dec('ipx.FeedRows', [0x0a, 0x03, 0x0a, 0x01, 0x61]);
|
||||
assert.ok(Array.isArray(rows) && rows.length === 1, 'a list message is its array');
|
||||
assert.equal(rows[0].id, 'a');
|
||||
assert.equal(rows[0].title, null, 'an optional not sent is null, as JSON had it');
|
||||
assert.equal(rows[0].failing, null, 'so is a message');
|
||||
assert.deepEqual([...rows[0].keywords], []);
|
||||
assert.equal(rows[0].pinned, false);
|
||||
assert.equal(dec('ipx.Settings', [0x31, 0, 0, 0, 0, 0, 0, 0xf8, 0x3f]).max_total_gb, 1.5, 'a double');
|
||||
assert.equal(run(`wireType('application/x-protobuf; messageType=ipx.FeedRows')`), 'ipx.FeedRows');
|
||||
assert.equal(run(`wireType('application/json')`), undefined);
|
||||
});
|
||||
|
||||
test('nextUp is the first in Up Next that can play, passing over the one playing', () => {
|
||||
const ep = (guid: string, path: string | null) =>
|
||||
({ feed_id: 'f', guid, enclosures: [{ id: 1, mime: 'audio/mpeg', path, url: 'http://x/a.mp3' }] });
|
||||
const list = JSON.stringify([ep('a', '/a.mp3'), ep('b', null), ep('c', '/c.mp3')]);
|
||||
assert.equal(run(`nextUp(${list}, null)?.guid`), 'a');
|
||||
assert.equal(run(`nextUp(${list}, 'f\\na')?.guid`), 'c', 'b is not downloaded yet');
|
||||
assert.equal(run(`nextUp(${list}, 'f\\nc')?.guid`), 'a');
|
||||
assert.equal(run(`nextUp([], null)`), undefined);
|
||||
});
|
||||
|
||||
@@ -10,8 +10,6 @@ import type { Locator, Page, Request } from '@playwright/test';
|
||||
declare global {
|
||||
interface Window { started: string[]; done: boolean; shared: ShareData[] }
|
||||
}
|
||||
/// Answers the page's own question (#462): yes, or Cancel.
|
||||
const answer = (page: Page, yes = true) => page.locator(`dialog.ask [value="${yes ? 'y' : ''}"]`).click();
|
||||
/// What a failed `ipx` command said, from execFileSync's error.
|
||||
const said = (e: unknown) => { const x = e as { stderr?: unknown, stdout?: unknown }; return String(x.stderr || x.stdout); };
|
||||
|
||||
@@ -53,22 +51,12 @@ test.beforeEach(async ({ page }) => {
|
||||
await expect(page.locator('#feedlist')).toBeVisible();
|
||||
});
|
||||
|
||||
test('a toolbar button that cannot act says why, and its usual tooltip comes back when it can (#507)', async ({ page }) => {
|
||||
await page.locator('#feedlist .place', { hasText: 'All Subscriptions' }).click();
|
||||
await expect(page.locator('#tbRemove')).toBeDisabled();
|
||||
await expect(page.locator('#tbRemove')).toHaveAttribute('title', 'Open a feed to unsubscribe from it');
|
||||
await expect(page.locator('#tbRead')).toHaveAttribute('title', 'Choose an item first');
|
||||
await page.locator('#feedlist .feed', { hasText: 'Test Show' }).click();
|
||||
await expect(page.locator('#tbRemove')).toBeEnabled();
|
||||
await expect(page.locator('#tbRemove')).toHaveAttribute('title', 'Unsubscribe from this feed');
|
||||
});
|
||||
|
||||
test('the page loads and lists the configured feeds', async ({ page }) => {
|
||||
// Regression: a ReferenceError in the script left the shell rendered and the sidebar
|
||||
// empty, with every handler below the error dead. Server-side checks all passed.
|
||||
// Six top-level feeds in the fixture config, the season one's (#482) among them; the OPML's
|
||||
// children are inside a closed folder. The Signals folder is above them, and no feed.
|
||||
await expect(page.locator('.feed:not(.sigs):not(.plists)')).toHaveCount(6, { timeout: 15_000 });
|
||||
// Four top-level feeds in the fixture config; the OPML's children are inside a closed folder.
|
||||
// The Signals folder is above them, and no feed.
|
||||
await expect(page.locator('.feed:not(.sigs)')).toHaveCount(5, { timeout: 15_000 });
|
||||
await expect(page.locator('.feed', { hasText: 'Test Show' })).toBeVisible();
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', e => errors.push(e.message));
|
||||
@@ -435,139 +423,6 @@ test('Currently Listening, its own place below the Directory, resumes an episode
|
||||
await expect(row.locator('.eq')).toBeHidden();
|
||||
});
|
||||
|
||||
test('Up Next lines episodes up, moves them, and plays the next when one ends (#473)', async ({ page }) => {
|
||||
await page.evaluate(() => saveUpNext([]));
|
||||
await page.locator('.feed', { hasText: 'Test Show' }).click();
|
||||
for (const name of ['First Episode', 'Second Episode']) {
|
||||
const ep = page.locator('#eps .ep', { hasText: name });
|
||||
await ep.hover();
|
||||
await ep.locator('[data-a=queue]').click();
|
||||
await expect(ep.locator('[data-a=queue]')).toHaveAttribute('aria-pressed', 'true');
|
||||
}
|
||||
const place = page.locator('#feedlist .place', { hasText: 'Up Next' });
|
||||
await expect(place.locator('.badge')).toHaveText('2');
|
||||
|
||||
await place.click();
|
||||
const rows = page.locator('#listening .childrow .txt b');
|
||||
await expect(rows).toHaveText(['First Episode', 'Second Episode']);
|
||||
// Moved by its handle's arrow keys, and kept so on the server.
|
||||
await page.locator('#listening .childrow', { hasText: 'Second Episode' }).locator('.grip').press('ArrowUp');
|
||||
await expect(rows).toHaveText(['Second Episode', 'First Episode']);
|
||||
await expect.poll(() => page.evaluate(async () => (await api('/api/queue')).entries.map((e: Entry) => e.guid)))
|
||||
.toEqual(['ui-2', 'ui-1']);
|
||||
|
||||
// Playing one takes it out; the end of it plays the next.
|
||||
await page.locator('#listening .childrow', { hasText: 'Second Episode' }).click();
|
||||
await expect(page.locator('#ptitle')).toHaveText('Second Episode');
|
||||
await expect(rows).toHaveText(['First Episode']);
|
||||
await expect(page.locator('#pnext')).toBeVisible();
|
||||
// The fixture files are not real audio, so the end is said rather than played to.
|
||||
await page.evaluate(() => audio.dispatchEvent(new Event('ended')));
|
||||
await expect(page.locator('#ptitle')).toHaveText('First Episode', { timeout: 20_000 });
|
||||
await expect(page.locator('#listening')).toContainText('Nothing lined up');
|
||||
await expect(page.locator('#pnext')).toBeHidden();
|
||||
|
||||
await page.locator('#pclose').click();
|
||||
await page.evaluate(() => api('/api/entries/test-show/ui-1/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) }));
|
||||
await page.evaluate(() => api('/api/entries/test-show/ui-2/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) }));
|
||||
});
|
||||
|
||||
test('the Podcasts shelf shows the feeds with episodes, as their artwork, and opens one (#474)', async ({ page }) => {
|
||||
await page.locator('#feedlist .place', { hasText: 'Podcasts' }).click();
|
||||
const shows = page.locator('#content .shelf .show');
|
||||
await expect(shows.filter({ hasText: 'Test Show' })).toBeVisible();
|
||||
// A blog of pictures has files, and no episodes.
|
||||
await expect(shows.filter({ hasText: 'Picture Blog' })).toHaveCount(0);
|
||||
await page.locator('#epSearch').fill('multi');
|
||||
await expect(shows).toHaveText([/Multi Show/]);
|
||||
await page.locator('#epSearch').fill('');
|
||||
await shows.filter({ hasText: 'Test Show' }).click();
|
||||
await expect(page.locator('#eps .ep', { hasText: 'First Episode' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('Now Playing opens from the player bar with the artwork, show notes and Up Next (#475)', async ({ page }) => {
|
||||
await page.evaluate(() => saveUpNext([]));
|
||||
await page.locator('.feed', { hasText: 'Test Show' }).click();
|
||||
const first = page.locator('#eps .ep', { hasText: 'First Episode' });
|
||||
await first.hover();
|
||||
await first.locator('[data-a=queue]').click();
|
||||
const second = page.locator('#eps .ep', { hasText: 'Second Episode' });
|
||||
await second.hover();
|
||||
await second.locator('[data-a=play]').click();
|
||||
await expect(page.locator('#ptitle')).toHaveText('Second Episode');
|
||||
|
||||
const sheet = page.locator('#nowsheet');
|
||||
await page.locator('#pnow').click();
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(page.locator('#pnow')).toHaveAttribute('aria-expanded', 'true');
|
||||
await expect(sheet.locator('h2')).toHaveText('Second Episode');
|
||||
await expect(sheet.locator('.dbody')).toContainText('Notes for the second.');
|
||||
await expect(sheet.locator('#nowqueue .childrow')).toHaveText([/First Episode/]);
|
||||
// Its chapters, from the file its item names, in order; a tap plays from there (#477).
|
||||
const chapters = sheet.locator('.chapters button');
|
||||
await expect(chapters).toHaveText([/0:00\s*Opening/, /0:01\s*The middle/]);
|
||||
await chapters.nth(1).click();
|
||||
await expect.poll(() => page.evaluate(() => audio.currentTime)).toBeGreaterThanOrEqual(1.4);
|
||||
await expect(chapters.nth(1)).toHaveAttribute('aria-current', 'true');
|
||||
await expect(chapters.nth(0)).not.toHaveAttribute('aria-current');
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(sheet).toBeHidden();
|
||||
// From the keyboard too, and the podcast's name opens its feed.
|
||||
await page.locator('#pnow').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await sheet.locator('.nowshow').click();
|
||||
await expect(sheet).toBeHidden();
|
||||
await expect(page.locator('#eps .ep', { hasText: 'Second Episode' })).toBeVisible();
|
||||
|
||||
await page.locator('#pclose').click();
|
||||
await page.evaluate(() => saveUpNext([]));
|
||||
await page.evaluate(() => api('/api/entries/test-show/ui-2/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) }));
|
||||
});
|
||||
|
||||
test('a smart playlist puts its first podcasts ahead and plays on through itself (#476)', async ({ page }) => {
|
||||
await page.evaluate(() => saveUpNext([]));
|
||||
await page.locator('#feedlist .feed', { hasText: 'Playlists' }).click();
|
||||
await page.locator('#content .acts [data-a="new"]').click();
|
||||
await page.locator('#plname').fill('Commute');
|
||||
await page.locator('[data-in="test-show"]').check();
|
||||
await page.locator('[data-in="multi-show"]').check();
|
||||
await page.locator('[data-first="multi-show"]').check();
|
||||
await page.locator('#plunplayed').uncheck();
|
||||
await page.locator('#plsave').click();
|
||||
|
||||
const rows = page.locator('#listening .childrow .txt b');
|
||||
await expect(rows).toHaveText(['Two Files', 'Second Episode', 'First Episode']);
|
||||
await expect(page.locator('#feedlist .feed.child', { hasText: 'Commute' }).locator('.badge')).toHaveText('3');
|
||||
|
||||
// Both of Test Show's files here, whatever ran before: only a downloaded one plays next.
|
||||
const missing = async () => (await page.evaluate(() => api('/api/feeds/test-show/entries')) as ListPage).entries
|
||||
.flatMap(e => e.enclosures).filter(x => !x.path).map(x => x.id);
|
||||
for (const id of await missing()) await page.evaluate(id => api(`/api/enclosures/${id}/download`, { method: 'POST' }), id);
|
||||
await expect.poll(missing, { timeout: 20_000 }).toEqual([]);
|
||||
await page.locator('#feedlist .feed.child', { hasText: 'Commute' }).click();
|
||||
|
||||
// Played from the playlist, the end of one plays the next in it.
|
||||
await page.locator('#listening .childrow', { hasText: 'Second Episode' }).click();
|
||||
await expect(page.locator('#ptitle')).toHaveText('Second Episode');
|
||||
await expect(page.locator('#pnext')).toBeVisible();
|
||||
await page.evaluate(() => audio.dispatchEvent(new Event('ended')));
|
||||
await expect(page.locator('#ptitle')).toHaveText('First Episode');
|
||||
await page.locator('#pclose').click();
|
||||
|
||||
// Its X marks it played (#497): an onclick of the playlist's own once skipped it.
|
||||
const twoFiles = async () => (await page.evaluate(() => api('/api/feeds/multi-show/entries')) as ListPage).entries
|
||||
.find(e => e.title === 'Two Files')!;
|
||||
await page.locator('#listening .childrow', { hasText: 'Two Files' }).locator('[data-a="remove"]').click();
|
||||
await expect.poll(async () => (await twoFiles()).read).toBe(true);
|
||||
await page.evaluate(e => setRead(e, false), await twoFiles());
|
||||
|
||||
await page.locator('#content .acts [data-a="rm"]').click();
|
||||
await answer(page);
|
||||
await expect(page.locator('#feedlist .feed.child', { hasText: 'Commute' })).toHaveCount(0);
|
||||
for (const g of ['ui-1', 'ui-2'])
|
||||
await page.evaluate(g => api(`/api/entries/test-show/${g}/position`, { method: 'POST', body: JSON.stringify({ secs: 0 }) }), g);
|
||||
});
|
||||
|
||||
test('a player nobody has played since it last saved does not save again', async ({ page }) => {
|
||||
// A tab left paused at 41:15 saved that as it reloaded, over the 32:48 another had reached,
|
||||
// and the episode dropped out of Currently Listening. The fixture audio does not decode, so
|
||||
@@ -672,7 +527,7 @@ test('an OPML subscription is a collapsible folder', async ({ page }) => {
|
||||
const chev = page.locator('.feed.group .chev');
|
||||
await expect(chev).toBeVisible({ timeout: 20_000 });
|
||||
// The Signals folder is a folder too (#255).
|
||||
await expect(page.locator('.feed:not(.group):not(.sigs):not(.plists) .chev')).toHaveCount(0);
|
||||
await expect(page.locator('.feed:not(.group):not(.sigs) .chev')).toHaveCount(0);
|
||||
await expect(chev).toHaveAttribute('aria-expanded', 'false');
|
||||
|
||||
// Closed by default: the children are not listed until the folder is opened.
|
||||
@@ -756,107 +611,6 @@ test('a show inside an OPML can be kept, and only it', async ({ page }) => {
|
||||
await expect(page.locator('#content [data-a="keep"]')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('feeds in every shape are read, and what is no feed is refused saying why (#463)', async ({ page }) => {
|
||||
const F = 'http://127.0.0.1:8792';
|
||||
const add = (url: string) => page.request.post('/api/feeds', { data: { url } });
|
||||
for (const [file, said] of [
|
||||
['said.txt', 'the site sent "Unable to establish a DB connection" instead of a feed'],
|
||||
['long.txt', '…" instead of a feed'],
|
||||
['empty.xml', 'the site sent an empty reply'],
|
||||
['garbled.xml', 'not RSS ('],
|
||||
] as const) {
|
||||
const r = await add(`${F}/${file}`);
|
||||
expect(r.status(), file).toBe(400);
|
||||
expect(await r.text(), file).toContain(said);
|
||||
}
|
||||
|
||||
const ids: Record<string, string> = {};
|
||||
for (const file of ['atom.xml', 'amp.xml', 'wp.json']) {
|
||||
const r = await add(`${F}/${file}`);
|
||||
expect(r.status(), file).toBe(200);
|
||||
ids[file] = (await r.json()).id;
|
||||
}
|
||||
const entries = async (file: string) => ((await (await page.request.get(
|
||||
`/api/feeds/${encodeURIComponent(ids[file]!)}/entries?limit=50`)).json()) as ListPage).entries;
|
||||
const byTitle = async (file: string) => Object.fromEntries((await entries(file)).map(e => [e.title, e]));
|
||||
const feed = async (file: string) => (await (await page.request.get('/api/feeds')).json() as Feed[])
|
||||
.find(f => f.id === ids[file])!;
|
||||
|
||||
// Atom: its title's entity decoded, the player's repeat of one file dropped, Markdown made HTML.
|
||||
await expect.poll(async () => Object.keys(await byTitle('atom.xml')).sort(), { timeout: 20_000 })
|
||||
.toEqual(['Markdown entry', 'Q&A in Atom']);
|
||||
const atom = await byTitle('atom.xml');
|
||||
expect(atom['Q&A in Atom']!.enclosures).toHaveLength(1);
|
||||
expect(atom['Q&A in Atom']!.description).toContain('<b>notes</b>');
|
||||
expect(atom['Markdown entry']!.description).toContain('<strong>bold</strong>');
|
||||
expect((await feed('atom.xml')).title).toBe('Atom’s Show');
|
||||
|
||||
// A bare "&" read after all, with the iTunes and Media RSS fields.
|
||||
await expect.poll(async () => Object.keys(await byTitle('amp.xml')).length, { timeout: 20_000 }).toBe(3);
|
||||
const amp = await byTitle('amp.xml');
|
||||
expect(amp['Tom & Jerry']!.duration).toBe(3723);
|
||||
expect(amp['Tom & Jerry']!.image).toBe(`${F}/art2.jpg`);
|
||||
expect(amp['Tom & Jerry']!.description).toMatch(/^<p><em>A subtitle not in the body<\/em><\/p>/);
|
||||
expect(amp['Cut body']!.description).toBe('The whole description');
|
||||
expect(amp['Cut body']!.image).toBe(`${F}/pic.png`);
|
||||
expect(amp['Picture only']!.image).toBe(`${F}/amp-pic.png`);
|
||||
expect((await feed('amp.xml')).feed_category).toBe('Games');
|
||||
|
||||
// WordPress.com's posts, as its API sends them, read as a feed.
|
||||
await expect.poll(async () => Object.keys(await byTitle('wp.json')), { timeout: 20_000 })
|
||||
.toEqual(['WordPress “post”']);
|
||||
|
||||
for (const id of Object.values(ids)) await page.request.delete(`/api/feeds/${encodeURIComponent(id)}`);
|
||||
});
|
||||
|
||||
test('a feed that starts failing says why, and after a day in words with something to do (#463)', async ({ page }) => {
|
||||
const F = 'http://127.0.0.1:8792';
|
||||
const flip = (to: string) => page.request.get(`${F}/flip?to=${to}`);
|
||||
await flip('ok');
|
||||
const id = (await (await page.request.post('/api/feeds', { data: { url: `${F}/flip.xml` } })).json()).id as string;
|
||||
const feed = async () => (await (await page.request.get('/api/feeds')).json() as Feed[]).find(f => f.id === id)!;
|
||||
await expect.poll(async () => (await feed()).entries, { timeout: 20_000 }).toBe(1);
|
||||
const db = path.join(setup.root, 'data', 'state.db');
|
||||
try {
|
||||
for (const [to, error, reason] of [
|
||||
['404', /HTTP 404/, 'took this feed down'],
|
||||
['403', /HTTP 403/, 'refuses'],
|
||||
['402', /HTTP 402/, 'paid plan'],
|
||||
['500', /HTTP 500/, null],
|
||||
['text', /the site sent/, 'sent a message'],
|
||||
['page', /got a web page, not a feed; it links .*moved\.xml/, 'The feed moved'],
|
||||
['garbled', /not RSS/, null],
|
||||
['loop', /redirect/i, null],
|
||||
['drop', /./, null],
|
||||
] as const) {
|
||||
await flip(to);
|
||||
await page.request.post('/api/fetch', { data: { feed: id, force: true } });
|
||||
await expect.poll(async () => (await feed()).last_error ?? '', { timeout: 20_000 }).toMatch(error);
|
||||
// A day in, which is when the page names a failure in words.
|
||||
execFileSync('sqlite3', [db, `UPDATE feeds SET error_since = ${Math.floor(Date.now() / 1000) - 2 * 86_400} WHERE id = '${id}'`]);
|
||||
const f = await feed();
|
||||
if (reason) expect(f.failing?.reason, to).toContain(reason);
|
||||
else expect(f.failing, to).toBeNull();
|
||||
if (to === 'page') {
|
||||
expect(f.failing?.new_url).toBe(`${F}/moved.xml`);
|
||||
await page.reload();
|
||||
await page.locator('#feedlist .feed', { hasText: 'Flip Show' }).click();
|
||||
await expect(page.locator('#content .fail')).toContainText('The feed moved');
|
||||
await expect(page.locator('#content [data-ffail="newurl"]')).toBeVisible();
|
||||
}
|
||||
}
|
||||
// Back again, from the address it moved to for good: the error goes, and the feed is read
|
||||
// from there from now on.
|
||||
await flip('moved');
|
||||
await page.request.post('/api/fetch', { data: { feed: id, force: true } });
|
||||
await expect.poll(async () => (await feed()).last_error, { timeout: 20_000 }).toBeNull();
|
||||
await expect.poll(async () => (await feed()).url, { timeout: 20_000 }).toBe(`${F}/moved.xml`);
|
||||
} finally {
|
||||
await flip('ok');
|
||||
await page.request.delete(`/api/feeds/${encodeURIComponent(id)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('an item sent as HTML and Markdown switches between them', async ({ page }) => {
|
||||
const api = (p: string, init?: { method?: string, body?: string }) => page.evaluate(([p, init]) => fetch(p, { headers: { 'Content-Type': 'application/json' }, ...init })
|
||||
.then((r) => r.json().catch(() => null)), [p, init] as const);
|
||||
@@ -1111,15 +865,18 @@ test('deleting a shared file warns that it is everyone\'s copy', async ({ page }
|
||||
const del = page.locator('#modalCard [data-m="del"]');
|
||||
await expect(del).toHaveText(/^Delete from iPX, for everyone \(shared with 1 other person/);
|
||||
|
||||
// Two questions: the page's own, then the server's, because someone else has not played
|
||||
// it. Yes to the first, Cancel to the second, and the file must survive.
|
||||
// Two prompts: the page's own, then the server's, because someone else has not played
|
||||
// it. Accept the first, decline the second, and the file must survive.
|
||||
const seen: string[] = [];
|
||||
page.on('dialog', d => {
|
||||
seen.push(d.message());
|
||||
if (seen.length === 1) d.accept();
|
||||
else d.dismiss();
|
||||
});
|
||||
await del.click();
|
||||
const ask = page.locator('dialog.ask');
|
||||
await expect(ask).toContainText('shared with 1 other person');
|
||||
await answer(page);
|
||||
await expect(ask).toContainText('one copy of this file');
|
||||
await answer(page, false);
|
||||
await expect(ask).toHaveCount(0);
|
||||
await expect.poll(() => seen.length, { timeout: 10_000 }).toBe(2);
|
||||
expect(seen[0]).toContain('shared with 1 other person');
|
||||
expect(seen[1]).toContain('one copy of this file');
|
||||
|
||||
await page.reload();
|
||||
await page.locator('.feed', { hasText: 'Test Show' }).click();
|
||||
@@ -1156,8 +913,8 @@ test('an admin adds someone, makes them an admin, and removes them', async ({ pa
|
||||
(await (await page.request.get('/api/users')).json()).find((u: Account) => u.name === 'pat')?.admin
|
||||
).toBe(true);
|
||||
|
||||
page.once('dialog', d => d.accept());
|
||||
await row.locator('[data-a="rm"]').click();
|
||||
await answer(page);
|
||||
await expect(row).toHaveCount(0);
|
||||
});
|
||||
|
||||
@@ -1272,43 +1029,6 @@ test('an export from one account imports into another', async ({ page, browser }
|
||||
await ctx.close();
|
||||
});
|
||||
|
||||
test('ipxd user adds, lists, renames and removes accounts, and says what is wrong (#463)', async () => {
|
||||
// Its own database, as the import test has, so the suite's accounts are not touched.
|
||||
const dir = path.join(setup.root, 'cli-users');
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
fs.mkdirSync(path.join(dir, 'data'), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'config.toml'),
|
||||
`[general]\ndownload_dir = "${dir}/downloads"\nsocket = "${dir}/ipx.sock"\nfetch_internal = ["127.0.0.1"]\n`);
|
||||
const env = { ...process.env, IPX_CONFIG: path.join(dir, 'config.toml'), IPX_DATA_DIR: path.join(dir, 'data') };
|
||||
const cli = (args: string[]) => execFileSync(setup.IPX_BIN, args, { env, encoding: 'utf8' });
|
||||
const ipx = (args: string[], input = '') => execFileSync(setup.IPX_BIN, ['user', ...args], { env, input, encoding: 'utf8' });
|
||||
const fails = (args: string[], input = '') => { try { ipx(args, input); } catch (e) { return said(e); } throw new Error(`${args} succeeded`); };
|
||||
|
||||
expect(ipx(['list'])).toContain('no accounts yet');
|
||||
expect(fails(['add', 'ada'])).toContain('no password on stdin');
|
||||
expect(fails(['add', ' '])).toContain('a name is required');
|
||||
expect(ipx(['add', 'Ada'], 'adapassword\n')).toBe('added ada (admin)\n');
|
||||
expect(fails(['add', 'ada'], 'x')).toContain('ada already exists');
|
||||
expect(ipx(['add', 'bo', '--no-password'])).toBe('added bo, signs in through the proxy\n');
|
||||
const list = ipx(['list']);
|
||||
expect(list).toMatch(/^ada\s+admin\s+password\s+added \d{4}-\d\d-\d\d\s+never signed in$/m);
|
||||
expect(list).toMatch(/^bo\s+proxy only\s+added /m);
|
||||
|
||||
expect(ipx(['passwd', 'ada'], 'newpassword')).toContain('password changed for ada');
|
||||
expect(fails(['passwd', 'nobody'], 'x')).toContain('no such account: nobody');
|
||||
expect(fails(['rename', 'bo', 'b;o'])).toContain('not a usable name');
|
||||
expect(fails(['rename', 'bo', 'ada'])).toContain('ada already exists');
|
||||
expect(ipx(['rename', 'bo', 'bea'])).toBe('renamed bo to bea\n');
|
||||
expect(ipx(['rm', 'bea'])).toBe('removed bea\n');
|
||||
expect(fails(['rm', 'bea'])).toContain('no such account: bea');
|
||||
expect(ipx(['list'])).not.toContain('bea');
|
||||
|
||||
// ipxd list: the feeds, each with its id on a line of its own.
|
||||
expect(cli(['list'])).toContain('No feeds configured');
|
||||
cli(['add', 'http://127.0.0.1:8792/cli.xml']);
|
||||
expect(cli(['list'])).toMatch(/^ {4}id {11}\S+\n {4}url {10}http:\/\/127\.0\.0\.1:8792\/cli\.xml\n {4}last checked never$/m);
|
||||
});
|
||||
|
||||
test('ipxd import subscribes the admin, and ipxd export writes the feeds out', async () => {
|
||||
// Its own config and database. The CLI works in-process, and the suite's running daemon
|
||||
// reads config.toml once at start, so it would not see what the CLI added anyway.
|
||||
@@ -1628,7 +1348,7 @@ test('a download by hand fills its bar and names its file, and only on its own s
|
||||
await slow.click();
|
||||
await page.locator('#files button[title="Download to iPX"]').click();
|
||||
await expect(slow.locator('.dlbar.live')).toBeAttached({ timeout: 10_000 });
|
||||
await expect(page.locator('#count')).toContainText(/Downloading .+: \d+%/);
|
||||
await expect(page.locator('#count')).toContainText(/downloading .+ — \d+%/);
|
||||
await expect(page.locator('.toast', { hasText: /^Downloaded .+\.mp3/ })).toBeVisible({ timeout: 20_000 });
|
||||
await expect(slow.locator('.kind.here')).toBeVisible({ timeout: 5_000 });
|
||||
|
||||
@@ -1774,15 +1494,14 @@ test('the player keeps its speed and volume, marks an item played to its end rea
|
||||
});
|
||||
|
||||
test('a deleted file looks as if it was never downloaded', async ({ page }) => {
|
||||
// Other people subscribe to Picture Blog by now, so both questions come; yes to each.
|
||||
// Other people subscribe to Picture Blog by now, so both prompts come; take them.
|
||||
page.on('dialog', d => d.accept());
|
||||
await page.locator('.feed', { hasText: 'Picture Blog' }).click();
|
||||
const row = page.locator('.ep', { hasText: 'An Article' });
|
||||
await expect(row).toBeVisible({ timeout: 20_000 });
|
||||
await row.click();
|
||||
await page.locator('#files .encbox [data-a="more"]').last().click();
|
||||
await page.locator('#modalCard [data-m="del"]').click();
|
||||
await answer(page);
|
||||
await answer(page);
|
||||
|
||||
// No "reaped", no chip at all: just the way to get it again.
|
||||
await expect(row.locator('.kind.here')).toHaveCount(0);
|
||||
@@ -1856,8 +1575,8 @@ test('All Subscriptions marks everything read, across every feed', async ({ page
|
||||
await expect(page.locator('#epSearch')).toHaveAttribute('placeholder', 'Search');
|
||||
await expect(page.locator('#epSearch')).toHaveAccessibleName('Search All Subscriptions');
|
||||
|
||||
page.once('dialog', d => d.accept());
|
||||
await page.locator('#content .acts [data-a="readall"]').click();
|
||||
await answer(page);
|
||||
await expect(all.locator('.badge')).toHaveText('0');
|
||||
await page.locator('.tabs button', { hasText: 'Unread' }).click();
|
||||
await expect(page.locator('.ep')).toHaveCount(0);
|
||||
@@ -2161,8 +1880,8 @@ test('an admin removes a feed from the directory, and unblocks it (#206)', async
|
||||
await piper.locator('.show [data-a="drefresh"]').click();
|
||||
await expect(piper.locator('.toast', { hasText: 'Checked' })).toBeVisible();
|
||||
await expect(piper.locator('.show [data-a="dremove"]')).toHaveCount(1);
|
||||
piper.once('dialog', d => d.accept());
|
||||
await piper.locator('.show [data-a="dremove"]').click();
|
||||
await answer(piper);
|
||||
await expect(piper.locator('.show h2')).toHaveCount(0);
|
||||
expect(await listed()).not.toContain('Aardvark Radio');
|
||||
} finally {
|
||||
@@ -2454,9 +2173,7 @@ test.describe('an item with no files, on a phone', () => {
|
||||
});
|
||||
const bar = page.locator('#detail .dfloat');
|
||||
await expect(bar.locator('#dback')).toBeVisible();
|
||||
// By name, not counted: an episode has Up Next's button too (#473), so the count depended on
|
||||
// which item the tests before had left first.
|
||||
for (const a of ['read', 'flag', 'share']) await expect(bar.locator(`.dacts [data-a="${a}"]`)).toBeVisible();
|
||||
await expect(bar.locator('.dacts [data-a]')).toHaveCount(3);
|
||||
await page.locator('#detail').evaluate(el => { el.scrollTop = 3000; });
|
||||
// Still at the top of the screen, not scrolled away with the title.
|
||||
for (const q of ['#dback', '.dacts']) expect((await bar.locator(q).boundingBox())!.y).toBeLessThan(80);
|
||||
@@ -2466,10 +2183,6 @@ test.describe('an item with no files, on a phone', () => {
|
||||
await flag.click();
|
||||
await expect(bar.locator('[data-a="flag"]')).not.toHaveAttribute('aria-pressed', was!);
|
||||
expect(await page.locator('#detail').evaluate(el => el.scrollTop)).toBeGreaterThan(2500);
|
||||
// Pinned, it keeps its accent disc in the bar: cleared like the others, its pin was drawn in the
|
||||
// colour meant for the accent, white on a light theme's capsule (#480).
|
||||
const pinned = bar.locator('[data-a="flag"][aria-pressed="true"]');
|
||||
if (was !== 'true') await expect(pinned).not.toHaveCSS('background-color', 'rgba(0, 0, 0, 0)');
|
||||
await bar.locator('[data-a="flag"]').click();
|
||||
await expect(bar.locator('[data-a="flag"]')).toHaveAttribute('aria-pressed', was!);
|
||||
await bar.locator('#dback').click();
|
||||
@@ -2479,7 +2192,7 @@ test.describe('an item with no files, on a phone', () => {
|
||||
|
||||
test('a pinned feed, even one from inside a folder, goes to the top of the list', async ({ page }) => {
|
||||
// The Signals folder is first, under All Subscriptions (#256), and no feed.
|
||||
const rows = page.locator('#feedlist .feed:not(.sigs):not(.plists)');
|
||||
const rows = page.locator('#feedlist .feed:not(.sigs)');
|
||||
const group = page.locator('.feed.group').first();
|
||||
if ((await group.locator('.chev').getAttribute('aria-expanded')) !== 'true') await group.locator('.chev').click();
|
||||
const child = page.locator('.feed.child').first();
|
||||
@@ -2605,8 +2318,10 @@ test('Share hands the feed, and an episode as a link to its page on ipx-play (#4
|
||||
const paid = await page.evaluate(() => api('/api/entries/paid-show/paid-1/share', { method: 'POST', body: '{}' }));
|
||||
expect(paid).toEqual({ url: null, why: 'private' });
|
||||
// Through the same menu all the same: the sheet needs a press of its own after that request
|
||||
// (#452), and a key in the address is warned of there rather than asked first.
|
||||
// (#452), and a key in the address is warned of there, not asked with confirm(), which the iOS
|
||||
// app answers Cancel (#453).
|
||||
await page.evaluate(async () => {
|
||||
window.confirm = () => false;
|
||||
const e = (await api('/api/feeds/paid-show/entries') as ListPage).entries[0];
|
||||
await shareEpisode({ ...e, link: 'https://www.patreon.com/posts/1?auth=secret123' }, null);
|
||||
});
|
||||
@@ -2626,22 +2341,6 @@ test('Share hands the feed, and an episode as a link to its page on ipx-play (#4
|
||||
await expect(page.locator('#modalCard')).not.toContainText('own access');
|
||||
await page.locator('#shlink').click();
|
||||
await expect.poll(() => page.evaluate(() => window.shared.at(-1)?.url)).toBe('https://www.patreon.com/glasscannon/posts/1');
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
// A feed whose address carries its key is asked about first, in the page's own dialog (#462):
|
||||
// Cancel shares nothing, and Escape closes the question alone.
|
||||
const before = await page.evaluate(() => window.shared.length);
|
||||
await page.locator('.feed', { hasText: 'Paid Show' }).click();
|
||||
await page.locator('#content .acts [data-a="share"]').click();
|
||||
await expect(page.locator('dialog.ask')).toContainText('includes your own access');
|
||||
await answer(page, false);
|
||||
await page.locator('#content .acts [data-a="share"]').click();
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('dialog.ask')).toHaveCount(0);
|
||||
expect(await page.evaluate(() => window.shared.length)).toBe(before);
|
||||
await page.locator('#content .acts [data-a="share"]').click();
|
||||
await answer(page);
|
||||
await expect.poll(() => page.evaluate(() => window.shared.at(-1)?.url)).toBe('http://127.0.0.1:8792/paid.xml?auth=secret123');
|
||||
});
|
||||
|
||||
test('a refresh button turns from the press to the end of the scan it asked for', async ({ page }) => {
|
||||
@@ -3072,8 +2771,8 @@ signalsTest('a Signal is renamed from its own page and deleted from there', asyn
|
||||
const one = async () => (await (await page.request.get('/api/signals')).json() as Signal[]).find(s => s.id === id);
|
||||
expect((await one())?.name).toBe('Bread and cakes');
|
||||
|
||||
page.once('dialog', d => d.accept());
|
||||
await page.locator('#content [data-a="rm"]').click();
|
||||
await answer(page);
|
||||
await expect(page.locator('.toast', { hasText: 'Deleted' })).toBeVisible();
|
||||
await expect(page.locator('#feedlist .feed.child', { hasText: 'Bread and cakes' })).toHaveCount(0);
|
||||
expect(await one()).toBeUndefined();
|
||||
@@ -3099,8 +2798,8 @@ signalsTest('Signals are turned on in Settings with a key TypeSafe takes, and of
|
||||
await page.locator('#stskey').fill('test-key');
|
||||
await page.locator('#stskey').blur();
|
||||
await expect(page.locator('#feedlist .sigs')).toHaveCount(1);
|
||||
await page.locator('#ssigon').click();
|
||||
await answer(page);
|
||||
page.once('dialog', d => d.accept());
|
||||
await page.locator('#ssigon').uncheck();
|
||||
await expect(page.locator('#feedlist .sigs')).toHaveCount(0);
|
||||
expect((await (await page.request.get('/api/me')).json()).typesafe_key_set).toBe(false);
|
||||
await page.keyboard.press('Escape');
|
||||
@@ -3142,7 +2841,7 @@ test('a dialog keeps the keyboard inside it and gives it back on closing', async
|
||||
await expect(page.locator('#modalCard[role=dialog]')).toHaveAttribute('aria-labelledby', /.+/);
|
||||
await expect(page.locator('#nurl')).toBeFocused();
|
||||
// Labels name their boxes (#307).
|
||||
await expect(page.getByRole('textbox', { name: 'Feed address' })).toHaveCount(1);
|
||||
await expect(page.getByRole('textbox', { name: 'Feed URL' })).toHaveCount(1);
|
||||
for (let i = 0; i < 8; i++) {
|
||||
await page.keyboard.press('Tab');
|
||||
// Past the last control Tab goes to the browser's own toolbar (the body, from here), never the page behind.
|
||||
@@ -3184,177 +2883,3 @@ test('an error toast is announced and stays until it is dismissed', async ({ pag
|
||||
await t.getByRole('button', { name: 'Dismiss' }).click();
|
||||
await expect(t).toHaveCount(0);
|
||||
});
|
||||
|
||||
/// A scrape as Prometheus makes it: gzipped (#253), and every sample a name, labels perhaps, and a
|
||||
/// number, since one line that is not fails the whole scrape.
|
||||
async function scrape(page: Page, port: number): Promise<string> {
|
||||
const r = await page.request.get(`http://127.0.0.1:${port}/metrics`, { headers: { 'Accept-Encoding': 'gzip' } });
|
||||
expect(r.status()).toBe(200);
|
||||
expect(r.headers()['content-type']).toContain('text/plain');
|
||||
const text = await r.text();
|
||||
const bad = text.split('\n').filter(l => l && !l.startsWith('#') && !/^[a-z_:][a-z0-9_:]*(\{.*\})? (-?[0-9.e+-]+|NaN|\+Inf)$/i.test(l));
|
||||
expect(bad, `port ${port}`).toEqual([]);
|
||||
return text;
|
||||
}
|
||||
|
||||
test('each service serves its metrics as Prometheus reads them, the requests made counted by route', async ({ page }) => {
|
||||
// #194, #370, #458: production's Prometheus scrapes these every 15 s; the dashboard and the
|
||||
// alerts go blank if one stops answering, and nothing else in the suite asks for them.
|
||||
await page.request.get('/api/feeds');
|
||||
const ipx = await scrape(page, 8799);
|
||||
expect(ipx).toMatch(/^# TYPE ipx_http_request_duration_seconds histogram$/m);
|
||||
expect(ipx).toMatch(/^ipx_http_request_duration_seconds_count\{method="GET",route="\/api\/feeds",status="200"\} [1-9]/m);
|
||||
expect(ipx).toMatch(/^ipx_build_info\{version="[^"]+"\} 1$/m);
|
||||
expect(ipx).toMatch(/^ipx_db_connections_max [1-9]/m);
|
||||
expect(ipx).toMatch(/^ipx_feeds [1-9]/m);
|
||||
// The suite's ipx shares with its directory, so the directory has taken a snapshot and answered.
|
||||
const dir = await scrape(page, 8797);
|
||||
expect(dir).toMatch(/^directory_build_info\{version="[^"]+"\} 1$/m);
|
||||
expect(dir).toMatch(/^directory_snapshots_total [1-9]/m);
|
||||
expect(dir).toMatch(/^directory_http_request_duration_seconds_count\{/m);
|
||||
const play = await scrape(page, 8790);
|
||||
expect(play).toMatch(/^play_build_info\{version="[^"]+"\} 1$/m);
|
||||
expect(play).toMatch(/^play_uptime_seconds [0-9]/m);
|
||||
});
|
||||
|
||||
test('a reap over the quota says what it would delete and, dry, deletes nothing', async ({ page }) => {
|
||||
// Retention (retention.rs) runs on the daemon's own clock in production, once a day; nothing in
|
||||
// the suite ran it. Dry, so the files the tests after this one play are still there.
|
||||
const env = { ...process.env, IPX_CONFIG: `${setup.root}/config/config.toml`, IPX_DATA_DIR: `${setup.root}/data` };
|
||||
const ipx = (args: string[]) => execFileSync(setup.IPX_BIN, args, { env, encoding: 'utf8', timeout: 30_000 });
|
||||
const files = () => fs.readdirSync(`${setup.root}/downloads`, { recursive: true, withFileTypes: true }).filter(f => f.isFile()).length;
|
||||
const had = (await (await page.request.get('/api/settings')).json()).max_total_gb;
|
||||
const before = files();
|
||||
expect(before, 'the suite has downloaded files by now').toBeGreaterThan(0);
|
||||
expect((await page.request.patch('/api/settings', { data: { max_total_gb: 0.000001 } })).status()).toBe(204);
|
||||
try {
|
||||
const out = ipx(['reap', '--dry-run']);
|
||||
// Said as what would go, not as gone (#461).
|
||||
expect(out).toMatch(/^would delete [1-9]\d* old file\(s\)/m);
|
||||
expect(out).toMatch(/^would delete .+\/downloads\/.+ \(\d+\.\d MB\)$/m);
|
||||
expect(out).not.toMatch(/^deleted /m);
|
||||
expect(files(), 'a dry run deletes nothing').toBe(before);
|
||||
} finally {
|
||||
await page.request.patch('/api/settings', { data: { max_total_gb: had } });
|
||||
}
|
||||
// No limit: a real reap only tidies (the directory, where unread lists start, the artwork kept).
|
||||
expect(ipx(['reap'])).toContain('deleted 0 old file(s), 0.0 MB');
|
||||
expect(files()).toBe(before);
|
||||
});
|
||||
|
||||
test('a podcast told in seasons runs in its own order, one season at a time or all, and a season downloads whole (#482)', async ({ page }) => {
|
||||
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click({ timeout: 20_000 });
|
||||
await page.locator('#content .tabs button[data-f="all"]').click();
|
||||
const picker = page.locator('#content .seasons');
|
||||
await expect(picker.locator('button')).toHaveText(['All seasons', 'Season 1', 'Season 2', 'Other']);
|
||||
// Every season, in the podcast's own order, season 1 episode 1 first: each season's start said.
|
||||
await expect(page.locator('#eps .ep .t')).toHaveText(['The Pilot', 'Season One Close', 'Season Two Opener', 'Season Two Finale', 'A Bonus Between']);
|
||||
await expect(page.locator('#eps .sdiv')).toHaveText(['Season 1', 'Season 2', 'Other episodes']);
|
||||
// A heading clicked sorts by it, newest first, as on any other podcast.
|
||||
await page.locator('.ephead [data-sort="published"]').click();
|
||||
await expect(page.locator('#eps .ep .t').first()).toHaveText('Season Two Finale');
|
||||
|
||||
await picker.locator('button', { hasText: 'Season 1' }).click();
|
||||
await expect(page.locator('#content .seasons button', { hasText: 'Season 1' })).toHaveAttribute('aria-pressed', 'true');
|
||||
await expect(page.locator('#eps .ep .t')).toHaveText(['The Pilot', 'Season One Close']);
|
||||
await expect(page.locator('#eps .sdiv')).toHaveCount(0);
|
||||
// The count under the list is the season's, as the server counts it.
|
||||
const unread = await page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/seasons').then(r => r.json()))
|
||||
.find((s: { season?: number }) => s.season === 1).unread);
|
||||
await expect(page.locator('#count')).toHaveText(`Seasoned Show: 2 items, ${unread} unread`);
|
||||
// The whole season onto iPX, after asking, its first episode first.
|
||||
await page.locator('#content .seasondl').click();
|
||||
await page.locator('#sgo').click();
|
||||
// By its words: each file's own toast follows at once on the fixtures' tiny files.
|
||||
await expect(page.locator('.toast', { hasText: /Downloading 2 episodes of Season 1|All of Season 1 is on iPX already/ })).toBeAttached();
|
||||
await expect.poll(async () => page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/entries?season=1').then(r => r.json()))
|
||||
.entries.every((e: { enclosures: { path: string | null }[] }) => e.enclosures.every(x => x.path))), { timeout: 20_000 }).toBe(true);
|
||||
expect(await page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/entries?season=2').then(r => r.json()))
|
||||
.entries.some((e: { enclosures: { path: string | null }[] }) => e.enclosures.some(x => x.path)))).toBe(false);
|
||||
|
||||
await page.locator('#content .seasons button', { hasText: 'Other' }).click();
|
||||
await expect(page.locator('#eps .ep .t')).toHaveText(['A Bonus Between']);
|
||||
// A podcast with one season has no picker, and opening it again starts from every season.
|
||||
await page.locator('#feedlist .feed', { hasText: 'Test Show' }).first().click();
|
||||
await expect(page.locator('#content .seasons')).toHaveCount(0);
|
||||
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click();
|
||||
await expect(page.locator('#content .seasons button.on')).toHaveText('All seasons');
|
||||
});
|
||||
|
||||
test.describe('on a phone', () => {
|
||||
test.use({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true });
|
||||
test('a row spends its width on the title: unread a dot before it, pinned a pin under it (#484)', async ({ page }) => {
|
||||
await page.locator('#burger').click();
|
||||
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click({ timeout: 20_000 });
|
||||
await page.locator('#content .tabs button[data-f="all"]').click();
|
||||
const row = page.locator('#eps .ep', { hasText: 'The Pilot' });
|
||||
await expect(row).toBeVisible();
|
||||
// No read or pin button before the title: it starts at the row's own padding.
|
||||
await expect(row.locator('.st')).toBeHidden();
|
||||
await expect(row.locator('.fl')).toBeHidden();
|
||||
const [r, t] = [await row.boundingBox(), await row.locator('.t').boundingBox()];
|
||||
expect(t!.x - r!.x).toBeLessThan(16);
|
||||
// Unread says so before the title, by a dot a screen reader names; read, nothing.
|
||||
const flags = (body: object) => page.evaluate(b => fetch('/api/entries/seasoned-show/sn-1/flags',
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b) }), body);
|
||||
await flags({ read: false, flagged: true });
|
||||
await page.reload();
|
||||
await page.locator('#burger').click();
|
||||
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click();
|
||||
await expect(row.locator('.t [role=img][aria-label="Unread"]')).toBeVisible();
|
||||
// One line like the rest: no length under the title (#500).
|
||||
await expect(row.locator('.line')).not.toContainText(/\d:\d\d/);
|
||||
await expect(row.locator('.line [aria-label="Pinned"]')).toBeVisible();
|
||||
// What is under the title starts where its text does, past the dot, and the date is on the
|
||||
// title's line, not centred between the two.
|
||||
const [dot, mark, title, date] = await Promise.all(['.udot', '.pinmark', '.t', '.date'].map(s => row.locator(s).boundingBox()));
|
||||
expect(Math.abs(mark!.x - (dot!.x + dot!.width + 7))).toBeLessThan(2);
|
||||
expect(date!.y + date!.height).toBeLessThan(title!.y + title!.height + 3);
|
||||
await flags({ read: true, flagged: false });
|
||||
await page.reload();
|
||||
await page.locator('#burger').click();
|
||||
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click();
|
||||
await expect(row.locator('.udot')).toBeHidden();
|
||||
await expect(row.locator('.pinmark')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('the reader opened on a phone has its scroller back two frames on, and scrolls (#450)', async ({ page }) => {
|
||||
await page.locator('#burger').click();
|
||||
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click({ timeout: 20_000 });
|
||||
await page.locator('#content .tabs button[data-f="all"]').click();
|
||||
await page.locator('#eps .ep .t').first().click();
|
||||
const d = page.locator('#detail');
|
||||
await expect.poll(() => d.evaluate(el => getComputedStyle(el).overflowY)).toBe('auto');
|
||||
expect(await d.evaluate(el => el.style.overflowY)).toBe('');
|
||||
});
|
||||
|
||||
test('a page of its own starts its header where a podcast\'s does (#485)', async ({ page }) => {
|
||||
const artX = async (id: string) => {
|
||||
await page.evaluate(id => { selectFeed(id); nav(false); }, id);
|
||||
await expect(page.locator('#content .fhead .art').first()).toBeVisible();
|
||||
return (await page.locator('#content .fhead .art').first().boundingBox())!.x;
|
||||
};
|
||||
const podcast = await artX('test-show');
|
||||
for (const id of [':upnext', ':listening']) expect(await artX(id), id).toBe(podcast);
|
||||
});
|
||||
|
||||
test('a folder\'s triangle is on the far left in a narrow margin, and a lone header button keeps its row (#486, #487, #491)', async ({ page }) => {
|
||||
await page.locator('#burger').click();
|
||||
const box = async (sel: string) => (await page.locator(sel).first().boundingBox())!;
|
||||
// Once the drawer has slid in: measured on its way, the rows are still moving.
|
||||
await expect.poll(async () => (await box('#feedlist')).x).toBeGreaterThanOrEqual(0);
|
||||
await page.waitForFunction(() => document.getAnimations().length === 0);
|
||||
const [list, folder, feed] = [await box('#feedlist'), await box('.feed.group .fart'), await box('#feedlist .feed:not(.group):not(.sigs):not(.plists) .fart')];
|
||||
// Every row's art in one line, near the list's edge: 20 px in, where the 16 px margin #486 took
|
||||
// out put it at 26.
|
||||
expect(feed.x).toBe(folder.x);
|
||||
expect(feed.x - list.x).toBeLessThanOrEqual(20);
|
||||
// The folder's triangle first, at the list's edge, and clear of the art (#491).
|
||||
const chev = await box('.feed.group .chev');
|
||||
expect(chev.x - list.x).toBeLessThanOrEqual(1);
|
||||
expect(chev.x + chev.width).toBeLessThanOrEqual(folder.x + 0.5);
|
||||
await page.evaluate(() => { selectFeed(PLAYLISTS); nav(false); });
|
||||
const [art, add] = [await box('#content .fhead .art'), await box('#content .fhead [data-a="new"]')];
|
||||
expect(add.y).toBeLessThan(art.y + art.height);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
<?xml version="1.0"?>
|
||||
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
|
||||
<channel><title>Seasoned Show</title><link>http://127.0.0.1:8792/</link><description>A fixture podcast told in seasons (#482).</description>
|
||||
<item><title>Season Two Finale</title><guid>sn-4</guid><pubDate>Mon, 01 Jun 2026 10:00:00 +0000</pubDate>
|
||||
<itunes:season>2</itunes:season><itunes:episode>2</itunes:episode>
|
||||
<enclosure url="http://127.0.0.1:8792/ep2.mp3?s2e2" length="40000" type="audio/mpeg"/></item>
|
||||
<item><title>Season Two Opener</title><guid>sn-3</guid><pubDate>Mon, 25 May 2026 10:00:00 +0000</pubDate>
|
||||
<itunes:season>2</itunes:season><itunes:episode>1</itunes:episode>
|
||||
<enclosure url="http://127.0.0.1:8792/ep2.mp3?s2e1" length="40000" type="audio/mpeg"/></item>
|
||||
<item><title>A Bonus Between</title><guid>sn-b</guid><pubDate>Mon, 18 May 2026 10:00:00 +0000</pubDate></item>
|
||||
<item><title>The Pilot</title><guid>sn-1</guid><pubDate>Mon, 11 May 2026 10:00:00 +0000</pubDate>
|
||||
<itunes:season>1</itunes:season><itunes:episode>1</itunes:episode>
|
||||
<enclosure url="http://127.0.0.1:8792/ep2.mp3?s1e1" length="40000" type="audio/mpeg"/></item>
|
||||
<item><title>Season One Close</title><guid>sn-2</guid><pubDate>Mon, 04 May 2026 10:00:00 +0000</pubDate>
|
||||
<itunes:season>1</itunes:season><itunes:episode>2</itunes:episode>
|
||||
<enclosure url="http://127.0.0.1:8792/ep2.mp3?s1e2" length="40000" type="audio/mpeg"/></item>
|
||||
</channel></rss>
|
||||
@@ -6,8 +6,6 @@ import path from 'node:path';
|
||||
const dir = import.meta.dirname;
|
||||
const port = Number(process.env.FIXTURE_PORT || 8792);
|
||||
|
||||
let flip = 'ok';
|
||||
|
||||
http.createServer((req, res) => {
|
||||
// Jev, for Signals (#254): sure of an item whose text has a question's keyword in it. Refuses
|
||||
// a request in the shape TypeSafe refuses, as it does (#257).
|
||||
@@ -89,67 +87,6 @@ http.createServer((req, res) => {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
// Feeds in the shapes the others are not (#463): Atom and RSS each with a bare "&", the RSS with the iTunes and
|
||||
// Media RSS fields; WordPress.com's posts as its API sends them; and replies that are no feed.
|
||||
const at = `http://127.0.0.1:${port}`;
|
||||
const shapes: Record<string, [string, string]> = {
|
||||
'/atom.xml': ['application/atom+xml', `<?xml version="1.0" encoding="utf-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom"><title type="html">Atom&#8217;s Show</title>
|
||||
<subtitle>An Atom feed</subtitle><link rel="alternate" href="${at}/atom.html"/><logo>${at}/art.jpg</logo>
|
||||
<id>urn:atom-show</id><updated>2026-01-01T00:00:00Z</updated>
|
||||
<entry><id>urn:atom-1</id><title>Q&A in Atom</title><updated>2026-01-02T00:00:00Z</updated>
|
||||
<published>2026-01-02T00:00:00Z</published><link rel="alternate" href="${at}/atom-1.html"/>
|
||||
<link rel="enclosure" href="${at}/atom-1.mp3" type="audio/mpeg" length="40000"/>
|
||||
<link rel="enclosure" href="${at}/atom-1.mp3?_=1" type="audio/mpeg" length="40000"/>
|
||||
<category term="tech"/><summary>Short summary</summary>
|
||||
<content type="html"><p>Full <b>notes</b></p></content></entry>
|
||||
<entry><id>urn:atom-2</id><title>Markdown entry</title><updated>2026-01-03T00:00:00Z</updated>
|
||||
<summary>A [link](http://example.com) and **bold**</summary></entry></feed>`],
|
||||
'/amp.xml': ['application/rss+xml', `<?xml version="1.0"?>
|
||||
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
<channel><title>Ampersand Radio</title><link>${at}/amp.html?a=1&b=2</link><description></description><ttl>90</ttl>
|
||||
<itunes:summary>Summary from iTunes</itunes:summary><itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:category text="Leisure"><itunes:category text="Games"/></itunes:category>
|
||||
<item><guid>amp-1</guid><title>Tom & Jerry</title><pubDate>2026-01-05T10:00:00Z</pubDate>
|
||||
<itunes:duration>1:02:03</itunes:duration><media:thumbnail url="${at}/art2.jpg"/>
|
||||
<description>A subtitle not in the body</description><content:encoded><![CDATA[<p>The body of the notes.</p>]]></content:encoded></item>
|
||||
<item><guid>amp-2</guid><title>Cut body</title><description>The whole description</description>
|
||||
<content:encoded><![CDATA[x">tail of a tag</p>]]></content:encoded><media:content url="${at}/pic.png" medium="image"/></item>
|
||||
<item><title>Picture only</title><enclosure url="${at}/amp-pic.png" type="image/png" length="10"/></item>
|
||||
</channel></rss>`],
|
||||
'/wp.json': ['application/json', JSON.stringify([{
|
||||
guid: { rendered: `${at}/?p=1` }, link: `${at}/wp-1`, title: { rendered: 'WordPress “post”' },
|
||||
date_gmt: '2026-01-04T12:00:00', content: { rendered: '<p>Post body</p>' }, jetpack_featured_media_url: `${at}/art.jpg`,
|
||||
}])],
|
||||
// Where /flip.xml moves to for good.
|
||||
'/moved.xml': ['application/rss+xml', `<?xml version="1.0"?><rss version="2.0"><channel><title>Flip Show</title>
|
||||
<item><guid>flip-1</guid><title>Flip one</title></item></channel></rss>`],
|
||||
// Second Episode's chapters (#477): one only for its artwork, which is not listed.
|
||||
'/chapters.json': ['application/json+chapters', JSON.stringify({ version: '1.2.0', chapters: [
|
||||
{ startTime: 1.5, title: 'The middle' }, { startTime: 0, title: 'Opening' }, { startTime: 1, img: `${at}/art.jpg`, toc: false },
|
||||
] })],
|
||||
'/said.txt': ['text/plain', 'Unable to establish a DB connection'],
|
||||
'/long.txt': ['text/plain', 'This site is down for maintenance and will be back shortly, thank you for your patience while we work'],
|
||||
'/empty.xml': ['application/xml', ''],
|
||||
'/garbled.xml': ['application/xml', '<rss><channel><title>Broken'],
|
||||
};
|
||||
const shape = shapes[req.url ?? ''];
|
||||
if (shape) { res.writeHead(200, { 'content-type': shape[0] }).end(shape[1]); return; }
|
||||
// A feed that starts failing, in whichever way a test asks for with /flip?to= (#463).
|
||||
if (req.url?.startsWith('/flip?to=')) { flip = req.url.slice('/flip?to='.length); res.writeHead(204).end(); return; }
|
||||
if (req.url === '/flip.xml') {
|
||||
if (/^\d{3}$/.test(flip)) { res.writeHead(Number(flip)).end('no'); return; }
|
||||
if (flip === 'moved') { res.writeHead(301, { location: '/moved.xml' }).end(); return; }
|
||||
if (flip === 'loop') { res.writeHead(302, { location: '/flip.xml' }).end(); return; }
|
||||
if (flip === 'drop') { req.socket.destroy(); return; }
|
||||
const body = flip === 'text' ? 'Unable to establish a DB connection'
|
||||
: flip === 'nothing' ? ''
|
||||
: flip === 'page' ? `<!doctype html><html><head><link rel="alternate" type="application/rss+xml" href="${at}/moved.xml"></head></html>`
|
||||
: flip === 'garbled' ? '<rss><channel><title>Broken'
|
||||
: `<?xml version="1.0"?><rss version="2.0"><channel><title>Flip Show</title><item><guid>flip-1</guid><title>Flip one</title></item></channel></rss>`;
|
||||
res.writeHead(200, { 'content-type': 'application/xml' }).end(body);
|
||||
return;
|
||||
}
|
||||
const name = decodeURIComponent((req.url ?? '/').split('?')[0]!.replace(/^\//, '')) || 'index';
|
||||
const file = path.join(dir, path.basename(name));
|
||||
fs.readFile(file, (err, body) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0"?>
|
||||
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:podcast="https://podcastindex.org/namespace/1.0">
|
||||
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
|
||||
<channel><title>Test Show</title><link>http://127.0.0.1:8792/</link><description>A fixture feed.</description>
|
||||
<itunes:image href="http://127.0.0.1:8792/art.png"/>
|
||||
<itunes:category text="Technology"/>
|
||||
@@ -12,6 +12,5 @@
|
||||
<pubDate>Mon, 08 Sep 2026 10:00:00 +0000</pubDate>
|
||||
<description>Notes for the second.</description>
|
||||
<itunes:duration>900</itunes:duration>
|
||||
<podcast:chapters url="http://127.0.0.1:8792/chapters.json" type="application/json+chapters"/>
|
||||
<enclosure url="http://127.0.0.1:8792/ep1.mp3?2" length="40000" type="audio/mpeg"/></item>
|
||||
</channel></rss>
|
||||
@@ -56,18 +56,11 @@ token = "${TOKEN}"
|
||||
trusted_header = "X-Test-User"
|
||||
trusted_proxies = ["127.0.0.1"]
|
||||
sign_out_url = "/signed-out-by-the-proxy"
|
||||
# What Prometheus scrapes in production (#194), read by a test once the others have made requests.
|
||||
metrics_bind = "127.0.0.1:8799"
|
||||
|
||||
[feeds.test-show]
|
||||
url = "http://127.0.0.1:8792/show.xml"
|
||||
auto_download = true
|
||||
|
||||
# Told in seasons, with a bonus naming none between them: the season picker (#482).
|
||||
[feeds.seasoned-show]
|
||||
url = "http://127.0.0.1:8792/seasons.xml"
|
||||
auto_download = false
|
||||
|
||||
# Downloads its image, so the UI has a file that is not playable to deal with.
|
||||
[feeds.picture-blog]
|
||||
url = "http://127.0.0.1:8792/pics.xml"
|
||||
@@ -89,7 +82,6 @@ auto_download = false
|
||||
`);
|
||||
fs.writeFileSync(path.join(root, 'directory.toml'), `
|
||||
bind = "127.0.0.1:8795"
|
||||
metrics_bind = "127.0.0.1:8797"
|
||||
database_url_env = "DIRECTORY_DATABASE_URL"
|
||||
# The fixture feeds are on loopback, which the refresher refuses otherwise (#329).
|
||||
fetch_internal = ["127.0.0.1"]
|
||||
@@ -101,7 +93,6 @@ token_sha256 = "${crypto.createHash('sha256').update(DIRECTORY_TOKEN).digest('he
|
||||
`);
|
||||
fs.writeFileSync(path.join(root, 'play.toml'), `
|
||||
bind = "127.0.0.1:8798"
|
||||
metrics_bind = "127.0.0.1:8790"
|
||||
public_url = "${PLAY}"
|
||||
|
||||
[[tokens]]
|
||||
|
||||
@@ -92,33 +92,6 @@ test('a place in an episode saved offline waits, and is saved once back', async
|
||||
expect((await call(page, '/api/entries/offline-blog/offline-2')).position).toBe(321);
|
||||
});
|
||||
|
||||
test('a page older than the script the server sends is loaded again, not run with it', async ({ page }) => {
|
||||
// #449: a page kept from before a deploy asks for its script by the old hash, and the server
|
||||
// sends the new one whatever the name says.
|
||||
await controlled(page);
|
||||
const mine = await page.evaluate(() => document.querySelector('script[src^="/app.js"]')!.getAttribute('src')!);
|
||||
const kept = () => page.evaluate(async () => (await (await caches.open('ipx-page')).keys()).map(k => new URL(k.url).pathname + new URL(k.url).search));
|
||||
await expect.poll(kept).toContain(mine);
|
||||
await page.evaluate(() => { (window as unknown as { stale: boolean }).stale = true; });
|
||||
const reloaded = page.waitForEvent('load');
|
||||
expect(await page.evaluate(() => fetch('/app.js?v=000000000000').then(() => 'given', () => 'refused'))).toBe('refused');
|
||||
await reloaded;
|
||||
expect(await page.evaluate(() => 'stale' in window), 'the page was loaded again').toBe(false);
|
||||
// What is kept is still the script under its own name, not the new one under the old.
|
||||
expect(await kept()).toContain(mine);
|
||||
expect(await kept()).not.toContain('/app.js?v=000000000000');
|
||||
});
|
||||
|
||||
test('the page has the worker keep it however it was loaded, for the iOS app (#506)', async ({ page }) => {
|
||||
await controlled(page);
|
||||
const has = () => page.evaluate(async () => !!(await (await caches.open('ipx-page')).match('/')));
|
||||
// As if the load had not come through the worker, which the app's own load does not.
|
||||
await page.evaluate(async () => { await (await caches.open('ipx-page')).delete('/'); });
|
||||
expect(await has()).toBe(false);
|
||||
await page.evaluate(() => navigator.serviceWorker.controller!.postMessage({ keepPage: true }));
|
||||
await expect.poll(has).toBe(true);
|
||||
});
|
||||
|
||||
test('online, a picture in an item\'s text still comes from its publisher, through the worker', async ({ page }) => {
|
||||
await controlled(page);
|
||||
await page.locator('#feedlist .feed', { hasText: 'Offline Blog' }).click({ timeout: 20_000 });
|
||||
|
||||
@@ -10,5 +10,5 @@
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["web/sw/*.ts", "web/src/wire.ts"]
|
||||
"include": ["web/sw/*.ts"]
|
||||
}
|
||||
|
||||
@@ -13,13 +13,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- Now Playing lists the episode's chapters, when its podcast has them, with the one playing in bold; a tap plays from there (#477).
|
||||
- A podcast told in seasons lists its episodes in its own order, season 1 episode 1 first, until a heading is clicked to sort it otherwise, with each season's start marked. A season picker under its tabs lists one season at a time, or the episodes in none, and a season picked can be downloaded whole (#482).
|
||||
- Smart playlists, in a folder of their own in the feed list: choose the podcasts, which of them play first, unplayed episodes only or all, newest or oldest first, and the playlist keeps itself up to date. Playing from one goes on through it once Up Next is empty (#476).
|
||||
- Now Playing: tap the player bar to see what is playing with its artwork large, its podcast (a tap opens it), its show notes and what follows in Up Next; Esc or the bar closes it (#475).
|
||||
- Podcasts: your podcasts as a shelf of their artwork, each with how many episodes are new; the search box narrows it, and a tap opens one (#474).
|
||||
- Up Next: line episodes up with the list button on a row or in the reader (`q`, or `Shift Q` to play one next), move them by their handles, and each plays when the one before it ends. The player has a Next button while something is lined up, and the lock screen's next-track button does the same (#473).
|
||||
- The page reads ipx's answers in protobuf, with a decoder of its own and no library, and in JSON from a server that has none; offline, a kept answer still shows what was read offline (#470).
|
||||
- On a phone, back and the item's actions (read, pin, open, share) float over the text as it scrolls, so they are at hand anywhere in a long post without scrolling back to the top; pressing one there keeps your place (#456).
|
||||
- Share on an episode offers Share link, Share from where you are, and Copy link, with a link to the episode's page on ipx-play that anyone can play; an episode of a private feed offers its own page in the same menu, never its file, which a paid feed signs for you, and says why there is no page anyone can play. An admin sets ipx-play up in Admin, Directory (#447, #452, #454, #455).
|
||||
- In the iOS app, Settings has a This device section for the app's server and player token, with a button that makes a token and hands it to the app (#445).
|
||||
@@ -40,20 +33,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Fixed
|
||||
|
||||
- The page is kept for opening offline however it was loaded, so the iOS app opens with no connection too (#506).
|
||||
- On a phone, an episode's row is one line like the rest: its length, which took a line of its own, is in the reader, and the date sits on the title's line (#500).
|
||||
- On an iPhone, the reader rebuilds its scrolling each time an item opens, and again after a drag that did not move it, so a freshly opened item scrolls on the first try (#450).
|
||||
- The count under All Subscriptions counts only its own unread items, not those of feeds hidden from it, so it agrees with the header (#499).
|
||||
- An item without a title is named in bold like the rest of the list, not in regular weight beside them (#498).
|
||||
- The X on a playlist's episode marks it played again; it did nothing (#497).
|
||||
- A folder's triangle in the feed list is back on the far left, in a narrower margin than before, with every feed's artwork still in line (#491).
|
||||
- Opening a podcast or a list draws only the list: the feed list beside it is no longer rebuilt to move its highlight, and dates are written by one formatter rather than one a row, about 40% less work on a phone (#490).
|
||||
- A report of a reader that would not scroll no longer comes from a quick flick that did scroll, and says when the reader was last swiped across, not that it was just now (#488).
|
||||
- The headers of Currently Listening, Up Next, Playlists and Signals start where a podcast's does, rather than twice as far in and further down (#485).
|
||||
- On a phone, a pinned item's pin in the reader's floating actions is on its accent disc again, rather than nearly invisible on a light theme (#480).
|
||||
- Swiping between items on a phone no longer flashes: the pictures of the items either side are loaded ahead, so the preview under your finger shows its picture with its text, and the swipe ends only once the new item's pictures are ready (#471).
|
||||
- Deleting a downloaded file, marking everything read, deleting a signal and the other actions that ask first now ask in the page's own dialog, so they go ahead in the iOS app, which answered the browser's question Cancel without showing it (#462).
|
||||
- A page kept for offline from before a deploy, shown on waking before the network was back, is loaded again rather than run with the new script, which left it dead until reloaded by hand (#449).
|
||||
- On a phone the totals along the bottom (All Subscriptions: N items, N unread) are text alone, centred just above the home indicator, instead of a band and rule that ran to the bottom edge and were cut off by the screen's rounded corners (#424).
|
||||
- The admin page's top bar clears the status bar in the iOS app, so its back button can be tapped; the page asked for no room under the clock as the app page does (#423).
|
||||
- Swiping, or j, through more than 50 items no longer stops at the 50th until a reload: the next ones are fetched as you near the end, and Load more on the Unread tab no longer skips as many unread items as you had read (#383).
|
||||
@@ -65,14 +44,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Changed
|
||||
|
||||
- An item row's date is short and smaller: the time today, the day and month this year, the month and year before; the full date on hover (#508).
|
||||
- A toolbar button that cannot act says why in its tooltip (Choose an item first, Open a feed to unsubscribe from it, Nothing to play in this item), and the admin page's Save says nothing has changed yet; on a phone a checkbox's row is 40 px to tap (#507).
|
||||
- On a phone the toolbar's buttons and the list's tabs are at least 40 px to tap, a chapter no longer stays lit after a tap, and an item's pin and download buttons have names a screen reader reads, as the style guide's design half asks (#507).
|
||||
- The page's words follow one style (docs/STYLE-GUIDE.md): failures say "Unable to …" and what to do, a podcast is a podcast rather than a show, a feed has an address rather than a URL, and the buttons Auto and Initials in a signal's icon picker read Pick for me and Use initials (#507).
|
||||
- A title that is only the opening of an item's own text, as ipx now names an untitled item, is not shown again above that text in the reader or a directory preview (#502).
|
||||
- A folder's triangle in the feed list is at its row's end, before the count, so every feed lines up with the places above at the list's edge, and on a phone Playlists' and Signals' + button sits beside the title rather than on a line of its own (#486, #487).
|
||||
- On a phone, an episode's title starts at the row's edge: the read and pin buttons are gone from the row, an unread episode has a dot before its title and a pinned one a pin under it, and both are changed from the reader's actions (#484).
|
||||
- Podcasts are in order by name with a leading "The", "A" or "An" set aside, in the feed list, the Podcasts shelf, a playlist's choices and the Directory: The Rest Is Science is under R, not T (#481).
|
||||
- A file has one button that brings it to where you are: on a phone or in the iOS app it ends on the device, with iPX fetching it first when it has not got it, and on a computer iPX fetches it and the button then saves a copy. A line beside the file's size says where it is (publisher only, queued for iPX, on iPX, on this device), and the rarer actions (remove from this device, delete from iPX, download to iPX only) are under ⋯ (#457).
|
||||
- The admin page is laid out as a feed's settings are: each tab in named parts, numbers with their unit beside them, switches for on and off, Server's Save always in reach, and on a phone the tabs in a row of their own so all four fit (#414).
|
||||
- An item's title and text take four fifths of the reading pane's width, no longer running to its far edge (#360).
|
||||
|
||||
168
web/app.css
168
web/app.css
@@ -509,7 +509,7 @@ a{color:var(--accent)}
|
||||
::-webkit-scrollbar-track{background:transparent}
|
||||
|
||||
/* ---------- shell ---------- */
|
||||
#shell{display:grid;grid-template-columns:290px 1fr;min-height:0;min-width:0;overflow:hidden;position:relative}
|
||||
#shell{display:grid;grid-template-columns:290px 1fr;min-height:0;min-width:0;overflow:hidden}
|
||||
/* [ hides the feed list. A phone slides it over the page instead, so this is for wider screens. */
|
||||
@media (min-width:821px){
|
||||
body.nosb #shell{grid-template-columns:minmax(0,1fr)}
|
||||
@@ -571,7 +571,7 @@ a{color:var(--accent)}
|
||||
@media (hover:hover){.sidetools button:hover,.sidefoot button:hover{border-color:var(--accent);color:var(--fg)}}
|
||||
/* Settings and the log are housekeeping: they sit under the feeds, out of the way. */
|
||||
.sidefoot{
|
||||
display:flex;flex-direction:column;gap:6px;padding:8px 12px;
|
||||
display:flex;flex-direction:column;gap:7px;padding:8px 12px;
|
||||
border-top:1px solid var(--line);flex:none;
|
||||
}
|
||||
.sidefoot .row{display:flex;gap:6px}
|
||||
@@ -600,9 +600,9 @@ input:focus,select:focus{border-color:var(--accent)}
|
||||
.clearx svg{width:11px;height:11px}
|
||||
.clearable:has(>input:placeholder-shown) .clearx{display:none}
|
||||
.inline .clearable{flex:1}
|
||||
/* The wider left gutter is the folder triangle's, kept narrow (#486, #491): everything in the list
|
||||
shifts with it, so the feeds still line up with the places above. */
|
||||
#feedlist{overflow-y:auto;overscroll-behavior:contain;padding:0 8px 12px 10px;flex:1;min-height:0}
|
||||
/* The wider left gutter is the folder triangle's; everything in the list shifts with it, so the
|
||||
feeds still line up with the places above. */
|
||||
#feedlist{overflow-y:auto;overscroll-behavior:contain;padding:0 8px 12px 16px;flex:1;min-height:0}
|
||||
.feed{
|
||||
display:flex;gap:10px;align-items:center;padding:7px 8px;border-radius:9px;
|
||||
cursor:pointer;margin-bottom:1px;position:relative;
|
||||
@@ -644,11 +644,11 @@ input:focus,select:focus{border-color:var(--accent)}
|
||||
content:"";display:inline-block;width:10px;height:10px;margin-left:6px;vertical-align:-1px;border-radius:50%;
|
||||
border:2px solid var(--line);border-top-color:var(--accent);animation:ipxspin .8s linear infinite;
|
||||
}
|
||||
/* Only a folder has a triangle, on the far left (#491), hung in the list's margin so every feed's
|
||||
art lines up with the places above it. The row's full height, and the margin and the row's
|
||||
padding wide, up to the art: a near miss used to open the folder's page. */
|
||||
/* Only a folder has a triangle, hung in the margin so every feed's art lines up with the places
|
||||
above it. The button is the row's full height and 24 px wide: a near miss used to open the
|
||||
folder's page, and 16 px left the triangle cramped against the art. */
|
||||
.chev{
|
||||
position:absolute;left:-10px;top:0;bottom:0;width:18px;display:grid;place-items:center;
|
||||
position:absolute;left:-16px;top:0;bottom:0;width:24px;display:grid;place-items:center;
|
||||
border-radius:4px;color:var(--faint);
|
||||
}
|
||||
@media (hover:hover){.chev:hover{color:var(--fg)}}
|
||||
@@ -688,70 +688,26 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
|
||||
/* Currently Listening: how far into each episode you are, as a rail along the foot of its row.
|
||||
The one in the player is marked as it is everywhere else, by the amber EQ bars, and its rail
|
||||
and time left move as it plays. The rest stay neutral, so that one is what stands out. */
|
||||
#listening .childrow,#nowqueue .childrow{position:relative;overflow:hidden;gap:12px;padding:10px 10px 13px}
|
||||
#listening .childrow .art,#nowqueue .childrow .art{width:44px;height:44px;font-size:13px}
|
||||
#listening .txt b,#nowqueue .txt b{display:flex;align-items:center;gap:6px}
|
||||
#listening .txt b span,#nowqueue .txt b span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
#listening .txt small,#nowqueue .txt small{display:flex;gap:12px;margin-top:3px;color:var(--faint);font-size:11.5px}
|
||||
#listening .txt small .fd,#nowqueue .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
#listening .txt small .left,#nowqueue .txt small .left{flex:none;color:var(--dim)}
|
||||
#listening .childrow:not(.now) .eq,#nowqueue .childrow:not(.now) .eq{display:none}
|
||||
/* Now Playing (#475): over the feeds and the list, above the player bar, which keeps the
|
||||
controls. The artwork is the one large thing on the page. */
|
||||
#nowsheet{position:absolute;inset:0;z-index:30;overflow:auto;background:var(--bg);
|
||||
padding:22px max(16px,calc((100% - 720px)/2)) 32px}
|
||||
#nowclose{position:sticky;float:right;top:0;margin:-8px -4px 0 0;right:max(12px,calc((100% - 720px)/2 - 44px))}
|
||||
.nowhead{display:grid;grid-template-columns:minmax(0,280px) minmax(0,1fr);gap:24px;align-items:end;margin:10px 0 26px}
|
||||
.nowhead .nowart{width:100%;height:auto;aspect-ratio:1;border-radius:14px;font-size:56px}
|
||||
.nowmeta{display:flex;flex-direction:column;gap:6px;min-width:0}
|
||||
.nowmeta h2{margin:0;font-size:24px;line-height:1.2;text-wrap:balance}
|
||||
.nowshow{align-self:flex-start;color:var(--accent);font-size:15px;font-weight:500;text-align:left}
|
||||
.nowmeta small{color:var(--dim);font-size:12.5px;font-variant-numeric:tabular-nums}
|
||||
#nowsheet h3{font-size:14px;font-weight:600;margin:22px 0 10px;color:var(--dim)}
|
||||
#nowqueue{display:flex;flex-direction:column;gap:6px}
|
||||
/* Chapters (#477): a tap plays from there; the one playing reads bold. */
|
||||
.chapters{list-style:none;margin:0;padding:0;display:flex;flex-direction:column}
|
||||
.chapters button{display:flex;gap:14px;width:100%;padding:8px 6px;border-radius:8px;text-align:left;font-size:14px}
|
||||
@media (hover:hover){.chapters button:hover{background:var(--raise)}}
|
||||
.chapters .ctime{min-width:4.5em;color:var(--dim);font-variant-numeric:tabular-nums}
|
||||
.chapters button[aria-current]{font-weight:600}
|
||||
#pnow{cursor:pointer;border-radius:8px}
|
||||
@media (max-width:820px){
|
||||
.nowhead{grid-template-columns:1fr;justify-items:center;text-align:center;gap:18px}
|
||||
.nowhead .nowart{max-width:300px}
|
||||
.nowmeta{align-items:center}
|
||||
.nowshow{align-self:center;text-align:center}
|
||||
}
|
||||
/* The Podcasts shelf (#474): the artwork is the podcast, as on a shelf of records, so nothing
|
||||
frames it: no card, no shadow, the name and its new episodes under it. */
|
||||
.shelf{display:grid;grid-template-columns:repeat(auto-fill,minmax(112px,1fr));gap:20px 14px;padding:4px 2px 24px}
|
||||
.shelf .show{display:flex;flex-direction:column;gap:6px;min-width:0;text-align:left;cursor:pointer;border-radius:10px}
|
||||
.shelf .show .art{width:100%;height:auto;aspect-ratio:1;border-radius:10px;font-size:26px}
|
||||
.shelf .show b{font-weight:500;font-size:13px;line-height:1.3;color:var(--fg);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
|
||||
.shelf .show small{color:var(--dim);font-size:11.5px;min-height:1em;margin-top:-3px}
|
||||
@media (hover:hover){.shelf .show:hover .art{outline:2px solid var(--accent);outline-offset:2px}}
|
||||
/* A playlist's podcasts in its dialog: each one in or out, and whether it plays first. */
|
||||
.plshows{display:flex;flex-direction:column;gap:2px;max-height:min(46vh,360px);overflow:auto;margin-top:4px}
|
||||
.plshow{display:grid;grid-template-columns:28px minmax(0,1fr) auto;gap:10px;align-items:center;padding:4px 2px}
|
||||
.plshow .art{width:28px;height:28px;font-size:10px}
|
||||
.plshow .check{margin:0;min-width:0}
|
||||
.plshow .first{color:var(--dim);font-size:12.5px}
|
||||
/* Up Next's handle: dragged, it takes the pointer, so the list does not scroll under the finger. */
|
||||
#listening .grip{width:22px;margin-left:-4px;color:var(--faint);cursor:grab;touch-action:none}
|
||||
#listening .grip svg{width:12px;height:12px}
|
||||
#listening .childrow.dragging{border-color:var(--accent);cursor:grabbing}
|
||||
#listening .rail,#nowqueue .rail{position:absolute;left:0;right:0;bottom:0;height:3px;background:var(--raise)}
|
||||
#listening .rail i,#nowqueue .rail i{display:block;height:100%;width:0;background:var(--faint);transition:width .25s linear}
|
||||
#listening .now,#nowqueue .now{border-color:color-mix(in srgb,var(--accent2) 60%,var(--line))}
|
||||
#listening .now .eq,#nowqueue .now .eq,#listening .now .left,#nowqueue .now .left{color:var(--accent2)}
|
||||
#listening .now .rail i,#nowqueue .now .rail i{background:var(--accent2)}
|
||||
#listening .childrow{position:relative;overflow:hidden;gap:12px;padding:10px 10px 13px}
|
||||
#listening .childrow .art{width:44px;height:44px;font-size:13px}
|
||||
#listening .txt b{display:flex;align-items:center;gap:7px}
|
||||
#listening .txt b span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
#listening .txt small{display:flex;gap:12px;margin-top:3px;color:var(--faint);font-size:11.5px}
|
||||
#listening .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
#listening .txt small .left{flex:none;color:var(--dim)}
|
||||
#listening .childrow:not(.now) .eq{display:none}
|
||||
#listening .rail{position:absolute;left:0;right:0;bottom:0;height:3px;background:var(--raise)}
|
||||
#listening .rail i{display:block;height:100%;width:0;background:var(--faint);transition:width .25s linear}
|
||||
#listening .now{border-color:color-mix(in srgb,var(--accent2) 60%,var(--line))}
|
||||
#listening .now .eq,#listening .now .left{color:var(--accent2)}
|
||||
#listening .now .rail i{background:var(--accent2)}
|
||||
/* Quiet buttons: a filled one on every row outshouted the row that is playing. */
|
||||
#listening [data-a=play],#nowqueue [data-a=play]{color:var(--accent)}
|
||||
#listening [data-a=remove],#nowqueue [data-a=remove]{color:var(--faint)}
|
||||
#listening [data-a=play]{color:var(--accent)}
|
||||
#listening [data-a=remove]{color:var(--faint)}
|
||||
/* The Directory, laid out as Apple's is: a large title, then sections. Every page carries what
|
||||
kind of feed (.tabs, as the item filters are) in its title row. */
|
||||
.dhead{margin-bottom:6px}
|
||||
.dback{display:inline-flex;align-items:center;gap:4px;margin:0 0 8px -5px;padding:3px 5px;border-radius:6px;font-size:13px;color:var(--accent)}
|
||||
.dback{display:inline-flex;align-items:center;gap:5px;margin:0 0 8px -5px;padding:3px 5px;border-radius:6px;font-size:13px;color:var(--accent)}
|
||||
.dback .i{width:11px;height:11px}
|
||||
@media (hover:hover){.dback:hover{background:var(--raise)}}
|
||||
.dtitle{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 18px}
|
||||
@@ -825,7 +781,7 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
|
||||
here reads it beside it, then what it has published lately. */
|
||||
.show{display:flex;gap:22px;align-items:flex-end;margin-top:4px}
|
||||
.show>.art{width:180px;height:180px;font-size:48px;border-radius:12px;box-shadow:var(--shadow)}
|
||||
.show .meta{min-width:0;flex:1;display:flex;flex-direction:column;align-items:flex-start;gap:4px}
|
||||
.show .meta{min-width:0;flex:1;display:flex;flex-direction:column;align-items:flex-start;gap:5px}
|
||||
.show h2{margin:0 0 2px;font-size:30px;line-height:1.15;font-weight:700;letter-spacing:-.02em;overflow-wrap:anywhere}
|
||||
.show .sub{margin:0;color:var(--dim);font-size:13px;font-variant-numeric:tabular-nums}
|
||||
.show .dfail{color:var(--bad)}
|
||||
@@ -843,7 +799,7 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
|
||||
.lep b a{color:var(--fg);text-decoration:none}
|
||||
@media (hover:hover){.lep b a:hover{color:var(--accent)}}
|
||||
.lep p{margin:4px 0 0;color:var(--dim);font-size:13px;line-height:1.5;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3;overflow:hidden}
|
||||
.lep small{display:flex;align-items:center;gap:6px;margin-top:6px;color:var(--faint);font-size:12px;font-variant-numeric:tabular-nums}
|
||||
.lep small{display:flex;align-items:center;gap:7px;margin-top:6px;color:var(--faint);font-size:12px;font-variant-numeric:tabular-nums}
|
||||
/* Outlined, not filled: on --raise the warning and error colours fell short of AA in most light
|
||||
themes, where on the row's own ground they clear it. */
|
||||
.tag{
|
||||
@@ -887,9 +843,6 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
|
||||
#content{display:flex;flex-direction:column;min-height:0;min-width:0;flex:1}
|
||||
#content>.fhead,#content>.toolbar{padding-left:20px;padding-right:20px;flex:none}
|
||||
#content>.fhead{padding-top:16px}
|
||||
/* A page of its own (Up Next, Playlists, Signals) has its own padding already: with this one too its
|
||||
header started twice as far in as a podcast's (#485). */
|
||||
#content.plain>.fhead{padding:0}
|
||||
|
||||
/* Three panes, as the original had: feeds beside, items above, the item below. */
|
||||
#split{
|
||||
@@ -956,7 +909,7 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
|
||||
.fhead .sub{color:var(--dim);font-size:13px;margin-bottom:8px}
|
||||
.fhead .sub a{color:var(--dim);text-decoration:none}
|
||||
@media (hover:hover){.fhead .sub a:hover{color:var(--accent)}}
|
||||
.acts{display:flex;gap:6px;align-items:center;margin-top:auto}
|
||||
.acts{display:flex;gap:7px;align-items:center;margin-top:auto}
|
||||
.acts .btn{display:inline-flex;align-items:center;gap:6px;padding:7px 13px;border-radius:999px}
|
||||
.acts .btn i{font-style:normal;font-size:13px;line-height:1;opacity:.7}
|
||||
@media (hover:hover){.acts .btn:hover{background:var(--raise)}}
|
||||
@@ -998,14 +951,6 @@ kbd{font:inherit;font-size:12px;color:var(--fg);background:var(--panel2);border:
|
||||
.tabs button.on{background:var(--raise);color:var(--fg);font-weight:500}
|
||||
.tabs a{padding:5px 12px;border-radius:7px;font-size:13px;color:var(--dim);text-decoration:none}
|
||||
.tabs a.on{background:var(--raise);color:var(--fg);font-weight:500}
|
||||
/* A podcast's seasons (#482): the tabs' track, scrolled sideways when there are more than fit. */
|
||||
.seasonrow{display:flex;gap:8px;align-items:center;min-width:0;max-width:100%}
|
||||
.tabs.seasons{min-width:0;overflow-x:auto;scrollbar-width:none}
|
||||
.tabs.seasons::-webkit-scrollbar{display:none}
|
||||
.tabs.seasons button{white-space:nowrap;flex:none}
|
||||
/* Where a season starts in the list of every season. */
|
||||
.sdiv{padding:14px 8px 5px;font-size:12px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:var(--dim);border-bottom:1px solid var(--line)}
|
||||
.sdiv:first-child{padding-top:4px}
|
||||
|
||||
/* ---------- the admin page (admin.html) ---------- */
|
||||
/* One column that scrolls under the same header, rather than the app's fixed panes. */
|
||||
@@ -1066,7 +1011,7 @@ body.adminpage #logbox{height:calc(100dvh - 230px);min-height:240px}
|
||||
/* A table, as the original's was: unread, kept, title, feed, file, size, published. */
|
||||
.ephead,.ep{
|
||||
display:grid;gap:8px;align-items:center;
|
||||
grid-template-columns:22px 22px minmax(120px,1fr) minmax(0,160px) 56px minmax(0,72px) minmax(0,92px) 96px;
|
||||
grid-template-columns:22px 22px minmax(120px,1fr) minmax(0,160px) 56px minmax(0,72px) minmax(0,92px) 64px;
|
||||
}
|
||||
/* A pixel more side padding than a row's: a row has a 1px border the heading has not, and without
|
||||
it every heading sat a pixel left of its column. */
|
||||
@@ -1122,11 +1067,11 @@ body.playing .eq i:nth-child(3){animation-delay:-.6s}
|
||||
@keyframes eq{from{transform:scaleY(.35)}}
|
||||
@media (hover:hover){.ep .st:hover,.ep .fl:hover{background:var(--raise)}}
|
||||
.ep .t{font-weight:600;font-size:13.5px;display:block;width:100%;padding:0;text-align:start;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
/* An item with no title shows its opening words: set as text, not as a heading. */
|
||||
.ep .t.notitle{font-weight:400}
|
||||
.ep.read .t{color:var(--dim);font-weight:500}
|
||||
.ep .line{display:flex;gap:8px;align-items:center;flex-wrap:wrap;color:var(--faint);font-size:11.5px}
|
||||
.ep .line{display:flex;gap:9px;align-items:center;flex-wrap:wrap;color:var(--faint);font-size:11.5px}
|
||||
.ep .line:empty{display:none}
|
||||
/* A phone's marks for what the row's buttons say elsewhere (#484). */
|
||||
.ep .udot,.ep .pinmark,.ep .pinmark+.dot{display:none}
|
||||
.ep .kept{display:inline-flex;align-items:center;gap:4px;color:var(--dim)}
|
||||
.ep .kept svg{width:1em;height:1em}
|
||||
.ep .fd,.ep .size,.ep .date{color:var(--dim);font-size:12.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
@@ -1136,7 +1081,7 @@ body.playing .eq i:nth-child(3){animation-delay:-.6s}
|
||||
.ep .file .dlbar{position:absolute;left:0;right:0;bottom:-5px;margin:0}
|
||||
.ep .rowacts{justify-content:flex-end}
|
||||
/* One feed's own table has no need of a Feed column; All Subscriptions does. */
|
||||
#split.one .ephead,#split.one .ep{grid-template-columns:22px 22px minmax(120px,1fr) 56px minmax(0,72px) minmax(0,92px) 96px}
|
||||
#split.one .ephead,#split.one .ep{grid-template-columns:22px 22px minmax(120px,1fr) 56px minmax(0,72px) minmax(0,92px) 64px}
|
||||
#split.one .h-fd,#split.one .ep .fd{display:none}
|
||||
.dot{width:3px;height:3px;border-radius:50%;background:var(--faint);flex:none}
|
||||
.ep .rowacts{display:flex;gap:2px;align-items:flex-start;opacity:0;transition:opacity .12s}
|
||||
@@ -1173,14 +1118,14 @@ body.has-video #audio{
|
||||
#pnow .eq{color:var(--accent2);margin-right:6px}
|
||||
#pnow small{color:var(--faint);font-size:11.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block}
|
||||
#pmid{display:flex;flex-direction:column;gap:3px;min-width:0}
|
||||
#pbtns{display:flex;gap:4px;align-items:center;justify-content:center}
|
||||
#pbtns{display:flex;gap:5px;align-items:center;justify-content:center}
|
||||
#pbtns .iconbtn{width:34px;height:34px}
|
||||
#pplay{
|
||||
width:40px!important;height:40px!important;background:var(--fg);color:var(--bg);
|
||||
border-radius:50%;
|
||||
}
|
||||
@media (hover:hover){#pplay:hover{background:var(--accent);color:var(--ink)}}
|
||||
#seekrow{display:flex;gap:8px;align-items:center;font-variant-numeric:tabular-nums;font-size:11.5px;color:var(--faint)}
|
||||
#seekrow{display:flex;gap:9px;align-items:center;font-variant-numeric:tabular-nums;font-size:11.5px;color:var(--faint)}
|
||||
input[type=range]{
|
||||
-webkit-appearance:none;appearance:none;height:4px;border-radius:3px;flex:1;
|
||||
background:var(--raise);cursor:pointer;
|
||||
@@ -1207,15 +1152,11 @@ input[type=range]::-moz-range-thumb{width:12px;height:12px;border:0;border-radiu
|
||||
overscroll-behavior:contain;
|
||||
}
|
||||
.card.wide{width:min(1000px,100%)}
|
||||
/* The page's own question before something hard to take back (#462): over any dialog already up. */
|
||||
dialog.ask{color:inherit;margin:auto;width:min(420px,calc(100% - 32px))}
|
||||
dialog.ask::backdrop{background:rgba(0,0,0,.6)}
|
||||
dialog.ask p{margin:0;line-height:1.45}
|
||||
#logbox{
|
||||
background:var(--bg);border:1px solid var(--line);border-radius:9px;padding:10px 12px;
|
||||
height:min(60vh,520px);overflow:auto;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;
|
||||
}
|
||||
#logbox .l{display:flex;gap:8px;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
#logbox .l{display:flex;gap:9px;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
#logbox time{color:var(--faint);flex:none}
|
||||
#logbox .lv{flex:none;width:42px;font-weight:700}
|
||||
#logbox .lv.ERROR{color:var(--bad)} #logbox .lv.WARN{color:var(--warn)}
|
||||
@@ -1411,28 +1352,13 @@ body:has(#player.on) #status{padding-bottom:3px}
|
||||
#topbar #epBox{width:auto;flex:1;min-width:0}
|
||||
.tgroup button,.tgroup a{padding:4px 8px;min-width:32px}
|
||||
.fhead.slim .acts{flex:1 1 100%}
|
||||
/* One button, Playlists' and Signals' +, stays beside the title rather than on a line alone (#487). */
|
||||
.fhead.slim .acts:has(>.btn:only-child){flex:none}
|
||||
.fhead.slim:has(>.acts>.btn:only-child) .meta{flex-basis:0}
|
||||
.iconbtn{width:38px;height:38px}
|
||||
|
||||
/* One pane at a time: the list, then the item over it. */
|
||||
#split{grid-template-columns:1fr;grid-template-rows:1fr;grid-template-areas:"list"}
|
||||
/* Title and date only; the files sit above the item's text in the reader instead. */
|
||||
#files,.ephead,.ep .fd,.ep .file,.ep .size,.ep .rowacts{display:none}
|
||||
/* No read or pin button: their two columns cost 77px of a 390px screen before the title, empty
|
||||
once an episode is read (#484). Unread is a dot before the title, pinned a pin under it, and
|
||||
both are changed from the reader's actions. */
|
||||
.ep .st,.ep .fl{display:none}
|
||||
.ep,#split.one .ep{grid-template-columns:minmax(0,1fr) auto}
|
||||
.ep:not(.read) .udot{display:inline-block;width:9px;height:9px;border-radius:50%;background:var(--accent2);margin-inline-end:7px;vertical-align:.12em}
|
||||
/* The line under an unread title starts where the title's text does, past the dot, and the date
|
||||
sits on the title's baseline: centred on the row, it floated between the two lines. */
|
||||
.ep:not(.read) .line{padding-inline-start:16px}
|
||||
.ep .date{align-self:baseline}
|
||||
.ep .pinmark{display:inline-flex;color:var(--dim)}
|
||||
.ep .pinmark+.dot{display:block}
|
||||
.ep .pinmark svg{width:.9em;height:.9em}
|
||||
.ep,#split.one .ep{grid-template-columns:20px 20px minmax(0,1fr) auto}
|
||||
#grab{display:none}
|
||||
#detail{position:fixed;inset:0;z-index:38;display:none;border-top:0;padding:12px 16px 90px;padding-top:calc(12px + var(--safe-t))}
|
||||
body.reading #detail{display:block}
|
||||
@@ -1448,9 +1374,6 @@ body:has(#player.on) #status{padding-bottom:3px}
|
||||
.dfloat #dback{margin:0;width:44px;height:44px;border-radius:999px}
|
||||
.dfloat .dacts{gap:2px;padding:2px 6px;border-radius:999px}
|
||||
#detail .dfloat .dacts .btn{background:transparent;border-color:transparent;box-shadow:none}
|
||||
/* Pinned keeps its accent disc: cleared with the rest, its pin, in the colour drawn on the accent,
|
||||
was white on a light theme's capsule (#480). */
|
||||
#detail .dfloat .dacts .btn[data-a=flag][aria-pressed=true]{background:var(--accent);border-color:var(--accent)}
|
||||
/* Beside the reader while it is swiped (gestures.ts): the item next to it, with a strip of the
|
||||
page's own background between them, so the list under the reader never shows (#52). */
|
||||
#dpeek{position:fixed;top:0;bottom:0;left:0;width:calc(100% + 16px);z-index:38;background:var(--bg);pointer-events:none}
|
||||
@@ -1546,7 +1469,7 @@ body:has(#player.on) #status{padding-bottom:3px}
|
||||
.iconbtn{width:40px;height:40px;border-radius:999px;background:var(--panel2)}
|
||||
.tgroup{border-radius:999px}
|
||||
.tgroup button+button,.tgroup button+a{border-left-color:var(--edge)}
|
||||
.tgroup button,.tgroup a{min-width:40px;height:40px;padding:0 8px}
|
||||
.tgroup button,.tgroup a{min-width:36px;height:40px;padding:0 8px}
|
||||
|
||||
/* Text boxes filled, and at 16px or more: Safari zooms the page in on one any smaller. */
|
||||
input[type=search],input[type=text],input[type=password],input[type=number],select{
|
||||
@@ -1569,20 +1492,15 @@ body:has(#player.on) #status{padding-bottom:3px}
|
||||
|
||||
/* Tabs as a segmented control: equal segments on one track, the chosen one lifted. */
|
||||
.tabs{flex:1 1 100%;border-radius:10px;padding:2px}
|
||||
.tabs button,.tabs a{flex:1;text-align:center;padding:7px 4px;border-radius:8px;font-size:14px;min-height:40px}
|
||||
.tabs button,.tabs a{flex:1;text-align:center;padding:7px 4px;border-radius:8px;font-size:14px}
|
||||
.tabs button.on,.tabs a.on{box-shadow:0 1px 3px rgba(0,0,0,.22)}
|
||||
/* Seasons keep their own widths, scrolling past the edge, rather than squeezing eight into 390px. */
|
||||
.seasonrow{flex:1 1 100%}
|
||||
.seasonrow .tabs.seasons{flex:1 1 auto}
|
||||
.tabs.seasons button{flex:none;padding:7px 12px}
|
||||
|
||||
/* Rows: taller, larger type, and a hairline between them that starts where the text does. */
|
||||
.ep{padding:10px 8px;border-radius:10px;min-height:44px}
|
||||
.ep.sel{border-color:var(--edge)}
|
||||
.ep .t{font-size:17px}
|
||||
.ep .line{font-size:15px}
|
||||
.ep .date{font-size:13px}
|
||||
.ep+.ep{background-image:linear-gradient(var(--line),var(--line));background-size:calc(100% - 8px) 1px;background-position:8px 0;background-repeat:no-repeat}
|
||||
.ep .line,.ep .date{font-size:15px}
|
||||
.ep+.ep{background-image:linear-gradient(var(--line),var(--line));background-size:calc(100% - 64px) 1px;background-position:64px 0;background-repeat:no-repeat}
|
||||
.ep.sel,.ep.sel+.ep{background-image:none}
|
||||
.feed{padding:9px 10px;min-height:44px;border-radius:10px}
|
||||
.places{border-bottom-color:var(--edge);padding-bottom:10px;margin-bottom:10px}
|
||||
@@ -1601,11 +1519,9 @@ body:has(#player.on) #status{padding-bottom:3px}
|
||||
width:100%;max-height:calc(100dvh - var(--safe-t) - 12px);border-color:var(--edge);border-radius:20px 20px 0 0;
|
||||
padding:20px 16px calc(20px + var(--safe-b));animation:sheet .3s cubic-bezier(.2,.8,.2,1);
|
||||
}
|
||||
/* A sheet, as every dialog is here. */
|
||||
dialog.ask{margin:auto 0 0;width:100%;max-width:100%}
|
||||
.card h3{font-size:22px}
|
||||
.field label,.field .hint{font-size:13px}
|
||||
.check{font-size:17px;min-height:40px}
|
||||
.check{font-size:17px}
|
||||
/* A feed's settings, at a phone's sizes. */
|
||||
.card.fset{padding:0}
|
||||
.fsetbody{padding:20px 16px 24px}
|
||||
|
||||
@@ -29,34 +29,13 @@ const WEB_VERSION = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.js
|
||||
// The files are one script, concatenated in this order, not modules: they share one top-level
|
||||
// scope, as the single inline script did, and code that runs at load needs what came before it.
|
||||
const PAGES: Record<string, { script: string, src: string[] }> = {
|
||||
'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'seasons', 'player', 'upnext', 'nowplaying', 'dialogs', 'signals', 'playlists', 'gestures', 'offline', 'events', 'native'] },
|
||||
'admin.html': { script: 'admin.js', src: ['util', 'wire', 'theme', 'admin'] },
|
||||
'index.html': { script: 'app.js', src: ['util', 'theme', 'feeds', 'feedpage', 'items', 'player', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] },
|
||||
'admin.html': { script: 'admin.js', src: ['util', 'theme', 'admin'] },
|
||||
'login.html': { script: 'login.js', src: ['login'] },
|
||||
};
|
||||
// The stylesheet the app and admin pages share, served and named by hash as the scripts are.
|
||||
const STYLE = 'app.css';
|
||||
|
||||
/// The protobuf messages ipx answers in (#470), for web/src/wire.ts: { 'pkg.Name': [[number, name,
|
||||
/// type, repeated, optional]] }, read from crates/wire/proto. Only what those files use: proto3,
|
||||
/// one level of messages, scalar types and messages as field types.
|
||||
export function wireMessages() {
|
||||
const dir = path.join(here, '..', 'crates', 'wire', 'proto');
|
||||
const short: Record<string, string> = { string: 's', bool: 'b', int64: 'i', int32: 'i', uint64: 'u', uint32: 'u', double: 'd' };
|
||||
const out: Record<string, [number, string, string, 0 | 1, 0 | 1][]> = {};
|
||||
for (const file of fs.readdirSync(dir).filter(f => f.endsWith('.proto')).sort()) {
|
||||
const text = fs.readFileSync(path.join(dir, file), 'utf8').replace(/\/\/.*$/gm, '');
|
||||
const pkg = /^\s*package\s+([\w.]+)\s*;/m.exec(text)?.[1];
|
||||
if (!pkg) throw new Error(`${file}: no package`);
|
||||
for (const [, name, body] of text.matchAll(/message\s+(\w+)\s*\{([^}]*)\}/g)) {
|
||||
out[`${pkg}.${name}`] = [...body!.matchAll(/^\s*(optional\s+|repeated\s+)?([\w.]+)\s+(\w+)\s*=\s*(\d+)\s*;/gm)].map(
|
||||
([, label, type, field, num]) => [Number(num), field!, short[type!] ?? (type!.includes('.') ? type! : `${pkg}.${type}`),
|
||||
label?.trim() === 'repeated' ? 1 : 0, label?.trim() === 'optional' ? 1 : 0]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const WIRE = JSON.stringify(wireMessages());
|
||||
|
||||
const hash = (s: string | Buffer) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 12);
|
||||
|
||||
// hls.js, for browsers that cannot play DeadAir's playlists themselves (#181). Served as it comes,
|
||||
@@ -83,7 +62,7 @@ const ICONS_URL = `/icons/index.json?v=${hash(ICONS)}`;
|
||||
|
||||
/// The shared stylesheet, minified. @swc/html minifies CSS inside a page, so it goes through as
|
||||
/// one; the doctype only keeps it from complaining that a fragment has none.
|
||||
export function buildStyle({ minify = !coverageMap } = {}) {
|
||||
export function buildStyle({ minify = true } = {}) {
|
||||
const css = fs.readFileSync(path.join(here, STYLE), 'utf8');
|
||||
if (!minify) return css;
|
||||
const r = html.minifySync(`<!doctype html><style>${css}</style>`, { minifyCss: true, removeComments: true });
|
||||
@@ -99,11 +78,9 @@ export function buildStyle({ minify = !coverageMap } = {}) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/// A script served on its own, not one of the pages' (#392): TypeScript made JavaScript. `before`
|
||||
/// are files put ahead of it, sharing its scope as the pages' files do.
|
||||
function compile(file: string, { minify = true } = {}, before: string[] = []): string {
|
||||
const src = [...before, file].map(f => fs.readFileSync(path.resolve(here, f), 'utf8')).join('\n')
|
||||
.replaceAll('/*__WIRE__*/{}', WIRE);
|
||||
/// A script served on its own, not one of the pages' (#392): TypeScript made JavaScript.
|
||||
function compile(file: string, { minify = true } = {}): string {
|
||||
const src = fs.readFileSync(path.resolve(here, file), 'utf8');
|
||||
return swc.transformSync(src, {
|
||||
filename: path.basename(file),
|
||||
jsc: { parser: { syntax: 'typescript' }, target: 'es2022', minify: minify ? { compress: true, mangle: true } : undefined },
|
||||
@@ -113,7 +90,7 @@ function compile(file: string, { minify = true } = {}, before: string[] = []): s
|
||||
}
|
||||
|
||||
/// The offline service worker (#389), at the top of the site.
|
||||
export const buildWorker = (o?: { minify?: boolean }) => compile('sw/sw.ts', o, ['src/wire.ts']);
|
||||
export const buildWorker = (o?: { minify?: boolean }) => compile('sw/sw.ts', o);
|
||||
/// The directory's one script (#392), as crates/directory/src/site.js holds it: readable, since it
|
||||
/// is committed, and saying where it comes from.
|
||||
export const buildDirectoryScript = () =>
|
||||
@@ -131,8 +108,7 @@ export function buildPage(name: string, { minify = !coverageMap } = {}) {
|
||||
const src = parts.map(p => p.text).join('\n')
|
||||
.replaceAll('__HLS_JS__', HLS_URL)
|
||||
.replaceAll('__ICONS__', ICONS_URL)
|
||||
.replaceAll('__WEB_VERSION__', WEB_VERSION)
|
||||
.replaceAll('/*__WIRE__*/{}', WIRE);
|
||||
.replaceAll('__WEB_VERSION__', WEB_VERSION);
|
||||
const js = swc.transformSync(src, {
|
||||
filename: name + '.ts',
|
||||
jsc: {
|
||||
|
||||
@@ -19,16 +19,16 @@
|
||||
<span id="applogo" title="iPX"><img class="logo onlight" src="/logo.svg" alt="iPX"><img class="logo ondark" src="/logo-dark.svg" alt="iPX"><img class="logo classic" src="/icon.png" alt="iPodderX"></span>
|
||||
<div class="tgroup">
|
||||
<button id="addFeed" title="Add a feed" aria-label="Add a feed" data-icon="plus"></button>
|
||||
<button id="tbRemove" title="Open a feed to unsubscribe from it" aria-label="Unsubscribe from this feed" data-icon="circleMinus" disabled></button>
|
||||
<button id="tbRemove" title="Unsubscribe from this feed" aria-label="Unsubscribe from this feed" data-icon="circleMinus" disabled></button>
|
||||
<button id="scanAll" title="Check every feed for new items" aria-label="Check every feed for new items" data-icon="scan"></button>
|
||||
</div>
|
||||
<div class="tgroup item">
|
||||
<button id="tbPlay" title="Choose an item first" aria-label="Play the selected item" data-icon="play" disabled></button>
|
||||
<button id="tbRead" title="Choose an item first" aria-label="Mark read or unread" data-icon="check" disabled></button>
|
||||
<button id="tbFlag" title="Choose an item first" aria-label="Pin" data-icon="pin" disabled></button>
|
||||
<button id="tbPlay" title="Play the selected item" aria-label="Play the selected item" data-icon="play" disabled></button>
|
||||
<button id="tbRead" title="Mark the selected item read or unread" aria-label="Mark read or unread" data-icon="check" disabled></button>
|
||||
<button id="tbFlag" title="Pin the selected item, so it is never deleted" aria-label="Pin" data-icon="pin" disabled></button>
|
||||
</div>
|
||||
<span class="grow"></span>
|
||||
<span class="clearable" id="epBox"><input type="search" id="epSearch" placeholder="Search" aria-label="Search"><button type="button" class="clearx" title="Clear the search" aria-label="Clear the search" data-icon="close"></button></span>
|
||||
<span class="clearable" id="epBox"><input type="search" id="epSearch" placeholder="Search" aria-label="Search"><button type="button" class="clearx" title="Clear" aria-label="Clear" data-icon="close"></button></span>
|
||||
<div class="tgroup" id="admintools">
|
||||
<button id="prefs" title="Settings" aria-label="Settings" data-icon="settings"></button>
|
||||
<a id="admin" href="/admin" title="Admin: the server's settings, accounts and the log" aria-label="Admin" data-icon="admin"></a>
|
||||
@@ -36,7 +36,7 @@
|
||||
</header>
|
||||
<div id="shell">
|
||||
<aside id="sidebar">
|
||||
<div class="searchwrap"><span class="clearable"><input type="search" id="feedFilter" placeholder="Filter feeds…" aria-label="Filter feeds"><button type="button" class="clearx" title="Clear the filter" aria-label="Clear the filter" data-icon="close"></button></span></div>
|
||||
<div class="searchwrap"><span class="clearable"><input type="search" id="feedFilter" placeholder="Filter feeds…" aria-label="Filter feeds"><button type="button" class="clearx" title="Clear" aria-label="Clear" data-icon="close"></button></span></div>
|
||||
<div id="feedlist"></div>
|
||||
<div class="sidefoot">
|
||||
<div class="who"><span id="who"></span><button id="signout" title="Sign out" aria-label="Sign out" data-icon="signout"></button></div>
|
||||
@@ -46,12 +46,11 @@
|
||||
<div class="wrap" id="content"></div>
|
||||
</div>
|
||||
<div id="scrim" hidden></div>
|
||||
<section id="nowsheet" aria-label="Now Playing" hidden></section>
|
||||
</div>
|
||||
<div id="status"><span id="count"></span></div>
|
||||
|
||||
<div id="player">
|
||||
<div id="pnow" role="button" tabindex="0" aria-expanded="false" aria-controls="nowsheet" title="Now Playing">
|
||||
<div id="pnow">
|
||||
<div id="partwrap"></div>
|
||||
<div class="txt"><b><span class="eq" aria-hidden="true"><i></i><i></i><i></i></span><span id="ptitle"></span></b><small id="pfeed"></small></div>
|
||||
</div>
|
||||
@@ -60,7 +59,6 @@
|
||||
<button class="iconbtn" id="pback" title="Back 15 seconds (←)" aria-label="Back 15 seconds" data-icon="back"></button>
|
||||
<button class="iconbtn" id="pplay" title="Play or pause (space)" aria-label="Play or pause" data-icon="play"></button>
|
||||
<button class="iconbtn" id="pfwd" title="Forward 30 seconds (→)" aria-label="Forward 30 seconds" data-icon="fwd"></button>
|
||||
<button class="iconbtn" id="pnext" hidden title="Play the next in Up Next" aria-label="Play the next in Up Next" data-icon="next"></button>
|
||||
</div>
|
||||
<div id="seekrow">
|
||||
<span id="pcur">0:00</span>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<title>Sign in to iPX</title>
|
||||
<title>Sign in — iPX</title>
|
||||
<link rel="icon" type="image/png" sizes="128x128" href="/favicon.png" media="(prefers-color-scheme:light)">
|
||||
<link rel="icon" type="image/png" sizes="128x128" href="/favicon-dark.png" media="(prefers-color-scheme:dark)">
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
|
||||
@@ -63,9 +63,9 @@ async function drawServer(){
|
||||
: 'This server has no TypeSafe key (<code>TYPESAFE_KEY</code>), so each person uses their own.'}</p>
|
||||
${anum('gsigdays', 'A new Signal looks back', g.signal_days, 'days', ' min="1" max="365"')}
|
||||
<p class="cap">Each item read is a call to TypeSafe, so a longer look back costs more, once for each new Signal.</p>`)}
|
||||
<div class="afoot"><button class="btn primary" id="gsave" title="Nothing changed yet" disabled>${ICON.check} Save</button></div>`;
|
||||
<div class="afoot"><button class="btn primary" id="gsave" disabled>${ICON.check} Save</button></div>`;
|
||||
// Save waits for a change, so it says whether there is one.
|
||||
box.oninput = () => { dim($<HTMLButtonElement>('#gsave'), null, 'Save'); };
|
||||
box.oninput = () => { $<HTMLButtonElement>('#gsave').disabled = false; };
|
||||
$<HTMLButtonElement>('#gsave').onclick = async () => {
|
||||
try{
|
||||
await api('/api/settings', {method: 'PATCH', body: JSON.stringify({
|
||||
@@ -79,7 +79,7 @@ async function drawServer(){
|
||||
// Left alone while the server has no key to offer, rather than switched off.
|
||||
...($<HTMLInputElement>('#gsig').disabled ? {} : {signals_on_server: $<HTMLInputElement>('#gsig').checked})})});
|
||||
toast('Settings saved');
|
||||
dim($<HTMLButtonElement>('#gsave'), 'Nothing changed yet', 'Save');
|
||||
$<HTMLButtonElement>('#gsave').disabled = true;
|
||||
}catch(e){ toast(why(e), true); }
|
||||
};
|
||||
}
|
||||
@@ -156,7 +156,7 @@ async function drawDirectoryStatus(){
|
||||
const sh = s.shared;
|
||||
if(sh){
|
||||
const when = new Date(sh.at * 1000).toLocaleString();
|
||||
lines.push(sh.error ? `Unable to share at ${esc(when)}: ${esc(sh.error)}`
|
||||
lines.push(sh.error ? `Sharing failed at ${esc(when)}: ${esc(sh.error)}`
|
||||
: `Shared ${plural(sh.accepted, 'feed')} at ${esc(when)}.` +
|
||||
(sh.refused_private ? ` The directory refused ${plural(sh.refused_private, 'feed')} as private.` : '') +
|
||||
(sh.refused_blocked ? ` ${plural(sh.refused_blocked, 'feed')} the directory has removed.` : ''));
|
||||
@@ -191,7 +191,7 @@ async function drawDirectoryAdmin(){
|
||||
try{
|
||||
if(b.dataset.a === 'drop'){
|
||||
const name = row!.dataset.name!;
|
||||
if(!await ask(`Drop ${name}'s feeds and counts from the directory? They come back the next time ${name} shares.`, 'Drop')) return;
|
||||
if(!confirm(`Drop ${name}'s feeds and counts from the directory? They come back the next time ${name} shares.`)) return;
|
||||
await api(`/api/directory-instances/${encodeURIComponent(name)}`, {method: 'DELETE'});
|
||||
toast(`Dropped ${name}'s snapshot`);
|
||||
}else if(b.dataset.a === 'unblock'){
|
||||
@@ -235,8 +235,8 @@ async function drawAccounts(){
|
||||
const u = users.find(x => String(x.id) === row.dataset.id)!;
|
||||
$('[data-a="admin"]', row).onchange = (e: Event) =>
|
||||
change(u, {method: 'PATCH', body: JSON.stringify({admin: (e.target as HTMLInputElement).checked})});
|
||||
$('[data-a="rm"]', row).onclick = async () => {
|
||||
if(await ask(`Remove ${u.name}? Their subscriptions and read state go with them. Downloaded files stay.`, 'Remove'))
|
||||
$('[data-a="rm"]', row).onclick = () => {
|
||||
if(confirm(`Remove ${u.name}? Their subscriptions and read state go with them. Downloaded files stay.`))
|
||||
change(u, {method: 'DELETE'});
|
||||
};
|
||||
}
|
||||
@@ -272,7 +272,7 @@ function drawLogView(){
|
||||
<div class="tabs" id="logtabs">
|
||||
${Object.keys(LOG_TABS).map(t =>
|
||||
`<button data-t="${t}" class="${logTab === t ? 'on' : ''}" title="${LOG_TAB_SAYS[t]}">${
|
||||
{all: 'All', daemon: 'Daemon I/O', scan: 'Checks', web: 'HTTP'}[t]}</button>`).join('')}
|
||||
{all: 'All', daemon: 'Daemon I/O', scan: 'Scans', web: 'HTTP'}[t]}</button>`).join('')}
|
||||
</div></div>
|
||||
<div class="logbar">
|
||||
<select id="loglevel" aria-label="Level">
|
||||
|
||||
@@ -35,8 +35,8 @@ $('#modal').onclick=(e: MouseEvent)=>{ if((e.target as Element).id==='modal') cl
|
||||
|
||||
$<HTMLButtonElement>('#addFeed').onclick=()=>{
|
||||
openModal(`<h3>Add a feed</h3>
|
||||
<div class="field"><label for="nurl">Feed address</label><input type="text" id="nurl" placeholder="https://example.com/rss">
|
||||
<span class="hint">A Patreon token on its own adds every podcast from that creator.</span></div>
|
||||
<div class="field"><label for="nurl">Feed URL</label><input type="text" id="nurl" placeholder="https://example.com/rss">
|
||||
<span class="hint">A Patreon token on its own adds every show from that creator.</span></div>
|
||||
<div class="field"><label for="nkw">Keywords (optional, comma separated)</label>
|
||||
<input type="text" id="nkw"><span class="hint">Only items matching a keyword are downloaded.</span></div>
|
||||
<label class="check"><input type="checkbox" id="nexp"> Allow items marked explicit</label>
|
||||
@@ -108,7 +108,7 @@ let dirShow: string|null=null;
|
||||
// Apple's or one an admin typed, neither of which starts with a colon.
|
||||
const EVERY=':every', OTHER=':other';
|
||||
const NAME=(p: {title: string|null, id: string})=>(p.title||p.id);
|
||||
const byName=(a: DirFeed,b: DirFeed)=>nameOrder(NAME(a),NAME(b));
|
||||
const byName=(a: DirFeed,b: DirFeed)=>NAME(a).localeCompare(NAME(b),undefined,{sensitivity:'base',numeric:true});
|
||||
const bySubs=(a: DirFeed,b: DirFeed)=>b.subscribers-a.subscribers||byName(a,b);
|
||||
/// The grid's orders. It opens A to Z, as the server sends it.
|
||||
const DIR_SORTS: Record<string,[string,(a: DirFeed,b: DirFeed)=>number]>={
|
||||
@@ -269,7 +269,7 @@ async function fillShow(box: HTMLElement,p: DirFeed){
|
||||
catch(e){ toast(why(e),true); }
|
||||
};
|
||||
$('[data-a="dremove"]',acts).onclick=async()=>{
|
||||
if(!await ask(`Remove ${NAME(p)} from the directory? It is blocked, so no server's snapshot brings it back. Admin, Directory can unblock it.`, 'Remove')) return;
|
||||
if(!confirm(`Remove ${NAME(p)} from the directory? It is blocked, so no server's snapshot brings it back. Admin, Directory can unblock it.`)) return;
|
||||
try{ await api(`/api/directory/${encodeURIComponent(p.id)}`,{method:'DELETE'}); }
|
||||
catch(e){ return toast(why(e),true); }
|
||||
toast(`Removed ${NAME(p)} from the directory`);
|
||||
@@ -279,9 +279,7 @@ async function fillShow(box: HTMLElement,p: DirFeed){
|
||||
}
|
||||
const items=got.items;
|
||||
list.innerHTML=items.length?items.map(e=>{
|
||||
const name=entryName(e), words=plainText(e.description);
|
||||
// No excerpt that only repeats the name ipx made from these same words (#502).
|
||||
const text=name.derived||titleEchoes(e,words)?'':words.slice(0,500);
|
||||
const name=entryName(e), text=name.derived?'':plainText(e.description).slice(0,500);
|
||||
const when=[dateOf(e.published),e.duration&&clock(e.duration)].filter(Boolean);
|
||||
return `<article class="lep"><b>${webUrl(e.link)?`<a href="${esc(webUrl(e.link))}" target="_blank" rel="noopener">${esc(name.text)}</a>`:esc(name.text)}</b>`
|
||||
+(text?`<p>${esc(text)}</p>`:'')
|
||||
@@ -303,7 +301,7 @@ function catTile(c: string,name: string,count: string,rows: DirFeed[]){
|
||||
async function renderListed(v: {title: string, icon: string, url?: string, blurb?: string}){
|
||||
const box=$('#content');
|
||||
box.classList.add('plain');
|
||||
dim($<HTMLButtonElement>('#tbRemove'),NO_FEED,UNSUB);
|
||||
$<HTMLButtonElement>('#tbRemove').disabled=true;
|
||||
syncTools(null);
|
||||
if(v===VIEWS[':directory']){
|
||||
$<HTMLInputElement>('#epSearch').placeholder='Find a feed…';
|
||||
@@ -312,7 +310,6 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb
|
||||
await renderDirectory(v.url!,$('#directory'),n=>{ if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'feed')}`; });
|
||||
return;
|
||||
}
|
||||
if(v===VIEWS[':podcasts']){ drawShelf(box); return; }
|
||||
$<HTMLInputElement>('#epSearch').setAttribute('aria-label','Search items');
|
||||
box.innerHTML=`
|
||||
<div class="fhead slim">
|
||||
@@ -321,31 +318,11 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb
|
||||
</div>
|
||||
<div class="childlist" id="listening"></div>`;
|
||||
$('#count').textContent=v.title;
|
||||
if(v===VIEWS[':upnext']){ drawUpNext(); return; }
|
||||
// The search box looks through these too, title and text, as it does a feed's items (#127).
|
||||
await renderListening(S.q?`${v.url}&q=${encodeURIComponent(S.q)}`:v.url!,$('#listening',box),
|
||||
n=>{ if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'episode')}`; });
|
||||
}
|
||||
|
||||
/// The Podcasts shelf (#474): every feed with audio or video, as its artwork, with how many of its
|
||||
/// episodes are new. A tap opens it. The search box narrows it by name.
|
||||
function drawShelf(box: HTMLElement){
|
||||
$<HTMLInputElement>('#epSearch').setAttribute('aria-label','Search podcasts');
|
||||
const q=S.q.trim().toLowerCase();
|
||||
const shows=S.feeds.filter(f=>f.podcast&&(!q||(f.title||f.id).toLowerCase().includes(q)));
|
||||
$('#count').textContent=`Podcasts: ${plural(shows.length,'podcast')}`;
|
||||
box.innerHTML=shows.length?'<div class="shelf"></div>'
|
||||
:`<p class="hint">${q?`No podcast is called “${esc(S.q)}”.`:'No podcasts yet. Add a feed with episodes in it, and it shows here.'}</p>`;
|
||||
const shelf=$('.shelf',box);
|
||||
for(const f of shows){
|
||||
const name=f.title||f.id, b=document.createElement('button');
|
||||
b.type='button'; b.className='show';
|
||||
b.innerHTML=`${artHTML(f.image,name)}<b>${esc(name)}</b><small>${f.unread?`${f.unread} new`:''}</small>`;
|
||||
b.onclick=()=>selectFeed(f.id);
|
||||
shelf.appendChild(b);
|
||||
}
|
||||
}
|
||||
|
||||
/// Currently Listening: episodes you started and have not finished, across every feed you
|
||||
/// subscribe to. A row resumes the episode in the player bar on click -- a shortcut back to
|
||||
/// where you left off, not another way to browse. The one in the player pauses instead.
|
||||
@@ -365,26 +342,22 @@ async function renderListening(url: string,box: HTMLElement,counted: (n: number)
|
||||
function drawListening(box: HTMLElement,rows: Entry[]){
|
||||
box.innerHTML=rows.length?'':S.q?`<p class="hint">Nothing you are listening to mentions “${esc(S.q)}”.</p>`
|
||||
:'<p class="hint">Nothing in progress. Episodes you start and do not finish show up here.</p>';
|
||||
for(const e of rows) box.appendChild(listenRow(e,'Remove from Currently Listening',()=>forget(e)));
|
||||
}
|
||||
/// An episode's row in Currently Listening and Up Next: its art, how far in, play, and a button
|
||||
/// to take it out of the list, which `remove` does. `start` plays it: a playlist's goes on through
|
||||
/// the playlist.
|
||||
function listenRow(e: Entry,removeLabel: string,remove: ()=>void,start=()=>play(e)){
|
||||
// Carries its episode, for paintListenRow to repaint as the player moves.
|
||||
const el: HTMLDivElement & {entry?: Entry}=document.createElement('div');
|
||||
el.className='childrow';
|
||||
el.entry=e;
|
||||
el.innerHTML=artHTML(e.image||feedArt(e.feed_id),e.title||'')+
|
||||
`<div class="txt"><b>${EQ}<span>${esc(entryName(e).text)}</span></b>`+
|
||||
`<small><span class="fd">${esc(feedName(e.feed_id))}</span><span class="left"></span></small></div>`+
|
||||
`<button class="iconbtn" data-a="play"></button>`+
|
||||
`<button class="iconbtn" data-a="remove" title="${removeLabel}" aria-label="${removeLabel}">${ICON.close}</button>`+
|
||||
`<div class="rail"><i></i></div>`;
|
||||
el.onclick=ev=>(ev.target as Element).closest('[data-a=remove]')?remove()
|
||||
:el.classList.contains('now')&&!audio.paused?audio.pause():start();
|
||||
paintListenRow(el);
|
||||
return el;
|
||||
for(const e of rows){
|
||||
// Carries its episode, for paintListenRow to repaint as the player moves.
|
||||
const el: HTMLDivElement & {entry?: Entry}=document.createElement('div');
|
||||
el.className='childrow';
|
||||
el.entry=e;
|
||||
el.innerHTML=artHTML(e.image||feedArt(e.feed_id),e.title||'')+
|
||||
`<div class="txt"><b>${EQ}<span>${esc(entryName(e).text)}</span></b>`+
|
||||
`<small><span class="fd">${esc(feedName(e.feed_id))}</span><span class="left"></span></small></div>`+
|
||||
`<button class="iconbtn" data-a="play"></button>`+
|
||||
`<button class="iconbtn" data-a="remove" title="Remove from Currently Listening" aria-label="Remove from Currently Listening">${ICON.close}</button>`+
|
||||
`<div class="rail"><i></i></div>`;
|
||||
el.onclick=ev=>(ev.target as Element).closest('[data-a=remove]')?forget(e)
|
||||
:el.classList.contains('now')&&!audio.paused?audio.pause():play(e);
|
||||
paintListenRow(el);
|
||||
box.appendChild(el);
|
||||
}
|
||||
}
|
||||
|
||||
/// One row's time left, progress and play button, taken from the player when it is the one in it.
|
||||
@@ -404,7 +377,7 @@ function paintListenRow(el: HTMLElement & {entry?: Entry}){
|
||||
}
|
||||
/// Keeps the list in step with the player. Only a row that is, or was, the one in it changes.
|
||||
function syncListening(){
|
||||
for(const el of $$<HTMLElement & {entry?: Entry}>('#listening .childrow, #nowqueue .childrow'))
|
||||
for(const el of $$<HTMLElement & {entry?: Entry}>('#listening .childrow'))
|
||||
if(el.entry&&(el.classList.contains('now')||inPlayer(el.entry))) paintListenRow(el);
|
||||
}
|
||||
|
||||
@@ -433,7 +406,7 @@ $<HTMLInputElement>('#epSearch').oninput=(ev: Event)=>{ clearTimeout(searchT);
|
||||
// server (#126, #127).
|
||||
searchT=setTimeout(()=>{ S.q=(ev.target as HTMLInputElement).value; S.offset=0;
|
||||
if(S.feed===':directory'){ dirShow=null; drawDirectory(); }
|
||||
else if(S.feed===':listening'||S.feed===':podcasts') renderListed(VIEWS[S.feed]);
|
||||
else if(S.feed===':listening') renderListed(VIEWS[':listening']);
|
||||
else loadEntries(); },250); };
|
||||
// Crossing the phone breakpoint moves the files between their pane and the text.
|
||||
window.matchMedia?.('(max-width:820px)')?.addEventListener?.('change',()=>{ const e=cur(); if(e) showDetail(e); });
|
||||
@@ -459,7 +432,7 @@ function due(ts: number){
|
||||
function deadSavedText(me: Me|null){
|
||||
const s=me&&me.deadair_saved||0;
|
||||
return s?`It has saved you ${spanText(s)} of dead air, on episodes you heard three quarters of or more.`
|
||||
:'Turn it on in a podcast\'s settings, or beside the speed while it plays, to cut the dead air from it.';
|
||||
:'Turn it on in a show\'s settings, or beside the speed while it plays, to cut the dead air from it.';
|
||||
}
|
||||
|
||||
async function prefsModal(){
|
||||
@@ -474,7 +447,7 @@ async function prefsModal(){
|
||||
<div class="field" id="smodefield"${THEMES[theme.name].modes?'':' hidden'}><label for="smode">Light or dark</label>
|
||||
<select id="smode">${Object.entries(MODES).map(([k,t])=>
|
||||
`<option value="${k}"${theme.mode===k?' selected':''}>${esc(t)}</option>`).join('')}</select>
|
||||
<span class="hint">Auto follows your system's light or dark setting.</span></div>
|
||||
<span class="hint">Auto follows your system's light/dark setting.</span></div>
|
||||
<div class="field"><label for="sfont">Interface font</label>
|
||||
<select id="sfont">${Object.entries(FONTS).map(([k,t])=>
|
||||
`<option value="${k}"${font===k?' selected':''}>${esc(t)}</option>`).join('')}</select></div>
|
||||
@@ -558,11 +531,11 @@ async function prefsModal(){
|
||||
renderFeeds();
|
||||
}catch(err){ toast(why(err),true); }
|
||||
};
|
||||
$<HTMLInputElement>('#ssigon').onchange=async(e: Event)=>{
|
||||
$<HTMLInputElement>('#ssigon').onchange=(e: Event)=>{
|
||||
const on=(e.target as HTMLInputElement).checked;
|
||||
if(on){ $('#ssigkey').hidden=false; $<HTMLInputElement>('#stskey').focus(); return; }
|
||||
if(!S.me?.typesafe_key_set){ $('#ssigkey').hidden=true; return; }
|
||||
if(await ask('Turn Signals off and forget your TypeSafe key? Your signals are kept for when you turn them on again.', 'Turn off')) saveKey(null);
|
||||
if(confirm('Turn Signals off and forget your TypeSafe key? Your signals are kept for when you turn them on again.')) saveKey(null);
|
||||
else (e.target as HTMLInputElement).checked=true;
|
||||
};
|
||||
$<HTMLInputElement>('#stskey').onchange=(e: Event)=>{ const k=(e.target as HTMLInputElement).value.trim(); if(k) saveKey(k); };
|
||||
@@ -654,7 +627,7 @@ function settingsModal(f: Feed, newUrl?: string){
|
||||
// Each part named in a column of its own, the controls beside it (#290): the dialog had grown one
|
||||
// captioned setting at a time into a single column three screens long on a phone.
|
||||
const sect=(title: string, body: string)=>`<section class="fsec"><h4>${title}</h4><div class="fsecin">${body}</div></section>`;
|
||||
const these=isGroup?'these podcasts':'this podcast';
|
||||
const these=isGroup?'these shows':'this show';
|
||||
// The places in the sidebar this show's items go to, drawn as the sidebar draws them (#288, #289).
|
||||
const place=(id: string, key: 'hide_from_all'|'hide_from_signals', icon: string, title: string)=>{
|
||||
const byList=f.group?S.feeds.find(g=>g.id===f.group&&g[key]):undefined;
|
||||
@@ -712,7 +685,7 @@ function settingsModal(f: Feed, newUrl?: string){
|
||||
|
||||
// The download limit, said as what it does. A number in a box hid that it is a window on the
|
||||
// newest items, not a pace through the back catalogue (#97).
|
||||
const each=isGroup?' of each podcast':'';
|
||||
const each=isGroup?' of each show':'';
|
||||
const older=' Older ones stay listed, to download by hand.';
|
||||
const caption=()=>mode==='newest'
|
||||
? `Downloads the newest <input type="number" id="smax" min="1" value="${newest}"
|
||||
@@ -809,7 +782,7 @@ function downloadLatestModal(f: Feed){
|
||||
openModal(`<h3>Download latest items</h3>
|
||||
<div class="field"><label for="dcount">How many of the newest undownloaded items?</label>
|
||||
<input type="number" id="dcount" min="1" max="100" value="5">
|
||||
<span class="hint">Downloaded now, past the limit on each check.</span></div>
|
||||
<span class="hint">Queued immediately, ignoring the per-scan limit.</span></div>
|
||||
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Cancel" aria-label="Cancel">${ICON.close}</button>
|
||||
<button class="btn ico primary" id="dgo" title="Download" aria-label="Download">${ICON.download}</button></div>`);
|
||||
$<HTMLButtonElement>('#dgo').onclick=async()=>{
|
||||
|
||||
@@ -31,7 +31,7 @@ function connect(){
|
||||
// every pending bar at once, so adding a feed looked like it was fetching the lot.
|
||||
const bar=document.querySelector<HTMLElement>(`.dlbar[data-bar="${ev.enclosure}"] i`);
|
||||
if(bar){ bar.style.width=pct+'%'; bar.parentElement!.classList.add('live'); }
|
||||
$('#count') && ($('#count').textContent=`Downloading ${ev.file}: ${pct.toFixed(0)}%`);
|
||||
$('#count') && ($('#count').textContent=`downloading ${ev.file} — ${pct.toFixed(0)}%`);
|
||||
}
|
||||
else if(ev.ev==='download_done'){
|
||||
const bar=document.querySelector(`.dlbar[data-bar="${ev.enclosure}"]`);
|
||||
@@ -138,5 +138,3 @@ function offerReload(){
|
||||
}
|
||||
connect();
|
||||
loadFeeds().then(preloadLists).catch(()=>{});
|
||||
loadUpNext();
|
||||
loadPlaylists();
|
||||
|
||||
@@ -23,12 +23,9 @@ function renderFeed(){
|
||||
const v=VIEWS[S.feed ?? ''];
|
||||
if(v&&v.url) return renderListed(v);
|
||||
if(S.feed===SIGNALS) return renderSignals();
|
||||
if(S.feed===PLAYLISTS) return renderPlaylists();
|
||||
const pl=playlistOf(S.feed);
|
||||
if(pl) return renderPlaylist(pl);
|
||||
const f=v?null:S.feeds.find(x=>x.id===S.feed);
|
||||
const sg=signalOf(S.feed);
|
||||
dim($<HTMLButtonElement>('#tbRemove'),f?null:NO_FEED,UNSUB);
|
||||
$<HTMLButtonElement>('#tbRemove').disabled=!f;
|
||||
syncTools(null);
|
||||
if(!v&&!f&&!sg){ box.innerHTML='<p class="empty">Add a feed to get started.</p>'; $('#count').textContent=''; return; }
|
||||
const name=f?(f.title||f.id):sg?sg.name:v.title;
|
||||
@@ -99,28 +96,22 @@ function renderFeed(){
|
||||
renderFeed(); loadEntries();
|
||||
});
|
||||
if(f) wireFailBanner(box,f);
|
||||
// An OPML's page is many podcasts' episodes together, their seasons each their own.
|
||||
if(f&&!kids.length) loadSeasons(f);
|
||||
}
|
||||
|
||||
/// The item table's headings, each a button that sorts by its column. The first click goes the
|
||||
/// natural way round (A to Z; newest, largest and kept first) and the next one reverses it.
|
||||
const COLS=[['kept','Pinned',ICON.pin],['title','Title'],['feed','Feed'],['type','File'],['size','Size'],['published','Published']];
|
||||
function sortHead(){
|
||||
const now=sortFor(S.feed ?? '');
|
||||
return '<div class="ephead"><span></span>'+COLS.map(([k,label,icon])=>{
|
||||
const on=now.col===k;
|
||||
const on=S.sort.col===k;
|
||||
return `<button class="hs${on?' on':''}${k==='feed'?' h-fd':''}${icon?' h-ic':''}" data-sort="${k}"`+
|
||||
` title="Sort by ${label.toLowerCase()}" aria-label="Sort by ${label.toLowerCase()}">${icon||label}`+
|
||||
`${on?`<span class="arr ${now.dir}">${ICON.caret}</span>`:''}</button>`;
|
||||
`${on?`<span class="arr ${S.sort.dir}">${ICON.caret}</span>`:''}</button>`;
|
||||
}).join('')+'<span></span></div>';
|
||||
}
|
||||
function sortBy(col: string){
|
||||
const first=['published','size','kept'].includes(col)?'desc':'asc';
|
||||
// From a seasoned podcast's own order (#482), the first click is that column's first way round.
|
||||
const now=sortFor(S.feed ?? '');
|
||||
S.sort={col,dir:now.col===col?(now.dir==='asc'?'desc':'asc'):first};
|
||||
sortPicked=true;
|
||||
S.sort={col,dir:S.sort.col===col?(S.sort.dir==='asc'?'desc':'asc'):first};
|
||||
try{ localStorage.setItem('ipx.sort',JSON.stringify(S.sort)); }catch{}
|
||||
S.offset=0; renderFeed(); loadEntries();
|
||||
}
|
||||
@@ -196,7 +187,7 @@ async function allAction(a: string){
|
||||
const n=S.feeds.reduce((k,x)=>k+(x.unread||0),0);
|
||||
if(!n){ toast('Nothing unread'); return; }
|
||||
// One click across every feed is a lot to take back, so this one asks first.
|
||||
if(!await ask(`Mark all ${n} unread item${n===1?'':'s'} read, in every feed you subscribe to?`, 'Mark all read')) return;
|
||||
if(!confirm(`Mark all ${n} unread item${n===1?'':'s'} read, in every feed you subscribe to?`)) return;
|
||||
try{
|
||||
const r=await api('/api/read-all',{method:'POST'});
|
||||
haptic('done'); toast(`Marked ${r.marked} read`); await loadFeeds(true); renderFeed(); loadEntries();
|
||||
|
||||
@@ -20,12 +20,12 @@ async function loadFeeds(keepSel?: boolean){
|
||||
// All Subscriptions rather than picking one alphabetically. Nothing to land on at all (a
|
||||
// brand new account) leaves S.feed alone, so the empty state's own message shows instead.
|
||||
if(!keepSel && S.feeds.length){
|
||||
const known = S.feed && (VIEWS[S.feed] || S.feed===SIGNALS || signalOf(S.feed) || S.feed===PLAYLISTS || playlistOf(S.feed) || S.feeds.some(f=>f.id===S.feed));
|
||||
const known = S.feed && (VIEWS[S.feed] || S.feed===SIGNALS || signalOf(S.feed) || S.feeds.some(f=>f.id===S.feed));
|
||||
selectFeed(known ? S.feed! : ':all');
|
||||
}
|
||||
}
|
||||
// An OPML can hold dozens of feeds; the ones with something new go first. sort is stable, so the
|
||||
// list's order by name (renderFeeds) still holds within each half.
|
||||
// server's alphabetical order still holds within each half.
|
||||
const unreadFirst=(a: Feed,b: Feed)=>Number(b.unread>0)-Number(a.unread>0);
|
||||
// The original's source list opened with these, above the feeds. They are places, not feeds:
|
||||
// an id starting with ':' can never be a feed's, since feed ids are slugs.
|
||||
@@ -34,10 +34,6 @@ const VIEWS: Record<string,{title: string, icon: string, url?: string, blurb?: s
|
||||
':directory':{title:'Directory',icon:ICON.directory,url:'/api/directory'},
|
||||
':listening':{title:'Currently Listening',icon:ICON.audio,url:'/api/entries?filter=in_progress&limit=50',
|
||||
blurb:'Episodes you started and have not finished, across every feed you subscribe to. Pick one up where you left off.'},
|
||||
':upnext':{title:'Up Next',icon:ICON.queue,url:'/api/queue',
|
||||
blurb:'Episodes lined up to play, in order. Each one plays when the one before it ends.'},
|
||||
// Drawn from the feed list the page already has; the address is only what marks it a place.
|
||||
':podcasts':{title:'Podcasts',icon:ICON.podcasts,url:'/api/feeds'},
|
||||
':all':{title:'All Subscriptions',icon:ICON.all},
|
||||
};
|
||||
/// Whether a feed's items are in All Subscriptions, or in Signals: not when it, or the OPML or
|
||||
@@ -95,9 +91,6 @@ function spinEnd(done?: {only: string|null, forced: boolean}){
|
||||
}
|
||||
|
||||
function renderFeeds(){
|
||||
// By name, not the server's order, which is by id: a slug of the title, so The Rest Is Science
|
||||
// was under T (#481). Here, so a feed a live update adds or renames takes its place too.
|
||||
S.feeds.sort((a,b)=>nameOrder(a.title||a.id,b.title||b.id));
|
||||
const q=$<HTMLInputElement>('#feedFilter').value.trim().toLowerCase();
|
||||
const list=$('#feedlist'); const top=list.scrollTop;
|
||||
// Every row is replaced, so put the keyboard back on the row, or the triangle, it was on.
|
||||
@@ -123,8 +116,7 @@ function renderFeeds(){
|
||||
el.className='place'+(S.feed===id?' sel':'');
|
||||
el.tabIndex=0; el.dataset.id=id;
|
||||
el.innerHTML=`<span class="ico">${v.icon}</span><b>${v.title}</b>`+(id===':all'
|
||||
?`<span class="badge${unreadAll?'':' zero'}" title="${unreadAll} unread">${unreadAll>999?'999+':unreadAll}</span>`
|
||||
:id===':upnext'&&upNext.length?`<span class="badge" title="${plural(upNext.length,'episode')}">${upNext.length}</span>`:'');
|
||||
?`<span class="badge${unreadAll?'':' zero'}" title="${unreadAll} unread">${unreadAll>999?'999+':unreadAll}</span>`:'');
|
||||
asLink(el,S.feed===id);
|
||||
el.onclick=()=>{ selectFeed(id); nav(false); };
|
||||
el.onpointerenter=el.ontouchstart=()=>prefetch(id);
|
||||
@@ -132,7 +124,6 @@ function renderFeeds(){
|
||||
}
|
||||
list.appendChild(places);
|
||||
signalFolder(list,q);
|
||||
playlistFolder(list,q);
|
||||
const shown=S.feeds.filter(f=>!q||(f.title||f.id).toLowerCase().includes(q));
|
||||
if(!shown.length){ list.insertAdjacentHTML('beforeend','<p class="empty" style="padding:20px 8px">No feeds.</p>'); return done(); }
|
||||
|
||||
@@ -181,11 +172,11 @@ function renderFeeds(){
|
||||
// The mark sits on the artwork, the thing the eye scans the list by, and the line under
|
||||
// the name says what is wrong in place of the counts.
|
||||
`<span class="fart">${mine.length?folderArt(f,mine):artHTML(f.image,f.title||f.id)}`+
|
||||
(err?`<span class="ferr" role="img" title="${esc(err)}" aria-label="Not updating: ${esc(err)}">${ICON.alert}</span>`:'')+
|
||||
(err?`<span class="ferr" role="img" title="${esc(err)}" aria-label="Error: ${esc(err)}">${ICON.alert}</span>`:'')+
|
||||
(f.pinned?`<span class="fpin" role="img" title="Pinned" aria-label="Pinned">${ICON.pinOn}</span>`:'')+`</span>`+
|
||||
`<div class="txt"><b>${esc(f.title||f.id)}</b><small>`+
|
||||
(nbad?`${plural(nbad,'feed')} not updating`
|
||||
:err?esc(f.failing?.reason||'Unable to read it at the last check')
|
||||
:err?esc(f.failing?.reason||'The last check failed')
|
||||
:`${mine.length?plural(mine.length,'feed'):plural(eps,'item')} · ${saved} downloaded`)+
|
||||
`</small></div>`+
|
||||
(f.orphaned?'<span class="tag" title="No longer listed, kept because it has downloads">Gone</span>':'')+
|
||||
@@ -202,18 +193,9 @@ function renderFeeds(){
|
||||
done();
|
||||
}
|
||||
function selectFeed(id: string){
|
||||
S.feed=id; S.offset=0; S.sel=null; S.q=''; S.season=''; sortPicked=false; $<HTMLInputElement>('#epSearch').value='';
|
||||
S.feed=id; S.offset=0; S.sel=null; S.q=''; $<HTMLInputElement>('#epSearch').value='';
|
||||
try{ localStorage.setItem('ipx.feed',id); }catch{}
|
||||
markSelected(); renderFeed(); loadEntries();
|
||||
}
|
||||
/// The highlight moved to the feed now open. Rebuilding every row for it, as selecting once did,
|
||||
/// was a third of a list's drawing time on a phone.
|
||||
function markSelected(){
|
||||
for(const el of $$<HTMLElement>('#feedlist [data-id]')){
|
||||
const on=el.dataset.id===S.feed;
|
||||
el.classList.toggle('sel',on);
|
||||
if(on) el.setAttribute('aria-current','page'); else el.removeAttribute('aria-current');
|
||||
}
|
||||
renderFeeds(); renderFeed(); loadEntries();
|
||||
}
|
||||
|
||||
/// A failing feed's error, in plain words with something to do about it, once `failing` is
|
||||
|
||||
@@ -118,8 +118,6 @@ function beside(dx: number){
|
||||
/// beside it with it.
|
||||
function slide(dx: number, ms = 160){
|
||||
const d = $('#detail'); if(!d) return;
|
||||
// Only a move across: every touch in the reader that is not a swipe ends in slide(0) (#488).
|
||||
if(dx) slidAt = Date.now();
|
||||
dx = Math.round(dx); // whole pixels, or the seam between the reader and its neighbour blurs
|
||||
const w = d.clientWidth || 1, tr = ms ? `transform ${ms}ms ease-out, opacity ${ms}ms ease-out` : 'none';
|
||||
d.style.transition = tr;
|
||||
@@ -150,31 +148,7 @@ function slideOn(dx: number, go: () => void){
|
||||
const to = dir * (w + (beside(dx).className === 'dim' ? 0 : GAP));
|
||||
const ms = still() ? 0 : Math.round(Math.max(120, 250 * (1 - Math.abs(dx) / (w || 1))));
|
||||
slide(to, ms);
|
||||
// The preview stays over the reader until the new item's pictures are drawn (#471): swapped at
|
||||
// once, its text came a frame before the picture above it, and flashed where the picture would be.
|
||||
setTimeout(() => { go(); drawn($('#detail'), 300).then(() => { if(!touch) slide(0, 0); }); }, ms);
|
||||
}
|
||||
|
||||
/// The pictures of the items either side of the one open, fetched and decoded ahead (#471): the
|
||||
/// preview a swipe draws is built as the drag begins, and its picture loaded only then came in
|
||||
/// after its text, flashing and pushing the text down under the finger. Held here, so the browser
|
||||
/// keeps them decoded; a few each, since only the top of an item shows in the preview.
|
||||
let warm: HTMLImageElement[] = [];
|
||||
function warmNeighbours(){
|
||||
if(!narrow()) return;
|
||||
const i = S.entries.findIndex(x => entryKey(x) === S.sel);
|
||||
const html = [S.entries[i - 1], S.entries[i + 1]].filter(e => e).map(e => textOf(e!)).join('');
|
||||
// Parsed, not put in the page: a document from DOMParser loads none of its pictures.
|
||||
const srcs = [...new DOMParser().parseFromString(html, 'text/html').images].slice(0, 6).map(i => i.src);
|
||||
warm = srcs.map(src => { const im = new Image(); im.src = src; im.decode().catch(() => {}); return im; });
|
||||
}
|
||||
|
||||
/// When the pictures in `el` are decoded and ready to draw, or `max` ms, whichever is sooner, so a
|
||||
/// slow picture never holds up the page.
|
||||
function drawn(el: HTMLElement | null, max: number): Promise<unknown> {
|
||||
const pending = [...el?.querySelectorAll('img') ?? []].filter(i => !i.complete || !i.naturalWidth);
|
||||
if(!pending.length) return Promise.resolve();
|
||||
return Promise.race([Promise.all(pending.map(i => i.decode().catch(() => {}))), new Promise(r => setTimeout(r, max))]);
|
||||
setTimeout(() => { go(); slide(0, 0); }, ms);
|
||||
}
|
||||
|
||||
document.addEventListener('touchend', () => {
|
||||
@@ -207,11 +181,7 @@ document.addEventListener('touchcancel', () => { if(touch?.pane === 'list') pull
|
||||
/// way, after which it has not moved. Watched by where the finger is, not by what it landed on,
|
||||
/// so something lying over the reader is caught too, and named. Reported with what could hold it,
|
||||
/// since the cause of the one in #383 was never found.
|
||||
// What #450's three reports could not say (#450): where the finger began, whether the page saw it
|
||||
// move at all (none means the browser kept the drag for itself), whether the page cancelled the
|
||||
// touch, and how long since the reader was last slid across, the one thing a swipe changes on it.
|
||||
let drag: {x: number, y: number, t: number, top: number, on: string, moves: number, cancelled: boolean} | null = null,
|
||||
shownAt = Date.now(), slidAt = 0;
|
||||
let drag: {x: number, y: number, top: number, on: string} | null = null, shownAt = Date.now();
|
||||
document.addEventListener('visibilitychange', () => { if(!document.hidden) shownAt = Date.now(); });
|
||||
const named = (el: Element | null) => !el ? 'nothing'
|
||||
: el.id ? '#' + el.id : el.tagName.toLowerCase() + (typeof el.className === 'string' && el.className ? '.' + el.className.split(' ')[0] : '');
|
||||
@@ -226,37 +196,14 @@ document.addEventListener('touchstart', ev => {
|
||||
if(ev.touches.length !== 1 || !d || !S.sel) return;
|
||||
const r = d.getBoundingClientRect();
|
||||
if(t.clientX < r.left || t.clientX > r.right || t.clientY < r.top || t.clientY > r.bottom) return;
|
||||
drag = {x: t.clientX, y: t.clientY, t: Date.now(), top: d.scrollTop, on: named(ev.target as Element), moves: 0, cancelled: false};
|
||||
// After the swipe's own touchstart, which may cancel it, has run.
|
||||
queueMicrotask(() => { if(drag) drag.cancelled = ev.defaultPrevented; });
|
||||
drag = {x: t.clientX, y: t.clientY, top: d.scrollTop, on: named(ev.target as Element)};
|
||||
}, {passive: true});
|
||||
document.addEventListener('touchmove', () => { if(drag) drag.moves++; }, {passive: true});
|
||||
document.addEventListener('touchend', ev => {
|
||||
const d = $('#detail'), t = ev.changedTouches[0], g = drag;
|
||||
drag = null;
|
||||
if(!g || !d || !t) return;
|
||||
const dy = t.clientY - g.y, dx = t.clientX - g.x, room = d.scrollHeight - d.clientHeight, ms = Date.now() - g.t;
|
||||
if(!stuckDrag(dy, dx, g.top, d.scrollTop, room)) return;
|
||||
// Looked at again a moment later: iOS scrolls off the main thread, and a fast flick can end
|
||||
// before the page has been told where it went (#488).
|
||||
setTimeout(() => {
|
||||
if(stuckDrag(dy, dx, g.top, d.scrollTop, room)) stuck(d, t, g, dy, room, ms);
|
||||
}, 300);
|
||||
});
|
||||
/// Makes iOS build the reader's scroller again (#450): every stuck drag was on a reader whose
|
||||
/// content had been swapped, with nothing over it and the touch left alone, which is WebKit keeping
|
||||
/// a scroller sized for what was there before. Two frames without overflow, so the hidden state is
|
||||
/// committed and not merged away with the change back.
|
||||
function rearm(d: HTMLElement){
|
||||
d.style.overflowY = 'hidden';
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => { d.style.overflowY = ''; }));
|
||||
}
|
||||
let stuckAt = 0;
|
||||
function stuck(d: HTMLElement, t: Touch, g: NonNullable<typeof drag>, dy: number, room: number, ms: number){
|
||||
rearm(d);
|
||||
// A second report soon after the first says rearm did not free it.
|
||||
const again = stuckAt ? Math.round((Date.now() - stuckAt) / 1000) + 's ago' : 'never';
|
||||
stuckAt = Date.now();
|
||||
const dy = t.clientY - g.y, room = d.scrollHeight - d.clientHeight;
|
||||
if(!stuckDrag(dy, t.clientX - g.x, g.top, d.scrollTop, room)) return;
|
||||
const inert = ([...document.body.children] as HTMLElement[]).filter(el => el.inert).map(named).join(' ');
|
||||
report('scroll_stuck', {feed: S.feed, state: [
|
||||
`top ${g.top} of ${room}`, `drag ${Math.round(dy)}px`, `started on ${g.on}`,
|
||||
@@ -264,7 +211,5 @@ function stuck(d: HTMLElement, t: Touch, g: NonNullable<typeof drag>, dy: number
|
||||
`inert ${inert || 'none'}`, `dialog ${$('#modal')?.classList.contains('on') ? 'open' : 'closed'}`,
|
||||
`transform ${d.style.transform || 'none'}`, `peek ${$('#dpeek') ? 'left behind' : 'gone'}`,
|
||||
`overflow ${getComputedStyle(d).overflowY}`, `reading ${document.body.classList.contains('reading')}`,
|
||||
`shown ${Math.round((Date.now() - shownAt) / 1000)}s ago`, `${S.entries.length} loaded`,
|
||||
`from x ${Math.round(g.x)}`, `${g.moves} moves seen in ${ms}ms`, `touch ${g.cancelled ? 'cancelled' : 'left alone'}`,
|
||||
`slid ${slidAt ? Math.round((Date.now() - slidAt) / 1000) + 's ago' : 'never'}`, `last stuck ${again}`].join(', ')});
|
||||
}
|
||||
`shown ${Math.round((Date.now() - shownAt) / 1000)}s ago`, `${S.entries.length} loaded`].join(', ')});
|
||||
});
|
||||
|
||||
@@ -14,13 +14,10 @@ const lists=new Map<string,ListPage>();
|
||||
const LISTS_KEPT=40;
|
||||
/// Lists on their way, so a click on one already being fetched ahead waits for that answer.
|
||||
const fetching=new Map<string,Promise<ListPage>>();
|
||||
// A season is of the podcast open (#482): another feed's list, fetched ahead, is of every season.
|
||||
const seasonFor=(feed: string)=>feed===S.feed?S.season:'';
|
||||
const listKey=(feed: string, filter=S.filter)=>[feed,filter,sortFor(feed).col,sortFor(feed).dir,S.q,seasonFor(feed)].join('\n');
|
||||
const listKey=(feed: string, filter=S.filter)=>[feed,filter,S.sort.col,S.sort.dir,S.q].join('\n');
|
||||
function listUrl(feed: string, filter=S.filter, offset=0){
|
||||
const p=new URLSearchParams({offset:String(offset),limit:String(LIMIT),filter,sort:sortFor(feed).col,dir:sortFor(feed).dir});
|
||||
const p=new URLSearchParams({offset:String(offset),limit:String(LIMIT),filter,sort:S.sort.col,dir:S.sort.dir});
|
||||
if(S.q) p.set('q',S.q);
|
||||
if(seasonFor(feed)) p.set('season',seasonFor(feed));
|
||||
const sg=signalId(feed);
|
||||
return feed===':all' ? `/api/entries?${p}`
|
||||
: sg!==null ? `/api/signals/${sg}/entries?${p}`
|
||||
@@ -81,7 +78,7 @@ function preloadLists(){
|
||||
/// `quiet` for a refresh nobody asked for (a live update): not a wait anyone sees, so not timed.
|
||||
async function loadEntries(append?: boolean, quiet?: boolean){
|
||||
// The Directory lists feeds, and Currently Listening draws its own episodes.
|
||||
if(!S.feed || VIEWS[S.feed]?.url || S.feed===SIGNALS || S.feed===PLAYLISTS || playlistOf(S.feed)) return;
|
||||
if(!S.feed || VIEWS[S.feed]?.url || S.feed===SIGNALS) return;
|
||||
const feed=S.feed, key=listKey(feed), asked=performance.now(), seq=++loadSeq;
|
||||
// From asking to the list drawn: what someone waits for after a click, under that click's trace
|
||||
// (#246). Once, when the list first shows: from what is kept, at once.
|
||||
@@ -146,7 +143,7 @@ function renderEntries(){
|
||||
const f=S.feeds.find(x=>x.id===S.feed), v=VIEWS[S.feed ?? ''], sg=signalOf(S.feed);
|
||||
// An OPML's own row counts nothing: its shows do.
|
||||
const kids=f?S.feeds.filter(c=>c.group===f.id):[];
|
||||
const unread=kids.length?kids.reduce((n,x)=>n+x.unread,0):f?(seasonUnread(f.id)??f.unread):sg?sg.unread:unreadInAll();
|
||||
const unread=kids.length?kids.reduce((n,x)=>n+x.unread,0):f?f.unread:sg?sg.unread:S.feeds.reduce((n,x)=>n+(x.unread||0),0);
|
||||
$('#count').textContent=
|
||||
`${f?(f.title||f.id):sg?sg.name:v?v.title:''}: ${S.total} item${S.total===1?'':'s'}, ${unread} unread`;
|
||||
const pane=$('#list'), top=pane?pane.scrollTop:0;
|
||||
@@ -158,14 +155,7 @@ function renderEntries(){
|
||||
else if(sg&&S.filter==='all') box.innerHTML='<p class="empty">Nothing has come through yet. New items are read as your feeds are checked.</p>';
|
||||
return;
|
||||
}
|
||||
const breaks=seasonBreaks();
|
||||
let last: number|null|undefined;
|
||||
S.entries.forEach((e,i)=>{
|
||||
if(breaks&&(i===0||(e.season??null)!==(last??null)))
|
||||
box.insertAdjacentHTML('beforeend',`<div class="sdiv" role="heading" aria-level="3">${seasonName(e.season)}</div>`);
|
||||
last=e.season;
|
||||
box.appendChild(epEl(e));
|
||||
});
|
||||
for(const e of S.entries) box.appendChild(epEl(e));
|
||||
syncPlayButtons();
|
||||
if(pane) pane.scrollTop=top;
|
||||
if(hasMore()){
|
||||
@@ -195,16 +185,12 @@ function epEl(e: Entry){
|
||||
<button class="st" data-a="read" title="Mark ${e.read?'unread':'read'}" aria-label="Mark ${e.read?'unread':'read'}">${
|
||||
inPlayer(e)?EQ:(e.read?'':'<span aria-hidden="true">●</span>')}</button>
|
||||
<button class="fl${e.flagged?' on':''}" data-a="flag" aria-pressed="${!!e.flagged}" title="${
|
||||
e.flagged?'Unpin':'Pin, so it is never deleted'}" aria-label="${e.flagged?'Unpin':'Pin, so it is never deleted'}">${e.flagged?ICON.pinOn:ICON.pin}</button>
|
||||
e.flagged?'Unpin':'Pin, so it is never deleted'}">${e.flagged?ICON.pinOn:ICON.pin}</button>
|
||||
<div class="body">
|
||||
<button type="button" class="t">${e.read?'':'<span class="udot" role="img" aria-label="Unread"></span>'}${esc(name.text)}</button>
|
||||
<button type="button" class="t${name.derived?' notitle':''}">${esc(name.text)}</button>
|
||||
<div class="line">${[
|
||||
// On a phone, where the row has no pin button, what says it is pinned (#484).
|
||||
e.flagged&&`<span class="pinmark" role="img" aria-label="Pinned">${ICON.pinOn}</span>`,
|
||||
num&&`<span>${num}</span>`,
|
||||
// Not on a phone, where it took a second line under a title the others do not have, and
|
||||
// the reader says it anyway.
|
||||
left&&!window.matchMedia?.('(max-width:820px)')?.matches&&`<span>${left}</span>`,
|
||||
left&&`<span>${left}</span>`,
|
||||
others>0&&`<span>+${others} more file${others===1?'':'s'}</span>`,
|
||||
enc&&enc.deadair&&enc.deadair>0&&`<span title="DeadAir cut its dead air">${shorter(enc.deadair)}</span>`,
|
||||
enc&&enc.deadair_pending&&DEAD_PENDING,
|
||||
@@ -219,12 +205,11 @@ function epEl(e: Entry){
|
||||
${enc&&!has?`<div class="dlbar" data-bar="${enc.id}"><i></i></div>`:''}
|
||||
</div>
|
||||
<span class="size">${enc?mb(enc.length):''}</span>
|
||||
<span class="date" title="${dateOf(e.published)}">${rowDate(e.published)}</span>
|
||||
<span class="date">${dateOf(e.published)}</span>
|
||||
<div class="rowacts">
|
||||
${enc&&playsKind(enc)?queueButton(e):''}
|
||||
${playable?`<button class="iconbtn" data-a="play" title="Play" aria-label="Play">${ICON.play}</button>`:
|
||||
(enc&&!has?`<button class="iconbtn" data-a="get" title="Download this ${
|
||||
enc.state==='skipped'?kindOf(enc):'file'}" aria-label="Download this ${enc.state==='skipped'?kindOf(enc):'file'}">${ICON.download}</button>`:'')}
|
||||
enc.state==='skipped'?kindOf(enc):'file'}">${ICON.download}</button>`:'')}
|
||||
${has?`<button class="iconbtn" data-a="del" title="Delete file" aria-label="Delete file">${ICON.trash}</button>`:''}
|
||||
</div>`;
|
||||
el.onclick=()=>selectEntry(e);
|
||||
@@ -266,7 +251,7 @@ function kindIcon(enc: Enclosure){
|
||||
const k=kindOf(enc);
|
||||
const i=(<Record<string,string>>{audio:ICON.audio,video:ICON.video,image:ICON.image,pdf:ICON.doc,torrent:ICON.torrent})[k]||ICON.file;
|
||||
const [cls,label]=enc.path ? [' here',`${k}, downloaded`]
|
||||
: enc.state==='error' ? [' bad',`${k}, unable to download${enc.last_error?': '+enc.last_error:''}`]
|
||||
: enc.state==='error' ? [' bad',`${k}, download failed${enc.last_error?': '+enc.last_error:''}`]
|
||||
: ['',k];
|
||||
return `<span class="kind${cls}" title="${esc(label)}" aria-label="${esc(label)}">${i}</span>`;
|
||||
}
|
||||
@@ -277,19 +262,13 @@ const feedName=(id: string|null|undefined): string=>{ const f=S.feeds.find(x=>x.
|
||||
/// What an item is called. Its title, or for one published without (RSS 2.0 makes it optional,
|
||||
/// and Scripting News titles almost none of its posts) the opening of its text, then its file's
|
||||
/// name, then its feed and date: "(untitled)" fifty times down a list said nothing about any of
|
||||
/// them. `derived` marks a name that is not a title, which the reader does not repeat as its text.
|
||||
/// them. `derived` marks a name that is not a title, which the list sets as text, not heading.
|
||||
/// Feed HTML as plain words. An inert document: nothing in it loads or runs, where a detached
|
||||
/// element fetches its images. A line break or paragraph's end is a space, or "2010)<br>Recorded"
|
||||
/// read "2010)Recorded".
|
||||
const plainText=(html?: string|null)=>html
|
||||
? (new DOMParser().parseFromString(html.replace(/<(br|\/p|\/div|\/li|\/h\d)\b[^>]*>/gi,' $&'),'text/html').body.textContent||'')
|
||||
.replace(/\s+/g,' ').trim() : '';
|
||||
/// Whether the title is only the opening of the item's own text: the name ipx gives an untitled
|
||||
/// item as it stores it (#502), or a post titled by its first sentence. Shown above that text, it
|
||||
/// reads twice.
|
||||
const titleEchoes=(e: Partial<Entry>, words=plainText(e.description))=>
|
||||
!!e.title && !!words && words.startsWith(e.title.trim().replace(/\u2026$/,''));
|
||||
// ipx names an untitled item as it stores it (#502); this is for a list saved offline before then.
|
||||
function entryName(e: Partial<Entry>): {text: string, derived: boolean}{
|
||||
if(e.title&&e.title.trim()) return {text:e.title, derived:false};
|
||||
const words=plainText(e.description);
|
||||
@@ -356,7 +335,6 @@ function selectEntry(e: Entry,turning=false){
|
||||
showDetail(e);
|
||||
const d=$('#detail'); if(d) d.scrollTop=0;
|
||||
if(turning) loadAhead();
|
||||
warmNeighbours();
|
||||
}
|
||||
|
||||
/// Where the next page starts. On the Unread tab the items read here are no longer unread on the
|
||||
@@ -399,12 +377,8 @@ function dragSplit(pane: HTMLElement){
|
||||
/// Which item the toolbar's play, read and keep buttons act on.
|
||||
const cur=()=>S.entries.find(x=>entryKey(x)===S.sel);
|
||||
function syncTools(e: Entry|null){
|
||||
const pick=e?null:'Choose an item first';
|
||||
dim($<HTMLButtonElement>('#tbPlay'),pick??(e!.enclosures.some(isPlayable)?null:'Nothing to play in this item'),'Play the selected item');
|
||||
dim($<HTMLButtonElement>('#tbRead'),pick,e?`Mark ${e.read?'unread':'read'}`:'');
|
||||
dim($<HTMLButtonElement>('#tbFlag'),pick,e?.flagged?'Unpin':'Pin, so it is never deleted');
|
||||
// The play button says Pause when the item chosen is the one playing.
|
||||
syncPlayButtons();
|
||||
$<HTMLButtonElement>('#tbPlay').disabled=!(e&&e.enclosures.some(isPlayable));
|
||||
$<HTMLButtonElement>('#tbRead').disabled=$<HTMLButtonElement>('#tbFlag').disabled=!e;
|
||||
// The same icons as the item's own buttons beside its title, so the two never disagree. Each
|
||||
// shows what is, as the pin always did: read showed what a click would do, so the two side by
|
||||
// side said opposite things (#74). The shape carries it, not the colour.
|
||||
@@ -412,6 +386,10 @@ function syncTools(e: Entry|null){
|
||||
$<HTMLButtonElement>('#tbRead').setAttribute('aria-pressed',String(!!(e&&e.read)));
|
||||
$<HTMLButtonElement>('#tbFlag').setAttribute('aria-pressed',String(!!(e&&e.flagged)));
|
||||
$<HTMLButtonElement>('#tbFlag').innerHTML=e&&e.flagged?ICON.pinOn:ICON.pin;
|
||||
if(e){
|
||||
$<HTMLButtonElement>('#tbRead').title=`Mark ${e.read?'unread':'read'}`;
|
||||
$<HTMLButtonElement>('#tbFlag').title=e.flagged?'Unpin':'Pin, so it is never deleted';
|
||||
}
|
||||
}
|
||||
|
||||
/// The item's text in the pane below the list, and its files in the pane beside it.
|
||||
@@ -433,7 +411,6 @@ function showDetail(e: Entry|null){
|
||||
const narrow=!!window.matchMedia?.('(max-width:820px)')?.matches;
|
||||
box.innerHTML=detailHtml(e);
|
||||
if(files) files.innerHTML=narrow?'':`<div class="fhd">Files</div>${encs}`;
|
||||
if(narrow) rearm(box);
|
||||
$<HTMLButtonElement>('#dback').onclick=()=>showDetail(null);
|
||||
const view=box.querySelector<HTMLSelectElement>('.tview');
|
||||
if(view) view.onchange=()=>{
|
||||
@@ -461,7 +438,6 @@ function detailHtml(e: Entry){
|
||||
aria-label="Mark ${e.read?'unread':'read'}" aria-pressed="${!!e.read}">${e.read?ICON.check:ICON.unread}</button>
|
||||
<button class="btn ico" data-a="flag" title="${e.flagged?'Pinned: never deleted. Unpin':'Pin, so it is never deleted'}"
|
||||
aria-label="${e.flagged?'Unpin':'Pin'}" aria-pressed="${!!e.flagged}">${e.flagged?ICON.pinOn:ICON.pin}</button>
|
||||
${e.enclosures.some(playsKind)?queueButton(e,'btn ico'):''}
|
||||
${webUrl(e.link)?`<a class="btn ico" href="${esc(webUrl(e.link))}" target="_blank" rel="noopener noreferrer"
|
||||
title="Open the original" aria-label="Open the original">${ICON.open}</a>
|
||||
<button class="btn ico" data-a="share" title="Share" aria-label="Share">${ICON.share}</button>`:''}</span>`;
|
||||
@@ -471,7 +447,7 @@ function detailHtml(e: Entry){
|
||||
at hand anywhere in a long post, not only back at its top. */
|
||||
narrow ? `<div class="dfloat">${back}${acts}</div>` : back}
|
||||
${/* A post without a title starts with its text: its own first words as a heading above
|
||||
themselves would read as a mistake. */ e.title&&e.title.trim()&&!titleEchoes(e) ? `<h3 class="dt">${esc(e.title)}</h3>` : ''}
|
||||
themselves would read as a mistake. */ e.title&&e.title.trim() ? `<h3 class="dt">${esc(e.title)}</h3>` : ''}
|
||||
<div class="dmeta">
|
||||
${/* Joined, so a missing date or number leaves no stray dot behind. */
|
||||
[f&&esc(f.title||f.id), num, dateOf(e.published), e.duration&&clock(e.duration),
|
||||
@@ -503,7 +479,7 @@ function whereText(x: Enclosure){
|
||||
if(here) return 'On this device';
|
||||
if(wanted.has(x.id)) return 'Downloading to iPX, then this device';
|
||||
if(x.state==='pending') return 'Queued for iPX';
|
||||
if(x.state==='error') return 'Unable to download to iPX';
|
||||
if(x.state==='error') return 'iPX could not download it';
|
||||
return 'Publisher only';
|
||||
}
|
||||
return here ? 'On iPX and this device' : busy ? 'On iPX, downloading to this device' : 'On iPX';
|
||||
@@ -589,7 +565,7 @@ const shareAt=(url: string, secs: number)=>secs>=5 ? `${url}?t=${Math.floor(secs
|
||||
function noLinkNote(why: string|null, url: string): string{
|
||||
const notes: string[]=[];
|
||||
if(why==='private') notes.push('This podcast\'s feed is private to you, so it gets no page anyone can play, and its file is never shared: this is the episode\'s own page.');
|
||||
else if(why==='failed') notes.push('Unable to make a page anyone can play just now, so this is the episode\'s own address. Try again later for a link to it.');
|
||||
else if(why==='failed') notes.push('The page anyone can play could not be made just now, so this is the episode\'s own address. Try again later for a link to it.');
|
||||
if(carriesAccess(url)) notes.push(ACCESS_WARNING);
|
||||
return notes.map(n=>`<p class="hint">${esc(n)}</p>`).join('');
|
||||
}
|
||||
@@ -618,7 +594,7 @@ async function shareEpisode(e: Entry, encId: number|null){
|
||||
const at=!link.url ? 0 : player.guid===e.guid && player.feed===e.feed_id ? audio.currentTime : e.position;
|
||||
// A menu rather than the share sheet at once, for the item's own address too: the sheet needs a
|
||||
// press of its own, and the request above has used up the one that opened this (#452). The
|
||||
// warning is written here, not asked first, since it is in the menu anyway.
|
||||
// warning is written here, not asked with confirm(), which the iOS app answers Cancel (#453).
|
||||
openModal(`<button class="iconbtn cardx" onclick="closeModal()" title="Close" aria-label="Close">${ICON.close}</button>
|
||||
<h3>Share</h3><p class="hint">${esc(name)}</p>
|
||||
${link.url ? '' : noLinkNote(link.why, url)}
|
||||
@@ -649,7 +625,6 @@ async function epAction(a: string, e: Entry, el: HTMLElement|null, encId?: numbe
|
||||
try{
|
||||
if(a==='play'){ haptic('tap'); play(e, encId!=null ? enc : undefined); }
|
||||
if(a==='offline' && enc) await toggleKept(enc, entryName(e).text);
|
||||
if(a==='queue'||a==='playnext'){ haptic('tap'); await toggleQueued(e, a==='playnext'); }
|
||||
if(a==='share') await shareEpisode(e, encId??null);
|
||||
if(a==='flag'){ e.flagged=!e.flagged; await api(path+'/flags',{method:'POST',body:JSON.stringify({flagged:e.flagged})}); haptic('tap'); redraw(); }
|
||||
if(a==='read'){ await setRead(e,!e.read); haptic(e.read?'done':'tap'); redraw(); }
|
||||
@@ -666,17 +641,17 @@ async function epAction(a: string, e: Entry, el: HTMLElement|null, encId?: numbe
|
||||
if(a==='del'){
|
||||
const f=S.feeds.find(x=>x.id===e.feed_id);
|
||||
const shared=f&&f.subscribers>1;
|
||||
if(!await ask(shared
|
||||
? `Delete this file? There is one copy, shared with ${f.subscribers-1} other `
|
||||
if(!confirm(shared
|
||||
? `Delete this file?\n\nThere is one copy, shared with ${f.subscribers-1} other `
|
||||
+`${f.subscribers===2?'person':'people'} reading this feed. The item stays listed `
|
||||
+`and will not be downloaded again automatically.`
|
||||
: 'Delete the downloaded file? The item stays listed and will not be downloaded again automatically.', 'Delete')) return;
|
||||
: 'Delete the downloaded file?\n\nThe item stays listed and will not be downloaded again automatically.')) return;
|
||||
try{
|
||||
await api(`/api/enclosures/${enc.id}`,{method:'DELETE'});
|
||||
}catch(err){
|
||||
// 409: somebody else has it starred or unplayed. Their reason, their words.
|
||||
if(!/one copy of this file/.test(why(err))) throw err;
|
||||
if(!await ask(why(err), 'Delete it anyway')) return;
|
||||
if(!confirm(why(err)+'\n\nDelete it anyway?')) return;
|
||||
await api(`/api/enclosures/${enc.id}?force=true`,{method:'DELETE'});
|
||||
}
|
||||
toast('Deleted'); loadEntries(); loadFeeds(true);
|
||||
|
||||
@@ -11,5 +11,5 @@ document.getElementById('f')!.onsubmit = async e => {
|
||||
}),
|
||||
});
|
||||
if (r.ok) location.href = '/';
|
||||
else msg.textContent = await r.text() || 'Unable to sign in. Check your name and password.';
|
||||
else msg.textContent = await r.text() || 'Sign in failed';
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user