Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c957db7f61 | |||
| 4e0b5eed5d | |||
| a9991545f9 | |||
| 60007d4e6a | |||
| 1471b9b9d0 | |||
| ec2b9e87b8 | |||
| af6eae9baf | |||
| 78704e40f2 | |||
| f20660a7d5 | |||
| a5e64e520d | |||
| 7ecbe8293f | |||
| 8d7a30d1f9 | |||
| cece114d98 | |||
| f00adf5da5 | |||
| d787bd26ec | |||
| 382f51a480 | |||
| 45c9f9252b | |||
| e4b505564c | |||
| 4cf568b263 | |||
| 724764c8df | |||
| cc155274e9 | |||
| 02bfa9571b | |||
| 1b137d6969 |
@@ -43,7 +43,7 @@ Start every check by seeing that all three run, since Loki cannot see a containe
|
||||
docker ps -a --filter name=iPX --filter name=ipx-web --filter name=ipx-directory --format '{{.Names}} {{.Status}}'
|
||||
```
|
||||
|
||||
All three should be `(healthy)`. Then work through ipx (the checks below), the page, the
|
||||
All three should be `Up`, with no recent restart; they have no Docker healthcheck (#218). Then work through ipx (the checks below), the page, the
|
||||
directory, Tower and the monitoring itself, in that order.
|
||||
|
||||
## ipx
|
||||
@@ -96,7 +96,8 @@ from 2026-10-11 15:15 UTC. All gauges:
|
||||
| `ipx_torrent_slots_free` | of 2 |
|
||||
| `ipx_deadair_playing` | episodes being played through DeadAir's playlist |
|
||||
| `ipx_runtime_workers`, `ipx_runtime_tasks`, `ipx_runtime_queue` | tokio: threads, live tasks, tasks waiting for a thread |
|
||||
| `ipx_process_resident_bytes`, `ipx_process_open_fds` | memory and open files and sockets |
|
||||
| `ipx_process_resident_bytes`, `ipx_process_open_fds` | memory and open files and sockets; mimalloc gives back what is freed, so memory follows use and a rise that never comes down is a leak (#224) |
|
||||
| `ipx_feed_fetches_total`, `ipx_feed_bytes_total` | counters: feeds fetched (304s included) and the bytes of their bodies, read whole, so what scans allocate |
|
||||
| `ipx_uptime_seconds`, `ipx_build_info{version}` | since the daemon started; what runs |
|
||||
| `ipx_worker_busy`, `ipx_worker_job_seconds{kind}` | the worker's job now (`scan`, `reap`, `download`, `status`, `reload`) and for how long; the healthcheck passes while it is stuck |
|
||||
| `ipx_jobs_total{kind}`, `ipx_job_seconds_total{kind}` | counters: jobs finished, and their seconds all told |
|
||||
@@ -108,6 +109,7 @@ from 2026-10-11 15:15 UTC. All gauges:
|
||||
| `ipx_feed_retries` | feeds waiting to retry a failed name lookup |
|
||||
| `ipx_art_cache_bytes`, `ipx_art_cache_limit_bytes` | artwork kept, as of the last sweep, and the most kept: kept sits at the limit by design |
|
||||
| `ipx_art_evicted_total`, `ipx_art_requests_total{result="hit"\|"miss"}` | counters: images the sweep threw out to stay under the limit, and artwork served from disk or fetched from the publisher; many evicted at every sweep with a falling hit rate means the limit is too small |
|
||||
| `directory_process_resident_bytes`, `directory_process_open_fds`, `directory_feed_fetches_total`, `directory_feed_bytes_total`, `directory_uptime_seconds`, `directory_build_info` | the directory's, `job="ipx-directory"`, from its `metrics_bind` (production `192.168.1.130:9188`, LAN only) |
|
||||
| `ipx_feeds`, `ipx_downloads_pending`, `ipx_files_downloaded` | the library, as the healthcheck last counted it (every 30 s) |
|
||||
|
||||
### The checks
|
||||
@@ -226,8 +228,8 @@ a count says something happened, the lines and traces say why.
|
||||
|
||||
Caddy logs one JSON line a request (#210), logger `http.log.access.log0`: Loki's `| json` gives
|
||||
`request_uri`, `request_method`, `request_remote_ip`, `status`, `duration` (seconds, not ms), `size`.
|
||||
The request's headers and a `?token=` are filtered out before it is written. Its healthcheck
|
||||
requests come from `127.0.0.1` every 30 s; leave them out. `/api` and `/media` pass on to ipx and
|
||||
The request's headers and a `?token=` are filtered out before it is written. Requests from
|
||||
`127.0.0.1` are local checks; leave them out. `/api` and `/media` pass on to ipx and
|
||||
are in ipx's own access log too, with ipx's time; Caddy's `duration` for them adds the hop.
|
||||
|
||||
```sh
|
||||
|
||||
26
CLAUDE.md
26
CLAUDE.md
@@ -103,11 +103,13 @@ docker tag mirror.gcr.io/library/rust:1-slim-trixie rust:1-slim-trixie
|
||||
|
||||
Run those again now and then, or the local copies go stale.
|
||||
|
||||
The healthcheck runs `ipx status` against the control socket, so `(healthy)` in `docker ps` means
|
||||
the daemon answers there and can read its database, not just that the web port is up. The socket
|
||||
answers `status` itself instead of queuing it behind the worker's current job, so a long scan or
|
||||
download does not fail the check; it also means a worker stuck on one job would still pass. The
|
||||
container restarts on its own after a reboot.
|
||||
The containers have no Docker healthcheck (#218): Docker runs one with `exec`, which on Tower
|
||||
fails whenever root is logged out, because elogind removes `/run/user/0`, where containerd puts
|
||||
each exec's state. Whether ipx is well is Prometheus's question (`up`, the worker's job and time)
|
||||
and `ipx status` against the control socket, which says the daemon answers and can read its
|
||||
database. The socket answers `status` itself instead of queuing it behind the worker's current
|
||||
job, so a worker stuck on one job still answers it. The containers restart on their own after a
|
||||
reboot.
|
||||
|
||||
Before the container, ipx ran by hand in code-server, with its files in `/config/.config/ipx/` and
|
||||
`/config/.local/share/ipx/`. Those are still there and the container does not read them. If you run
|
||||
@@ -149,13 +151,19 @@ After any edit to it:
|
||||
```sh
|
||||
npx tsc -p .
|
||||
node tests/page-smoke.js
|
||||
node --test tests/page-unit.js
|
||||
```
|
||||
|
||||
The first type-checks `web/src` (loosely: `strict` is off, and `$` returns `any`). The second
|
||||
The first type-checks `web/src` in TypeScript's `strict` mode: every parameter and variable has a
|
||||
type, what the API sends is typed in `web/src/types.ts`, which mirrors the Rust structs and changes
|
||||
with them, and a value that may be null has to be checked before use. `$<T>` returns the element
|
||||
type it is given (`$<HTMLInputElement>('#nurl')`) and assumes the element is there; one that may
|
||||
not be is written `$(...)?.`, and the page check below proves the ones wired at load exist. The second
|
||||
builds the page as shipped and runs its script against a stub DOM, checking every selector it
|
||||
wires at load actually exists. That check exists because a patch once anchored on a deleted
|
||||
function, `String.replace` silently matched nothing, and the whole UI died with a
|
||||
`ReferenceError` while every server-side test passed.
|
||||
`ReferenceError` while every server-side test passed. The third loads the same built script and
|
||||
calls its helpers directly (#234): a pure function added to the page gets its check there.
|
||||
|
||||
Patching that file by guessing an anchor string has failed repeatedly. Read the exact block first
|
||||
(`sed -n 'START,ENDp'`), match it verbatim, and assert the replacement happened rather than hoping.
|
||||
@@ -166,6 +174,7 @@ Patching that file by guessing an anchor string has failed repeatedly. Read the
|
||||
cargo test # ~80 tests: parsing, filters, retention, schedules, SQL, per-user state
|
||||
npx tsc -p . # type-checks web/src
|
||||
node tests/page-smoke.js
|
||||
node --test tests/page-unit.js # the page's own functions, called directly, in a second
|
||||
node tests/native-bridge.js # the page hands playback to a native shell
|
||||
node tests/contrast.js # every theme's palette against WCAG AA
|
||||
npx playwright test # 66 browser tests against a real daemon on fixture feeds
|
||||
@@ -199,8 +208,7 @@ seeking through files, a flood of wrong passwords. Things about them:
|
||||
127.0.0.1, as production trusts Cloudflare Access's; only the sign-in test uses a password.
|
||||
* Each threshold is a budget well above what the request takes now: it is there to catch a query
|
||||
that has started asking once per feed, or writers queueing on a lock, not a slow minute.
|
||||
* `ipx status`, the Docker healthcheck, runs every second throughout, and a run fails if one takes
|
||||
the healthcheck's 5s.
|
||||
* `ipx status` runs every second throughout, and a run fails if one takes 5s.
|
||||
* One at a time: `node tests/load/run.js signin`. All four take about six minutes.
|
||||
* The daemon is on **SQLite** unless `--postgres`, which puts it in `IPX_TEST_DATABASE_URL`, in
|
||||
a schema of its own (`ipx_load`) dropped and made again each run. That URL, in `/src/.envrc`, is
|
||||
|
||||
24
Cargo.lock
generated
24
Cargo.lock
generated
@@ -1820,7 +1820,7 @@ checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
||||
|
||||
[[package]]
|
||||
name = "ipx"
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
dependencies = [
|
||||
"ammonia",
|
||||
"anyhow",
|
||||
@@ -1856,13 +1856,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ipx-directory"
|
||||
version = "1.0.0"
|
||||
version = "1.1.1"
|
||||
dependencies = [
|
||||
"ammonia",
|
||||
"anyhow",
|
||||
"axum",
|
||||
"clap",
|
||||
"futures-util",
|
||||
"ipx-feed",
|
||||
"mimalloc",
|
||||
"opentelemetry",
|
||||
"opentelemetry-otlp",
|
||||
"opentelemetry_sdk",
|
||||
@@ -2102,6 +2104,15 @@ version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "libmimalloc-sys"
|
||||
version = "0.1.49"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libredox"
|
||||
version = "0.1.23"
|
||||
@@ -2541,6 +2552,15 @@ dependencies = [
|
||||
"rapidhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mimalloc"
|
||||
version = "0.1.52"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862"
|
||||
dependencies = [
|
||||
"libmimalloc-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
|
||||
@@ -24,6 +24,7 @@ opentelemetry = { version = "0.33", default-features = false, features = ["trace
|
||||
opentelemetry-otlp = { version = "0.33", default-features = false, features = ["trace", "http-proto", "reqwest-blocking-client"] }
|
||||
opentelemetry_sdk = { version = "0.33", default-features = false, features = ["trace"] }
|
||||
opml = "1.1.6"
|
||||
mimalloc = "0.1.52"
|
||||
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", "stream", "json", "charset", "system-proxy"] }
|
||||
|
||||
@@ -20,6 +20,8 @@ RUN mkdir -p crates/ipx/src crates/feed/src crates/directory/src \
|
||||
&& rm -rf crates/ipx/src crates/feed/src crates/directory/src
|
||||
|
||||
COPY crates ./crates
|
||||
# ipx builds the directory crate in, whose public pages serve these (#215).
|
||||
COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/
|
||||
# cargo skips a rebuild if mtimes look untouched; make sure it does not.
|
||||
RUN touch crates/ipx/src/main.rs crates/feed/src/lib.rs && cargo build --release --locked -p ipx
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@ COPY web ./web
|
||||
RUN node web/build.mjs /dist
|
||||
|
||||
FROM caddy:2
|
||||
# caddy:2's Alpine ships curl, which nothing here runs (no healthcheck since #218): out, so a
|
||||
# curl flaw such as CVE-2026-92392 has nothing to reach in a container facing the internet (#237).
|
||||
RUN apk del --no-cache curl
|
||||
COPY web/Caddyfile /etc/caddy/Caddyfile
|
||||
COPY --from=build /dist /srv
|
||||
EXPOSE 8080
|
||||
|
||||
@@ -10,6 +10,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.1] - 2026-10-15
|
||||
|
||||
### Changed
|
||||
|
||||
- The directory checks five feeds at a time, so a publisher that does not answer no longer holds up the rest of its round (#227).
|
||||
- A feed's server that takes 10 s to connect, or sends nothing for 15 s, is given up on (#230).
|
||||
|
||||
### Security
|
||||
|
||||
- A failed feed check is logged without its address's query or password (#238).
|
||||
|
||||
## [1.1.0] - 2026-10-13
|
||||
|
||||
### Added
|
||||
|
||||
- With `metrics_bind` set, the directory serves Prometheus metrics on a port of its own: memory, open files, and the feeds it has fetched and their bytes. A feed check's trace says how large the feed was (#224).
|
||||
|
||||
### Changed
|
||||
|
||||
- The directory uses mimalloc instead of glibc's allocator, so it gives back memory it has freed instead of holding over a gigabyte while idle (#224).
|
||||
- The example in docs/directory.md has no healthcheck; `ipx-directory health` is still there to run by hand (#218).
|
||||
|
||||
### Security
|
||||
|
||||
- A feed check's trace keeps the feed's address without its query or password (#225).
|
||||
|
||||
## [1.0.0] - 2026-10-12
|
||||
|
||||
### Added
|
||||
@@ -19,5 +45,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- `ipx-directory`, a directory of public podcasts that ipx servers share: each sends the public feeds its people subscribe to, and any server with a token browses them, each feed listed once it has been read. Tokens are in its config file, each read-only, read-write or admin, and revoked one at a time (#204, #205).
|
||||
- Traces: a span a request, joining the trace of the ipx server that called, and a trace a refresher round with a span a feed (#213).
|
||||
|
||||
[unreleased]: https://git.sdf1.net/rays/ipx/compare/directory-v1.0.0...main
|
||||
[unreleased]: https://git.sdf1.net/rays/ipx/compare/directory-v1.1.1...main
|
||||
[1.1.1]: https://git.sdf1.net/rays/ipx/compare/directory-v1.1.0...directory-v1.1.1
|
||||
[1.1.0]: https://git.sdf1.net/rays/ipx/compare/directory-v1.0.0...directory-v1.1.0
|
||||
[1.0.0]: https://git.sdf1.net/rays/ipx/releases/tag/directory-v1.0.0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ipx-directory"
|
||||
version = "1.0.0"
|
||||
version = "1.1.1"
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
@@ -12,10 +12,12 @@ ammonia.workspace = true
|
||||
anyhow.workspace = true
|
||||
axum.workspace = true
|
||||
clap.workspace = true
|
||||
futures-util.workspace = true
|
||||
ipx-feed.workspace = true
|
||||
opentelemetry.workspace = true
|
||||
opentelemetry-otlp.workspace = true
|
||||
opentelemetry_sdk.workspace = true
|
||||
mimalloc.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
reqwest.workspace = true
|
||||
sea-orm.workspace = true
|
||||
|
||||
@@ -14,6 +14,10 @@ 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 (#224), apart from `bind`, which the tunnel
|
||||
/// publishes: `0.0.0.0:9188`. Empty serves none.
|
||||
#[serde(default)]
|
||||
pub metrics_bind: String,
|
||||
#[serde(default)]
|
||||
pub tokens: Vec<TokenCfg>,
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//! people's behalf.
|
||||
|
||||
pub mod config;
|
||||
pub mod metrics;
|
||||
pub mod otel;
|
||||
mod site;
|
||||
pub mod store;
|
||||
@@ -133,6 +134,8 @@ impl Directory {
|
||||
pub fn new(store: Store, tokens: Vec<Token>) -> Result<Shared, reqwest::Error> {
|
||||
// No redirects: ipx_feed::fetch follows them itself, so it sees each hop.
|
||||
let client = reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(10))
|
||||
.read_timeout(ipx_feed::FEED_SILENCE)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.user_agent(concat!("ipx-directory/", env!("CARGO_PKG_VERSION")))
|
||||
.build()?;
|
||||
@@ -174,7 +177,7 @@ impl Directory {
|
||||
Err(e) => Refreshed::Failed(format!("{e:#}")),
|
||||
};
|
||||
if let Refreshed::Failed(e) = &got {
|
||||
tracing::info!(feed = %due.id, error = %e, "feed check failed");
|
||||
tracing::info!(feed = %due.id, error = %ipx_feed::redact_text(e), "feed check failed");
|
||||
}
|
||||
// ponytail: a feed that moved for good is still asked for at its old address, which
|
||||
// redirects; follow the move when a feed's id can change without losing its counts.
|
||||
@@ -192,12 +195,17 @@ pub async fn refresher(dir: Shared) {
|
||||
let round = tracing::info_span!("refresh", feeds = due.len());
|
||||
tracing::Instrument::instrument(
|
||||
async {
|
||||
for d in &due {
|
||||
// A few at a time: in turn, two publishers timing out held a round
|
||||
// for a minute and more (#227).
|
||||
futures_util::StreamExt::for_each_concurrent(futures_util::stream::iter(&due), 5, |d| {
|
||||
let check = tracing::info_span!("feed", feed = %d.id);
|
||||
if let Err(e) = tracing::Instrument::instrument(dir.refresh(d), check).await {
|
||||
tracing::warn!(feed = %d.id, error = %format!("{e:#}"), "could not store a feed check");
|
||||
async {
|
||||
if let Err(e) = tracing::Instrument::instrument(dir.refresh(d), check).await {
|
||||
tracing::warn!(feed = %d.id, error = %format!("{e:#}"), "could not store a feed check");
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
// One line a round, for the dashboard's refresher panel (#210); failures have their own.
|
||||
tracing::info!(checked = due.len(), "feeds checked");
|
||||
},
|
||||
|
||||
@@ -25,8 +25,7 @@ enum Cmd {
|
||||
#[command(subcommand)]
|
||||
cmd: TokenCmd,
|
||||
},
|
||||
/// Check that the directory on this machine answers and can read its database: the
|
||||
/// container's healthcheck.
|
||||
/// Check that the directory on this machine answers and can read its database.
|
||||
Health,
|
||||
}
|
||||
|
||||
@@ -83,7 +82,7 @@ async fn serve(path: &std::path::Path) -> Result<()> {
|
||||
.with(json.then(|| tracing_subscriber::fmt::layer().json().flatten_event(true).with_writer(std::io::stderr).with_filter(filter())))
|
||||
.with(otel.as_ref().map(|p| {
|
||||
use opentelemetry::trace::TracerProvider;
|
||||
tracing_opentelemetry::layer().with_tracer(p.tracer("ipx-directory")).with_filter(tracing_subscriber::EnvFilter::new("ipx_directory=info"))
|
||||
tracing_opentelemetry::layer().with_tracer(p.tracer("ipx-directory")).with_filter(tracing_subscriber::EnvFilter::new("ipx_directory=info,ipx_feed=info"))
|
||||
}))
|
||||
.init();
|
||||
|
||||
@@ -99,6 +98,11 @@ async fn serve(path: &std::path::Path) -> Result<()> {
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(&cfg.bind).await.with_context(|| format!("listening on {}", cfg.bind))?;
|
||||
tracing::info!(version = env!("CARGO_PKG_VERSION"), bind = %cfg.bind, tokens = cfg.tokens.len(), dropped, "directory started");
|
||||
if !cfg.metrics_bind.is_empty() {
|
||||
let metrics = tokio::net::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_directory::metrics::serve(metrics));
|
||||
}
|
||||
tokio::spawn(ipx_directory::refresher(dir.clone()));
|
||||
tokio::spawn(ipx_directory::reloader(dir.clone(), path.to_owned()));
|
||||
axum::serve(listener, ipx_directory::router(dir))
|
||||
|
||||
67
crates/directory/src/metrics.rs
Normal file
67
crates/directory/src/metrics.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
//! Memory, for ipx and the directory both (#224), and the directory's own /metrics.
|
||||
//!
|
||||
//! mimalloc is the allocator of every binary that builds this crate in, ipx included: with
|
||||
//! glibc's, ipx kept the 500-850 MB a night of scans had needed until it restarted, and the
|
||||
//! directory sat at 1.25 GiB doing nothing, each thread's arena holding what it had freed.
|
||||
//! mimalloc gives freed pages back, so resident memory follows what is in use: a spike that
|
||||
//! does not come down again is a leak. Not jemalloc, whose upstream was archived in 2025.
|
||||
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
|
||||
/// The process's resident memory in bytes and its open files, from /proc; None elsewhere.
|
||||
pub fn process() -> (Option<f64>, Option<f64>) {
|
||||
let rss = std::fs::read_to_string("/proc/self/status").ok().and_then(|s| {
|
||||
let kb = s.lines().find_map(|l| l.strip_prefix("VmRSS:"))?.trim().strip_suffix("kB")?.trim().parse::<f64>().ok()?;
|
||||
Some(kb * 1024.0)
|
||||
});
|
||||
let fds = std::fs::read_dir("/proc/self/fd").ok().map(|d| d.count() as f64);
|
||||
(rss, fds)
|
||||
}
|
||||
|
||||
/// The directory's /metrics, in Prometheus's text format: memory, open files, and the feeds it
|
||||
/// has fetched. Nothing from the database, so a scrape costs nothing and answers while it is down.
|
||||
fn render(started: std::time::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("directory_process_resident_bytes", "gauge", "Memory the process holds.", "", v);
|
||||
}
|
||||
if let Some(v) = fds {
|
||||
gauge("directory_process_open_fds", "gauge", "Files and sockets the process has open.", "", v);
|
||||
}
|
||||
gauge("directory_feed_fetches_total", "counter", "Feeds fetched, answered 304 included.", "", ipx_feed::FETCHES.load(Relaxed) as f64);
|
||||
gauge("directory_feed_bytes_total", "counter", "Bytes of feed bodies fetched.", "", ipx_feed::FETCHED_BYTES.load(Relaxed) as f64);
|
||||
gauge("directory_uptime_seconds", "gauge", "Seconds since the directory started.", "", started.elapsed().as_secs() as f64);
|
||||
gauge("directory_build_info", "gauge", "The version running, as a label.", &format!("{{version=\"{}\"}}", env!("CARGO_PKG_VERSION")), 1.0);
|
||||
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.
|
||||
pub async fn serve(listener: tokio::net::TcpListener) {
|
||||
let started = std::time::Instant::now();
|
||||
let app = axum::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 {
|
||||
#[test]
|
||||
fn metrics_say_memory_and_feeds() {
|
||||
let text = super::render(std::time::Instant::now());
|
||||
assert!(text.contains("directory_process_resident_bytes ") && text.contains("directory_feed_bytes_total "), "{text}");
|
||||
}
|
||||
}
|
||||
@@ -61,13 +61,57 @@ pub enum Fetched {
|
||||
/// downloads, which are not, have no such limit.
|
||||
pub const FEED_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
/// The longest a feed's server may send nothing, for the clients that fetch feeds to set: one
|
||||
/// that took the connection and never answered ran the whole 30 s, every scan it was in (#230).
|
||||
/// No feed that answered took over 8 s in a day of traces; one that keeps sending, however
|
||||
/// slowly, still has until FEED_TIMEOUT.
|
||||
pub const FEED_SILENCE: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
|
||||
/// Feeds fetched and the bytes of their bodies, since the process started, for /metrics to set
|
||||
/// beside memory (#224): a body is read whole, so a night of large feeds is a night of large
|
||||
/// allocations.
|
||||
pub static FETCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
pub static FETCHED_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Conditional GET, following redirects itself: `client` must follow none (`feed_client`), so
|
||||
/// each hop is seen. The second value is where the feed now is when every hop said so for good
|
||||
/// (301 or 308): a publisher that moved its feed, which the catalogue should follow rather
|
||||
/// than be redirected on every read. A temporary redirect (302, 307) moves nothing.
|
||||
/// `system-proxy` reads http_proxy/https_proxy.
|
||||
/// `auth` is a username and password, sent only to the feed's own host.
|
||||
#[tracing::instrument(skip_all, fields(url = %feed_url))]
|
||||
/// An address as a trace may keep it: without its query or user and password, where a private
|
||||
/// feed carries its credential (Patreon's `?auth=`), which Tempo kept for anyone reading it (#225).
|
||||
/// shortcut: a token in the path (`/feed/<token>.xml`) stays; strip paths too if a feed does that.
|
||||
pub fn redact(url: &str) -> String {
|
||||
match url::Url::parse(url) {
|
||||
Ok(mut u) => {
|
||||
u.set_query(None);
|
||||
u.set_fragment(None);
|
||||
let _ = u.set_username("");
|
||||
let _ = u.set_password(None);
|
||||
u.to_string()
|
||||
}
|
||||
// Not an address ipx could fetch; keep what comes before anything that could be a query.
|
||||
Err(_) => url.split(['?', '#', '@']).next().unwrap_or_default().to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text with each address in it redacted, for what is logged and sent to every open page: an
|
||||
/// error from reqwest names the whole address it fetched, a private feed's key with it (#238).
|
||||
pub fn redact_text(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(i) = rest.find("http://").into_iter().chain(rest.find("https://")).min() {
|
||||
out.push_str(&rest[..i]);
|
||||
let end = rest[i..].find(|c: char| c.is_whitespace() || "()<>\"'".contains(c)).map_or(rest.len(), |n| i + n);
|
||||
out.push_str(&redact(&rest[i..end]));
|
||||
rest = &rest[end..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(url = %redact(feed_url), http.response.body.size))]
|
||||
pub async fn fetch(
|
||||
client: &reqwest::Client,
|
||||
feed_url: &str,
|
||||
@@ -106,6 +150,7 @@ pub async fn fetch(
|
||||
continue;
|
||||
}
|
||||
let moved = (permanent && url != start).then(|| url.to_string());
|
||||
FETCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if status == StatusCode::NOT_MODIFIED {
|
||||
return Ok((Fetched::NotModified, moved));
|
||||
}
|
||||
@@ -119,6 +164,8 @@ pub async fn fetch(
|
||||
let etag = header(ETAG);
|
||||
let last_modified = header(LAST_MODIFIED);
|
||||
let bytes = resp.bytes().await.context("reading body")?.to_vec();
|
||||
tracing::Span::current().record("http.response.body.size", bytes.len());
|
||||
FETCHED_BYTES.fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
|
||||
return Ok((Fetched::Body { bytes, etag, last_modified }, moved));
|
||||
}
|
||||
// Worded as reqwest worded it, which failure_kind reads as a redirect loop.
|
||||
@@ -364,6 +411,7 @@ fn parse_patreon_shows(json: &[u8]) -> Result<(Option<String>, Vec<(String, Stri
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
match rss::Channel::read_from(bytes) {
|
||||
Ok(ch) => Ok(from_rss(ch, bytes)),
|
||||
@@ -1163,6 +1211,21 @@ const PAID_HOSTS: &[&str] =
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn redact_drops_what_carries_a_credential() {
|
||||
assert_eq!(super::redact("https://www.patreon.com/rss/x?auth=SECRET&show=1"), "https://www.patreon.com/rss/x");
|
||||
assert_eq!(super::redact("https://me:pw@example.com/feed.xml#top"), "https://example.com/feed.xml");
|
||||
assert_eq!(super::redact("https://example.com/feed.xml"), "https://example.com/feed.xml");
|
||||
assert_eq!(super::redact("not a url?token=SECRET"), "not a url");
|
||||
// As reqwest words a failure, and with two addresses and none.
|
||||
assert_eq!(
|
||||
super::redact_text("connecting: error sending request for url (https://www.patreon.com/rss/x?auth=SECRET&show=1): operation timed out"),
|
||||
"connecting: error sending request for url (https://www.patreon.com/rss/x): operation timed out"
|
||||
);
|
||||
assert_eq!(super::redact_text("from http://a/f?k=1 to https://u:p@b/g"), "from http://a/f to https://b/g");
|
||||
assert_eq!(super::redact_text("HTTP 404 Not Found"), "HTTP 404 Not Found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_carrying_someones_access_looks_private() {
|
||||
let private = super::url_looks_private;
|
||||
|
||||
@@ -12,6 +12,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.2.0] - 2026-10-15
|
||||
|
||||
### Added
|
||||
|
||||
- `scan_done` on the event stream says which feed or folder the scan was limited to and whether someone asked for it (`only`, `forced`), so a page can tell the end of its own scan from a scheduled one's (#233).
|
||||
|
||||
### Changed
|
||||
|
||||
- Check every feed looks up the site icons of feeds without artwork a few at a time, alongside the fetches, instead of one after another (#228).
|
||||
- A feed's server that sends nothing for 15 s is given up on, instead of holding a scan for the full 30 s; a feed that keeps sending still has 30 s (#230).
|
||||
- A scan's trace names the feed each fetch is for (#229).
|
||||
|
||||
### Security
|
||||
|
||||
- A failure's words, and the addresses in an event, go to the log and to every open page without their query or password, where a private feed keeps its key: a failed fetch of a Patreon feed logged its `auth` key (#238).
|
||||
|
||||
## [1.1.0] - 2026-10-13
|
||||
|
||||
### Added
|
||||
|
||||
- `/metrics` counts the feeds fetched and the bytes of their bodies (`ipx_feed_fetches_total`, `ipx_feed_bytes_total`), and a feed's trace says how large its body was (#224).
|
||||
|
||||
### Changed
|
||||
|
||||
- ipx uses mimalloc instead of glibc's allocator, which gives freed memory back to the system: with glibc's, the memory a night of scans needed stayed held until a restart (#224).
|
||||
- `docker-compose.yml` has no healthchecks: Docker runs them with exec, which can fail on the host while ipx is well. The library's counts in `/metrics` are kept every 30 s by the daemon itself (#218).
|
||||
|
||||
### Security
|
||||
|
||||
- Traces no longer keep a feed's or file's address with its query or password, where private feeds carry their credentials, such as Patreon's `auth` (#225).
|
||||
|
||||
## [1.0.0] - 2026-10-12
|
||||
|
||||
### Added
|
||||
@@ -801,7 +832,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Torrent enclosures through librqbit, seeding to a ratio or a time, with a stall timeout.
|
||||
- `ipx import` and `ipx export` for OPML, and systemd units in `contrib/`.
|
||||
|
||||
[unreleased]: https://git.sdf1.net/rays/ipx/compare/v1.0.0...main
|
||||
[unreleased]: https://git.sdf1.net/rays/ipx/compare/v1.2.0...main
|
||||
[1.2.0]: https://git.sdf1.net/rays/ipx/compare/v1.1.0...v1.2.0
|
||||
[1.1.0]: https://git.sdf1.net/rays/ipx/compare/v1.0.0...v1.1.0
|
||||
[1.0.0]: https://git.sdf1.net/rays/ipx/compare/v0.12.0...v1.0.0
|
||||
[0.12.0]: https://git.sdf1.net/rays/ipx/compare/v0.11.0...v0.12.0
|
||||
[0.11.0]: https://git.sdf1.net/rays/ipx/compare/v0.10.3...v0.11.0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ipx"
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -36,7 +36,15 @@ pub enum Event {
|
||||
DeadairDone { feed: String, enclosure: i64, saved_s: i64 },
|
||||
Reaped { path: String, bytes: u64 },
|
||||
/// Terminal: a client that asked for work stops reading here.
|
||||
ScanDone { feeds: usize },
|
||||
ScanDone {
|
||||
feeds: usize,
|
||||
/// The feed or folder the scan was limited to, and whether someone asked for it: a page
|
||||
/// stops the button they pressed at the end of their scan, not at a scheduled one's (#233).
|
||||
#[serde(default)]
|
||||
only: Option<String>,
|
||||
#[serde(default)]
|
||||
forced: bool,
|
||||
},
|
||||
ReapDone { files: usize, bytes: u64 },
|
||||
Status { feeds: usize, pending: i64, downloaded: i64 },
|
||||
Error { msg: String },
|
||||
@@ -82,7 +90,7 @@ impl Event {
|
||||
Event::FeedStart { feed } => format!("{feed}: checking"),
|
||||
Event::TorrentDeferred { feed, .. } => format!("{feed}: torrent deferred"),
|
||||
Event::DeadairDone { feed, saved_s, .. } => format!("{feed}: DeadAir found the silences, {saved_s} s shorter"),
|
||||
Event::ScanDone { feeds } => format!("scan complete, {feeds} feed(s)"),
|
||||
Event::ScanDone { feeds, .. } => format!("scan complete, {feeds} feed(s)"),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -136,6 +144,7 @@ impl Emitter {
|
||||
}
|
||||
|
||||
pub fn emit(&self, e: Event) {
|
||||
let e = e.redacted();
|
||||
// Also log it. Scans and downloads travel as events, not tracing calls, so
|
||||
// without this the log view shows only startup and HTTP lines and none of the
|
||||
// work the daemon is actually doing. Progress goes to debug: it fires on every
|
||||
@@ -159,6 +168,29 @@ impl Emitter {
|
||||
}
|
||||
}
|
||||
|
||||
impl Event {
|
||||
/// The event as it may go out: to the log, to every open page whoever's feed it is, to a
|
||||
/// terminal. Addresses lose their query and password, where a private feed keeps its key, and
|
||||
/// so do the ones in an error's words (#238).
|
||||
fn redacted(mut self) -> Self {
|
||||
use crate::feed::{redact, redact_text};
|
||||
match &mut self {
|
||||
Event::DownloadError { url, msg, .. } => {
|
||||
*url = redact(url);
|
||||
*msg = redact_text(msg);
|
||||
}
|
||||
Event::TorrentDeferred { url, .. } => *url = redact(url),
|
||||
Event::FeedMoved { from, to, .. } => {
|
||||
*from = redact(from);
|
||||
*to = redact(to);
|
||||
}
|
||||
Event::FeedError { msg, .. } | Event::Error { msg } => *msg = redact_text(msg),
|
||||
_ => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -198,7 +230,7 @@ fn log_event(e: &Event, wire: bool) {
|
||||
)
|
||||
};
|
||||
}
|
||||
// The healthcheck's answer, every 30s: a reply on the socket rather than work done, so it
|
||||
// `ipx status`'s answer: a reply on the socket rather than work done, so it
|
||||
// stays with the rest of the conversation, and the Scans tab stays about scans.
|
||||
if matches!(e, Event::Status { .. }) {
|
||||
return line!(info, "ipx::io", format!("<- {json}"));
|
||||
@@ -378,6 +410,30 @@ mod tests {
|
||||
assert!(matches!(rx.try_recv(), Ok(Event::FeedSkip { feed, .. }) if feed == "g"), "nothing missed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_goes_out_names_no_private_feeds_key() {
|
||||
let (tx, mut rx) = broadcast::channel(8);
|
||||
let out = Emitter::socket(tx, false);
|
||||
let key = "auth=SECRET";
|
||||
out.emit(Event::FeedError {
|
||||
feed: "f".into(),
|
||||
msg: format!("connecting: error sending request for url (https://x/rss?{key}&show=1): operation timed out"),
|
||||
});
|
||||
out.emit(Event::DownloadError {
|
||||
feed: "f".into(),
|
||||
enclosure: 1,
|
||||
url: format!("https://cdn/ep.mp3?{key}"),
|
||||
msg: format!("connecting: error sending request for url (https://cdn/ep.mp3?{key})"),
|
||||
});
|
||||
out.emit(Event::FeedMoved { feed: "f".into(), from: format!("https://x/rss?{key}"), to: format!("https://y/rss?{key}") });
|
||||
// What every open page is sent, whoever's feed it is (#238).
|
||||
for _ in 0..3 {
|
||||
let sent = serde_json::to_string(&rx.try_recv().unwrap()).unwrap();
|
||||
assert!(!sent.contains("SECRET"), "{sent}");
|
||||
assert!(sent.contains("https://"), "the address is still there, without its key: {sent}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_feed_that_moved_says_so_on_the_wire_and_in_words() {
|
||||
let e = Event::FeedMoved { feed: "x".into(), from: "http://a/f".into(), to: "https://a/f".into() };
|
||||
@@ -434,7 +490,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn only_completion_events_end_a_client_session() {
|
||||
assert!(Event::ScanDone { feeds: 1 }.is_terminal());
|
||||
assert!(Event::ScanDone { feeds: 1, only: None, forced: false }.is_terminal());
|
||||
assert!(Event::ReapDone { files: 0, bytes: 0 }.is_terminal());
|
||||
assert!(!Event::FeedDone {
|
||||
feed: "a".into(),
|
||||
|
||||
@@ -254,8 +254,8 @@ impl Ctx {
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
// The daemon only: `ipx status` runs every half minute as the healthcheck, and a trace
|
||||
// for each would bury the ones worth looking at.
|
||||
// The daemon only: a trace for every `ipx status` a script runs would bury the ones worth
|
||||
// looking at.
|
||||
let otel = match cli.command {
|
||||
Command::Daemon { .. } => ipx_directory::otel::provider("ipx")?,
|
||||
_ => None,
|
||||
@@ -299,7 +299,7 @@ async fn main() -> Result<()> {
|
||||
use opentelemetry::trace::TracerProvider;
|
||||
tracing_opentelemetry::layer()
|
||||
.with_tracer(p.tracer("ipx"))
|
||||
.with_filter(tracing_subscriber::EnvFilter::new("ipx=info"))
|
||||
.with_filter(tracing_subscriber::EnvFilter::new("ipx=info,ipx_feed=info"))
|
||||
}))
|
||||
.init();
|
||||
}
|
||||
@@ -355,6 +355,7 @@ async fn main() -> Result<()> {
|
||||
feed_client: reqwest::Client::builder()
|
||||
.user_agent(concat!("ipx/", env!("CARGO_PKG_VERSION")))
|
||||
.connect_timeout(std::time::Duration::from_secs(10))
|
||||
.read_timeout(feed::FEED_SILENCE)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()?,
|
||||
out: if is_daemon { Emitter::socket(events.clone(), false) } else { Emitter::terminal() },
|
||||
@@ -568,7 +569,7 @@ pub(crate) async fn status(ctx: &Ctx) -> Event {
|
||||
match ctx.db.counts().await {
|
||||
Ok((pending, downloaded)) => {
|
||||
let feeds = subscriptions(ctx).await.map(|s| s.len()).unwrap_or(0);
|
||||
// Kept for /metrics, which asks the database nothing (#195): the healthcheck asks this every 30 s.
|
||||
// Kept for /metrics, which asks the database nothing (#195); the daemon counts every 30 s.
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let st = &metrics::STATS;
|
||||
st.feeds.store(feeds as i64, Relaxed);
|
||||
@@ -663,6 +664,21 @@ async fn daemon(
|
||||
// must not wait behind it.
|
||||
tokio::spawn(deadair::run(ctx.clone(), rx_stop.clone()));
|
||||
tokio::spawn(directory::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).
|
||||
{
|
||||
let (ctx, mut stop) = (ctx.clone(), rx_stop.clone());
|
||||
tokio::spawn(async move {
|
||||
let mut every = tokio::time::interval(std::time::Duration::from_secs(30));
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = every.tick() => { status(&ctx).await; }
|
||||
_ = stop.changed() => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Runs one job, abandoning it if a signal arrives. Returns false to end the loop.
|
||||
async fn until_stopped(
|
||||
@@ -1245,18 +1261,33 @@ async fn fetch(ctx: &Arc<Ctx>, only: Option<&str>, force: bool, scope: &[String]
|
||||
const AHEAD: usize = 6;
|
||||
let mut bodies = futures_util::StreamExt::buffered(
|
||||
futures_util::stream::iter(due.iter().map(|(sub, state)| {
|
||||
let (client, feed_cfg) = (ctx.feed_client.clone(), sub.cfg.clone());
|
||||
let (client, web, feed_cfg) = (ctx.feed_client.clone(), ctx.client.clone(), sub.cfg.clone());
|
||||
let (etag, modified) = (state.etag.clone(), state.last_modified.clone());
|
||||
let early = !feed::is_patreon_creator(&feed_cfg.url);
|
||||
// Named for its feed: the fetch's own span has only the address, without its query
|
||||
// since #225, which for every YouTube channel is the same (#229).
|
||||
let span = tracing::info_span!("fetch_ahead", feed = %sub.id);
|
||||
tokio::spawn(tracing::Instrument::instrument(
|
||||
async move {
|
||||
if !early {
|
||||
return None;
|
||||
}
|
||||
let _fetching = metrics::busy(&metrics::STATS.feeds_fetching);
|
||||
Some(feed::fetch(&client, &feed_cfg.url, feed_cfg.auth(), etag.as_deref(), modified.as_deref()).await)
|
||||
let got = feed::fetch(&client, &feed_cfg.url, feed_cfg.auth(), etag.as_deref(), modified.as_deref()).await;
|
||||
// A forced scan looks for the site's icon of each feed naming no artwork: here,
|
||||
// a few feeds at a time, not each in its turn, 22 s of a 62 s scan (#228).
|
||||
let icon = match &got {
|
||||
Ok((feed::Fetched::Body { bytes, .. }, _)) if force => match feed::parse(bytes) {
|
||||
Ok(feed::ParsedFeed { image: None, site: Some(site), .. }) => {
|
||||
Some(feed::site_icon(&web, &site).await.unwrap_or_default())
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
Some((got, icon))
|
||||
},
|
||||
tracing::Span::current(),
|
||||
span,
|
||||
))
|
||||
})),
|
||||
AHEAD,
|
||||
@@ -1330,7 +1361,7 @@ async fn fetch(ctx: &Arc<Ctx>, only: Option<&str>, force: bool, scope: &[String]
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.out.emit(Event::ScanDone { feeds: scanned });
|
||||
ctx.out.emit(Event::ScanDone { feeds: scanned, only: only.map(str::to_owned), forced: force });
|
||||
// What people subscribe to may have changed, and new feeds have titles now: share it.
|
||||
ctx.directory_wake.notify_one();
|
||||
Ok(())
|
||||
@@ -1613,9 +1644,14 @@ async fn scan_one(
|
||||
feed_cfg: &config::Feed,
|
||||
state: &db::HttpState,
|
||||
force: bool,
|
||||
// The body the scan already fetched for it, if it did (#104), and where it moved, if it did.
|
||||
prefetched: Option<Result<(feed::Fetched, Option<String>)>>,
|
||||
// The body the scan already fetched for it, if it did (#104), and where it moved, if it did;
|
||||
// with the site's icon when a forced scan looked it up meanwhile, "" for none (#228).
|
||||
prefetched: Option<(Result<(feed::Fetched, Option<String>)>, Option<String>)>,
|
||||
) -> Result<Outcome> {
|
||||
let (prefetched, icon) = match prefetched {
|
||||
Some((got, icon)) => (Some(got), icon),
|
||||
None => (None, None),
|
||||
};
|
||||
// The queue follows the feed's settings each time it is due, changed or not, so files a
|
||||
// limit or auto-download no longer reaches stop counting as waiting (#113).
|
||||
let policy = policy_for(ctx, id, feed_cfg).await?;
|
||||
@@ -1717,13 +1753,16 @@ async fn scan_one(
|
||||
&& stored.image.as_deref() != Some(art.as_str())
|
||||
&& !feed::is_image(&ctx.client, art).await
|
||||
{
|
||||
tracing::info!(feed = id, art = %art, "the feed's artwork is not an image; trying its site's icon");
|
||||
tracing::info!(feed = id, art = %feed::redact(art), "the feed's artwork is not an image; trying its site's icon");
|
||||
parsed.image = None;
|
||||
}
|
||||
if parsed.image.is_none() {
|
||||
parsed.image = Some(match (&stored.image, &parsed.site) {
|
||||
(Some(known), _) if !force => known.clone(),
|
||||
(_, Some(site)) => feed::site_icon(&ctx.client, site).await.unwrap_or_default(),
|
||||
(_, Some(site)) => match &icon {
|
||||
Some(found) => found.clone(),
|
||||
None => feed::site_icon(&ctx.client, site).await.unwrap_or_default(),
|
||||
},
|
||||
(_, None) => String::new(),
|
||||
});
|
||||
}
|
||||
@@ -2124,7 +2163,7 @@ fn merge_policy(subs: &[db::Sub], feed_cfg: &config::Feed, global: usize) -> Pol
|
||||
|
||||
/// Downloads one file and records it. None when it turned out to be a torrent, handed off to run
|
||||
/// on its own, which records it when it finishes.
|
||||
#[tracing::instrument(name = "download", skip_all, fields(feed = feed_id, enclosure = enclosure, url = url))]
|
||||
#[tracing::instrument(name = "download", skip_all, fields(feed = feed_id, enclosure = enclosure, url = %feed::redact(url)))]
|
||||
async fn fetch_one(
|
||||
ctx: &Arc<Ctx>,
|
||||
feed_id: &str,
|
||||
@@ -2282,7 +2321,7 @@ async fn download_one(ctx: &Arc<Ctx>, id: i64) -> Result<()> {
|
||||
}
|
||||
}
|
||||
// Terminal, so a UI waiting on this request stops here.
|
||||
ctx.out.emit(Event::ScanDone { feeds: 1 });
|
||||
ctx.out.emit(Event::ScanDone { feeds: 1, only: None, forced: false });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2644,6 +2683,58 @@ mod tests {
|
||||
assert!(deadair::plan_for(&ctx, u, "f", 7).await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn two_people_play_one_file_each_in_their_own_version_and_place() {
|
||||
let ctx = test_ctx(config::Config::default()).await;
|
||||
let db = &ctx.db;
|
||||
for sql in [
|
||||
"INSERT INTO entries (feed_id, guid, first_seen, duration) VALUES ('f', 'g', 1, 600)",
|
||||
"INSERT INTO enclosures (id, feed_id, guid, url, path, state, downloaded_at)
|
||||
VALUES (7, 'f', 'g', 'http://x/a.mp3', '/x/a.mp3', 'done', 100)",
|
||||
] {
|
||||
db.sql(sql).await.unwrap();
|
||||
}
|
||||
db.store_plans(7, r#"{"300": {"cuts": [[60000,120000],[200000,260000]], "pieces": []},
|
||||
"500": {"cuts": [[60000,100000]], "pieces": []}}"#).await.unwrap();
|
||||
// One file on disk, three listeners at once: DeadAir at the usual pause, at a longer
|
||||
// one, and the original.
|
||||
let (usual, long, plain) = (
|
||||
db.create_user("usual", None, false).await.unwrap(),
|
||||
db.create_user("long", None, false).await.unwrap(),
|
||||
db.create_user("plain", None, false).await.unwrap(),
|
||||
);
|
||||
for u in [usual, long, plain] {
|
||||
db.subscribe(u, "f").await.unwrap();
|
||||
}
|
||||
for u in [usual, long] {
|
||||
db.set_deadair(u, "f", Some(true)).await.unwrap();
|
||||
}
|
||||
db.set_deadair_pause(long, "f", 500).await.unwrap();
|
||||
// Each is handed their own playlist, as /media/7/deadair.m3u8 does.
|
||||
let playing = deadair::Playing::default();
|
||||
for u in [usual, long] {
|
||||
let plan = deadair::plan_for(&ctx, u, "f", 7).await.unwrap().unwrap();
|
||||
playing.lock().unwrap().insert((u, "f".into(), "g".into()), Arc::new(plan));
|
||||
}
|
||||
assert!(deadair::plan_for(&ctx, plain, "f", 7).await.unwrap().is_none());
|
||||
// All three save 3:20 of what they hear, as the position route does: each is read in
|
||||
// that person's own clock and kept as a place in the original, theirs alone.
|
||||
let mut kept = vec![];
|
||||
for u in [usual, long, plain] {
|
||||
let (secs, len) = deadair::on_save(&ctx, &playing, u, "f", "g", 200, None).await.unwrap();
|
||||
db.set_position(u, "f", "g", secs, len).await.unwrap();
|
||||
kept.push(secs);
|
||||
}
|
||||
assert_eq!(kept, [320, 240, 200], "two minutes cut before 3:20, forty seconds, none");
|
||||
// Each comes back to 3:20 of their own version, whatever the others saved.
|
||||
let order = db::order_sql("published", "desc");
|
||||
for (u, len) in [(usual, 480), (long, 560), (plain, 600)] {
|
||||
let mut rows = db.entries_in(u, Some("f"), db::Filter::All, None, 0, 10, &order).await.unwrap();
|
||||
deadair::for_reader(&ctx, u, &mut rows).await.unwrap();
|
||||
assert_eq!((rows[0].position, rows[0].duration), (200, Some(len)), "user {u}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn two_changes_to_the_catalogue_at_once_both_keep() {
|
||||
let ctx = Arc::new(test_ctx(config::Config::default()).await);
|
||||
@@ -2743,6 +2834,18 @@ mod tests {
|
||||
assert_eq!(text().await, ["As it should read."]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_forced_scan_takes_the_icon_looked_up_ahead() {
|
||||
let ctx = Arc::new(test_ctx(config::Config::default()).await);
|
||||
// No artwork, and a site nothing answers at: only the icon found ahead can be stored (#228).
|
||||
let body = b"<?xml version=\"1.0\"?><rss version=\"2.0\"><channel><title>T</title><link>http://127.0.0.1:9/</link><item><title>One</title><guid>g1</guid></item></channel></rss>".to_vec();
|
||||
let got = feed::Fetched::Body { bytes: body, etag: None, last_modified: None };
|
||||
let icon = "https://example.com/favicon.ico".to_string();
|
||||
let cfg = config::Feed { url: "http://127.0.0.1:9/feed".into(), ..feed() };
|
||||
scan_one(&ctx, "iconic", &cfg, &db::HttpState::default(), true, Some((Ok((got, None)), Some(icon.clone())))).await.unwrap();
|
||||
assert_eq!(ctx.db.feed_summary("iconic").await.unwrap().image, Some(icon));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nothing_from_a_feed_that_never_posted_is_an_error_and_from_one_that_has_is_not() {
|
||||
let base = empty_or_feed_server().await;
|
||||
|
||||
@@ -36,7 +36,7 @@ pub struct Stats {
|
||||
/// Artwork served from disk, and fetched from the publisher because it was not there.
|
||||
pub art_hits: AtomicU64,
|
||||
pub art_misses: AtomicU64,
|
||||
/// The library as the healthcheck last counted it, every 30 s; -1 until it has.
|
||||
/// The library as the daemon last counted it, every 30 s; -1 until it has.
|
||||
pub feeds: AtomicI64,
|
||||
pub pending: AtomicI64,
|
||||
pub downloaded: AtomicI64,
|
||||
@@ -169,13 +169,15 @@ pub fn render(s: &Sources) -> String {
|
||||
gauge(&mut out, "ipx_runtime_workers", "The async runtime's worker threads.", &[("", rt.num_workers() as f64)]);
|
||||
gauge(&mut out, "ipx_runtime_tasks", "Tasks alive in the async runtime.", &[("", rt.num_alive_tasks() as f64)]);
|
||||
gauge(&mut out, "ipx_runtime_queue", "Tasks waiting in the runtime's global queue.", &[("", rt.global_queue_depth() as f64)]);
|
||||
let (rss, fds) = process();
|
||||
let (rss, fds) = ipx_directory::metrics::process();
|
||||
if let Some(v) = rss {
|
||||
gauge(&mut out, "ipx_process_resident_bytes", "Memory the process holds.", &[("", v)]);
|
||||
}
|
||||
if let Some(v) = fds {
|
||||
gauge(&mut out, "ipx_process_open_fds", "Files and sockets the process has open.", &[("", v)]);
|
||||
}
|
||||
counter(&mut out, "ipx_feed_fetches_total", "Feeds fetched, answered 304 included.", &[("", ipx_feed::FETCHES.load(Relaxed) as f64)]);
|
||||
counter(&mut out, "ipx_feed_bytes_total", "Bytes of feed bodies fetched.", &[("", ipx_feed::FETCHED_BYTES.load(Relaxed) as f64)]);
|
||||
gauge(&mut out, "ipx_uptime_seconds", "Seconds since the daemon started.", &[("", s.started.elapsed().as_secs() as f64)]);
|
||||
let version = format!("version=\"{}\"", env!("CARGO_PKG_VERSION"));
|
||||
gauge(&mut out, "ipx_build_info", "The version running, as a label.", &[(&version, 1.0)]);
|
||||
@@ -218,9 +220,9 @@ fn work(out: &mut String, st: &Stats, event_queue: usize, retries: usize, art_li
|
||||
counter(out, "ipx_art_requests_total", "Artwork asked for: served from disk, or fetched from the publisher.",
|
||||
&[("result=\"hit\"", st.art_hits.load(Relaxed) as f64), ("result=\"miss\"", st.art_misses.load(Relaxed) as f64)]);
|
||||
for (name, help, v) in [
|
||||
("ipx_feeds", "Feeds in the catalogue, as the healthcheck last counted.", &st.feeds),
|
||||
("ipx_downloads_pending", "Files a scan will download on its own, as the healthcheck last counted.", &st.pending),
|
||||
("ipx_files_downloaded", "Files on disk, as the healthcheck last counted.", &st.downloaded),
|
||||
("ipx_feeds", "Feeds in the catalogue, as last counted.", &st.feeds),
|
||||
("ipx_downloads_pending", "Files a scan will download on its own, as last counted.", &st.pending),
|
||||
("ipx_files_downloaded", "Files on disk, as last counted.", &st.downloaded),
|
||||
] {
|
||||
let v = v.load(Relaxed);
|
||||
if v >= 0 {
|
||||
@@ -248,16 +250,6 @@ fn write(out: &mut String, kind: &str, name: &str, help: &str, samples: &[(&str,
|
||||
}
|
||||
}
|
||||
|
||||
/// The process's resident memory in bytes and its open files, from /proc; None elsewhere.
|
||||
pub fn process() -> (Option<f64>, Option<f64>) {
|
||||
let rss = std::fs::read_to_string("/proc/self/status").ok().and_then(|s| {
|
||||
let kb = s.lines().find_map(|l| l.strip_prefix("VmRSS:"))?.trim().strip_suffix("kB")?.trim().parse::<f64>().ok()?;
|
||||
Some(kb * 1024.0)
|
||||
});
|
||||
let fds = std::fs::read_dir("/proc/self/fd").ok().map(|d| d.count() as f64);
|
||||
(rss, fds)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -293,13 +285,13 @@ mod tests {
|
||||
assert!(out.contains("ipx_worker_busy 0\n") && !out.contains("ipx_worker_job_seconds"), "{out}");
|
||||
assert!(out.contains("ipx_jobs_total{kind=\"scan\"} 1\n") && out.contains("# TYPE ipx_jobs_total counter"), "{out}");
|
||||
assert!(out.contains("ipx_event_queue 3\n") && out.contains("ipx_feed_retries 1\n"));
|
||||
// The library's counts are left out until the healthcheck has counted it.
|
||||
// The library's counts are left out until the daemon has counted it.
|
||||
assert!(!out.contains("ipx_feeds "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_process_reads_its_memory_and_files_on_linux() {
|
||||
let (rss, fds) = process();
|
||||
let (rss, fds) = ipx_directory::metrics::process();
|
||||
assert!(rss.unwrap() > 0.0 && fds.unwrap() > 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1907,7 +1907,7 @@ async fn art(State(state): State<WebState>, Query(q): Query<ArtQuery>) -> Respon
|
||||
Err(e) => {
|
||||
let why = format!("{e:#}");
|
||||
// The access line says only that it failed, not which image or why (#169).
|
||||
tracing::warn!(url = %q.u, error = %why, "could not fetch artwork");
|
||||
tracing::warn!(url = %crate::feed::redact(&q.u), error = %crate::feed::redact_text(&why), "could not fetch artwork");
|
||||
crate::art::fail(&q.u, &why);
|
||||
(StatusCode::BAD_GATEWAY, why).into_response()
|
||||
}
|
||||
|
||||
@@ -22,12 +22,6 @@ services:
|
||||
- ./config:/config # config.toml, written on first start
|
||||
- ./data:/data # state.db
|
||||
- ./downloads:/downloads
|
||||
healthcheck:
|
||||
test: ["CMD", "ipx", "status"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
ipx-web:
|
||||
image: ipx-web
|
||||
@@ -47,8 +41,3 @@ services:
|
||||
- "8099:8080" # the web UI
|
||||
depends_on:
|
||||
- ipx
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1:8080/favicon.png"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
@@ -78,6 +78,9 @@ with one name) leaves the tokens as they were, and the log says why.
|
||||
|
||||
```toml
|
||||
bind = "0.0.0.0:8100"
|
||||
# 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:9188"
|
||||
# The environment variable holding the database URL: postgres://... or sqlite://...
|
||||
database_url_env = "DIRECTORY_DATABASE_URL"
|
||||
|
||||
@@ -110,8 +113,6 @@ services:
|
||||
- "8100:8100"
|
||||
volumes:
|
||||
- ./directory:/config:ro # directory.toml
|
||||
healthcheck:
|
||||
test: ["CMD", "ipx-directory", "health"]
|
||||
```
|
||||
|
||||
## What it will not hold
|
||||
|
||||
@@ -51,8 +51,12 @@ pid = 0
|
||||
def panel(kind, title, w, h, x, targets, **extra):
|
||||
global pid
|
||||
pid += 1
|
||||
sources = {t.get("datasource", LOKI)["uid"] for t in targets}
|
||||
# A panel with queries on more than one data source must be Mixed, or Grafana runs them all on
|
||||
# the panel's and Downloads, Loki's and Prometheus's, failed (#226).
|
||||
ds = {"type": "datasource", "uid": "-- Mixed --"} if len(sources) > 1 else targets[0].get("datasource", LOKI)
|
||||
p = {"id": pid, "type": kind, "title": title, "gridPos": {"x": x, "y": y, "w": w, "h": h},
|
||||
"datasource": targets[0].get("datasource", LOKI), "targets": targets}
|
||||
"datasource": ds, "targets": targets}
|
||||
p.update(extra)
|
||||
panels.append(p)
|
||||
return p
|
||||
@@ -295,6 +299,13 @@ table("Failing feeds in the directory", [loki(f'sum by (feed, error) (count_over
|
||||
table("Snapshots by server", [loki(f'sum by (instance) (count_over_time({DIR} | message="snapshot" [$__range]))', instant=True)],
|
||||
12, rename={"instance": "Token", "Value": "Snapshots"}, sort=[{"displayName": "Snapshots", "desc": True}])
|
||||
y += 8
|
||||
# The directory's own /metrics, on a port apart from the tunnel's (#224).
|
||||
ts("Directory memory", [prom('directory_process_resident_bytes{job="ipx-directory"}', legend="resident")], 0, unit="bytes",
|
||||
desc="mimalloc gives back what is freed, so this follows what is in use: a rise that never comes down is a leak.")
|
||||
ts("Feed bytes fetched", [prom('rate(ipx_feed_bytes_total{job="ipx"}[$__rate_interval])', legend="ipx"),
|
||||
prom('rate(directory_feed_bytes_total{job="ipx-directory"}[$__rate_interval])', ref="B", legend="directory")],
|
||||
12, unit="Bps", desc="Feeds are read whole, so this is what scans and checks allocate; set it beside memory.")
|
||||
y += 8
|
||||
|
||||
# ---- Traces: all three send them to Tempo (#213)
|
||||
row("Traces")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ipx-web",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.2",
|
||||
"private": true,
|
||||
"description": "Builds the ipx web pages from web/src (web/build.mjs, run by build.rs) and tests them. The Rust tests cover the server.",
|
||||
"scripts": {
|
||||
|
||||
655
site/api.mjs
Normal file
655
site/api.mjs
Normal file
@@ -0,0 +1,655 @@
|
||||
// The API reference's content: each service's endpoints, grouped, and the types they take and
|
||||
// give, as the handlers in crates/ipx/src/web.rs and crates/directory/src/lib.rs have them. A
|
||||
// change to a route or a field there wants its line here; gen.mjs turns this into pages.
|
||||
// Types are written as Rust writes them, the way docs.rs shows a signature; a name in TYPES links
|
||||
// to its page.
|
||||
|
||||
const U = 'http://<your server>:8099';
|
||||
const D = 'https://directory.ipxreader.app';
|
||||
const ipxCurl = (m, p, body) =>
|
||||
`curl${m === 'GET' ? '' : ` -X ${m}`} -H "Authorization: Bearer ipx_…"${body ? ` \\\n -H "Content-Type: application/json" -d '${body}'` : ''} \\\n "${U}${p}"`;
|
||||
const dirCurl = (m, p, body) =>
|
||||
`curl${m === 'GET' ? '' : ` -X ${m}`} -H "Authorization: Bearer <token>"${body ? ` \\\n -H "Content-Type: application/json" -d '${body}'` : ''} \\\n "${D}${p}"`;
|
||||
|
||||
const NOT_SUBSCRIBED = ['404 Not Found', 'You do not subscribe to the feed, or it does not exist. A feed someone else reads is not yours to see.'];
|
||||
const NOT_ADMIN = ['403 Forbidden', 'You are not an admin.'];
|
||||
const NO_DIRECTORY = ['503 Service Unavailable', 'No directory is set up on this server.'];
|
||||
|
||||
export const ipx = {
|
||||
name: 'ipx',
|
||||
root: '/docs/api/ipx',
|
||||
changelog: 'crates/ipx/CHANGELOG.md',
|
||||
intro: `<p>The HTTP API of an iPX server: everything the page does, a script can do. Every request
|
||||
and answer is JSON unless an item says otherwise. The page is served by ipx-web, which passes
|
||||
<code>/api</code> and <code>/media</code> on to ipx at the same address, so a script talks to
|
||||
the address people open in a browser.</p>
|
||||
<h2 id="auth">Signing in</h2>
|
||||
<p>Send an API token, made in Settings under API tokens or with <a href="${'/docs/api/ipx/auth/post-tokens'}"><code>POST /api/tokens</code></a>:</p>
|
||||
<pre><code>Authorization: Bearer ipx_…</code></pre>
|
||||
<p>A token acts as the person who made it, and is an admin only if they are. A browser signs in
|
||||
with <a href="/docs/api/ipx/auth/post-login"><code>POST /api/login</code></a> instead and is
|
||||
given a cookie. Behind Cloudflare Access, Access stops a request with no Access sign-in before
|
||||
iPX sees it: send an Access service token's <code>CF-Access-Client-Id</code> and
|
||||
<code>CF-Access-Client-Secret</code> beside the API token.</p>
|
||||
<h2 id="errors">Errors</h2>
|
||||
<p>A request that fails answers with its status and a sentence saying why, as plain text:
|
||||
<code>401</code> not signed in, <code>403</code> an admin's to do, <code>404</code> not there or
|
||||
not yours, <code>400</code> a request that cannot be done as asked, <code>409</code> a conflict
|
||||
the answer explains.</p>
|
||||
<h2 id="ids">Ids</h2>
|
||||
<p>A feed's id is a short name made from its title, such as <code>99-invisible</code>, and
|
||||
appears in the page's address when the feed is open. An episode is its feed's id and its
|
||||
<code>guid</code>, the guid URL-encoded in a path. A file (an enclosure) has a number. Times are
|
||||
Unix seconds.</p>`,
|
||||
groups: [
|
||||
{
|
||||
id: 'auth', name: 'auth', title: 'Signing in and tokens',
|
||||
summary: 'Who you are, signing in and out, and API tokens.',
|
||||
items: [
|
||||
{
|
||||
method: 'POST', path: '/api/login', slug: 'post-login', access: 'none',
|
||||
summary: 'Sign in with a name and password, for a session cookie.',
|
||||
doc: '<p>Answers who signed in and sets the session cookie, which lasts <code>session_days</code> from the last request. A script is better off with an API token, which needs no password kept.</p>',
|
||||
body: 'Credentials', returns: 'Me',
|
||||
errors: [['401 Unauthorized', 'The name or password is wrong.']],
|
||||
example: `curl -c cookies -H "Content-Type: application/json" \\\n -d '{"name":"sam","password":"…"}' "${U}/api/login"`,
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/logout', slug: 'post-logout',
|
||||
summary: 'Sign out: end the session and clear its cookies.',
|
||||
returns: '204 No Content',
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/me', slug: 'get-me',
|
||||
summary: 'Who you are, your words that hide items, and the server’s version.',
|
||||
returns: 'Me',
|
||||
example: ipxCurl('GET', '/api/me'),
|
||||
},
|
||||
{
|
||||
method: 'PATCH', path: '/api/me', slug: 'patch-me',
|
||||
summary: 'Change the words that hide an item in every feed you read.',
|
||||
body: 'MePatch', returns: '204 No Content',
|
||||
errors: [['400 Bad Request', 'More than 500 words, or one over 200 characters.']],
|
||||
example: ipxCurl('PATCH', '/api/me', '{"blocked":["sponsor","ad read"]}'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/tokens', slug: 'get-tokens',
|
||||
summary: 'Your API tokens: names and when each was made and last used, never the token.',
|
||||
returns: 'Vec<Token>',
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/tokens', slug: 'post-tokens',
|
||||
summary: 'Make an API token that acts as you.',
|
||||
doc: '<p>The answer is the only time the token is shown: only its SHA-256 is kept.</p>',
|
||||
body: 'NewToken', returns: 'NewTokenMade',
|
||||
errors: [['400 Bad Request', 'No name.']],
|
||||
example: ipxCurl('POST', '/api/tokens', '{"name":"my script"}'),
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/api/tokens/{id}', slug: 'delete-token',
|
||||
summary: 'Revoke one of your API tokens.',
|
||||
pathParams: [['id', 'i64', 'The token’s id, from <code>GET /api/tokens</code>.']],
|
||||
returns: '204 No Content',
|
||||
errors: [['404 Not Found', 'No token of yours has that id.']],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'feeds', name: 'feeds', title: 'Feeds',
|
||||
summary: 'Your subscriptions: list, subscribe, change, unsubscribe, check, OPML.',
|
||||
items: [
|
||||
{
|
||||
method: 'GET', path: '/api/feeds', slug: 'get-feeds',
|
||||
summary: 'Your subscriptions, each with its counts and your settings for it.',
|
||||
returns: 'Vec<FeedRow>',
|
||||
example: ipxCurl('GET', '/api/feeds'),
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/feeds', slug: 'post-feeds',
|
||||
summary: 'Subscribe to a feed, by its address or a site that links one.',
|
||||
doc: '<p>A feed someone else on the server already has costs nothing to add: it is fetched once and each file is kept once. An OPML address subscribes to the list, kept in step as a folder.</p>',
|
||||
body: 'NewFeed', returns: 'Added',
|
||||
errors: [['400 Bad Request', 'The address is not a feed and links none; the answer says what was found.']],
|
||||
example: ipxCurl('POST', '/api/feeds', '{"url":"https://feeds.99percentinvisible.org/99percentinvisible"}'),
|
||||
},
|
||||
{
|
||||
method: 'PATCH', path: '/api/feeds/{id}', slug: 'patch-feed',
|
||||
summary: 'Change your settings for a feed, or (an admin) the feed’s own.',
|
||||
doc: '<p>Send only the fields to change. Which episodes you want, whether to download them, how many at a time, DeadAir and pinning are yours, and change for nobody else. The feed’s address, folder, schedule and category, and marking it shareable again, are the same for everyone and an admin’s to change.</p>',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']],
|
||||
body: 'FeedPatch', returns: '204 No Content',
|
||||
errors: [['400 Bad Request', 'A value out of range, such as a DeadAir pause that is not 200, 300, 400 or 500.'], ['403 Forbidden', 'A field only an admin may change.'], NOT_SUBSCRIBED],
|
||||
example: ipxCurl('PATCH', '/api/feeds/99-invisible', '{"keywords":["mini-stories"],"pinned":true}'),
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/api/feeds/{id}', slug: 'delete-feed',
|
||||
summary: 'Unsubscribe. The files stay for anyone else who reads the feed.',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']],
|
||||
returns: '204 No Content', errors: [NOT_SUBSCRIBED],
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/feeds/{id}/read-all', slug: 'post-read-all',
|
||||
summary: 'Mark every episode of a feed read, and of every feed in it for an OPML list.',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']],
|
||||
returns: 'Marked',
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/feeds/{id}/download-latest', slug: 'post-download-latest',
|
||||
summary: 'Download a feed’s newest episodes that are not downloaded yet.',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']],
|
||||
body: 'HowMany', returns: 'Queued', errors: [NOT_SUBSCRIBED],
|
||||
example: ipxCurl('POST', '/api/feeds/99-invisible/download-latest', '{"count":3}'),
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/fetch', slug: 'post-fetch',
|
||||
summary: 'Check one feed, or all of yours, for new episodes now.',
|
||||
doc: '<p>The check runs in the background; <a href="/docs/api/ipx/server/get-events"><code>GET /api/events</code></a> shows it as it goes.</p>',
|
||||
body: 'FetchBody', returns: '202 Accepted',
|
||||
example: ipxCurl('POST', '/api/fetch', '{"feed":"99-invisible","force":true}'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/opml', slug: 'get-opml',
|
||||
summary: 'Your subscriptions as an OPML file, for another podcast app.',
|
||||
returns: 'OPML (text/x-opml)',
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/opml', slug: 'post-opml',
|
||||
summary: 'Subscribe to every feed in an OPML file.',
|
||||
body: 'OpmlBody', returns: 'Imported',
|
||||
errors: [['400 Bad Request', 'Not OPML.']],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'entries', name: 'entries', title: 'Episodes',
|
||||
summary: 'Episodes and posts: list, search, mark read or kept, save where you are.',
|
||||
items: [
|
||||
{
|
||||
method: 'GET', path: '/api/feeds/{id}/entries', slug: 'get-feed-entries',
|
||||
summary: 'A page of one feed’s episodes, newest first unless sorted.',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']],
|
||||
query: 'Page', returns: 'EntryPage', errors: [NOT_SUBSCRIBED],
|
||||
example: ipxCurl('GET', '/api/feeds/99-invisible/entries?filter=unread&limit=10'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/entries', slug: 'get-entries',
|
||||
summary: 'The same, across every feed you subscribe to.',
|
||||
query: 'Page', returns: 'EntryPage',
|
||||
example: ipxCurl('GET', '/api/entries?q=bridges&sort=published&dir=desc'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/entries/{feed}/{guid}', slug: 'get-entry',
|
||||
summary: 'One episode.',
|
||||
pathParams: [['feed', 'String', 'The feed’s id.'], ['guid', 'String', 'The episode’s guid, URL-encoded.']],
|
||||
returns: 'EntryRow', errors: [NOT_SUBSCRIBED],
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/entries/{feed}/{guid}/flags', slug: 'post-flags',
|
||||
summary: 'Mark an episode read or unread, kept or not.',
|
||||
doc: '<p>Answers with the feed’s row, its counts changed, so a list can redraw one line.</p>',
|
||||
pathParams: [['feed', 'String', 'The feed’s id.'], ['guid', 'String', 'The episode’s guid, URL-encoded.']],
|
||||
body: 'Flags', returns: 'Option<FeedRow>', errors: [NOT_SUBSCRIBED],
|
||||
example: ipxCurl('POST', '/api/entries/99-invisible/{guid}/flags', '{"read":true}'),
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/entries/{feed}/{guid}/position', slug: 'post-position',
|
||||
summary: 'Save where you are in an episode, for every device you listen on.',
|
||||
pathParams: [['feed', 'String', 'The feed’s id.'], ['guid', 'String', 'The episode’s guid, URL-encoded.']],
|
||||
body: 'Position', returns: '204 No Content', errors: [NOT_SUBSCRIBED],
|
||||
example: ipxCurl('POST', '/api/entries/99-invisible/{guid}/position', '{"secs":1234}'),
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/read-all', slug: 'post-read-all-mine',
|
||||
summary: 'Mark every episode of every feed you subscribe to read.',
|
||||
returns: 'Marked',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'files', name: 'files', title: 'Files',
|
||||
summary: 'Downloading, deleting and playing an episode’s file.',
|
||||
items: [
|
||||
{
|
||||
method: 'POST', path: '/api/enclosures/{id}/download', slug: 'post-download',
|
||||
summary: 'Download a file now.',
|
||||
pathParams: [['id', 'i64', 'The file’s id, an <code>EncRow</code>’s <code>id</code>.']],
|
||||
returns: '202 Accepted, or 204 No Content when it is already here', errors: [NOT_SUBSCRIBED],
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/api/enclosures/{id}', slug: 'delete-file',
|
||||
summary: 'Delete a downloaded file. It is not downloaded again.',
|
||||
doc: '<p>There is one copy of each file, so deleting it deletes it for everyone. If someone else has kept the episode or not played it yet, the first try is refused with who: send it again with <code>?force=true</code> to delete it anyway.</p>',
|
||||
pathParams: [['id', 'i64', 'The file’s id.']],
|
||||
query: 'Force', returns: '204 No Content',
|
||||
errors: [['409 Conflict', 'Someone else still wants it; the answer says who. Send <code>force=true</code> to go ahead.'], NOT_SUBSCRIBED],
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/media/{id}', slug: 'get-media',
|
||||
summary: 'The file itself, with <code>Range</code> requests, so a player can seek.',
|
||||
pathParams: [['id', 'i64', 'The file’s id.']],
|
||||
returns: 'The file, with its own Content-Type', errors: [NOT_SUBSCRIBED],
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/media/{id}/deadair.m3u8', slug: 'get-deadair',
|
||||
summary: 'The episode with its long silences shortened by DeadAir, as an HLS playlist.',
|
||||
doc: '<p>Only once DeadAir has looked at the file: an <code>EncRow</code> with <code>deadair</code> set says how many seconds it saves. <code>/media/{id}/deadair</code> gives the shortened episode as one file to save.</p>',
|
||||
pathParams: [['id', 'i64', 'The file’s id.']],
|
||||
returns: 'An HLS playlist (application/vnd.apple.mpegurl)', errors: [NOT_SUBSCRIBED],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'directory', name: 'directory', title: 'The directory, through iPX',
|
||||
summary: 'Browse the directory and subscribe from it; iPX asks it on your behalf.',
|
||||
items: [
|
||||
{
|
||||
method: 'GET', path: '/api/popular', slug: 'get-popular',
|
||||
summary: 'The directory’s ten most subscribed feeds.',
|
||||
returns: 'Vec<PopularRow>', errors: [NO_DIRECTORY],
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/directory', slug: 'get-directory',
|
||||
summary: 'Every feed the directory lists, A to Z.',
|
||||
returns: 'Vec<PopularRow>', errors: [NO_DIRECTORY],
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/directory/{id}', slug: 'get-listed',
|
||||
summary: 'A feed’s page in the directory: what it says it is and its latest items.',
|
||||
pathParams: [['id', 'String', 'The directory’s id for the feed.']],
|
||||
returns: 'Listed', errors: [['404 Not Found', 'Not in the directory.'], NO_DIRECTORY],
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/popular/{id}', slug: 'post-popular',
|
||||
summary: 'Subscribe to a feed from the directory, by the directory’s id.',
|
||||
pathParams: [['id', 'String', 'The directory’s id for the feed.']],
|
||||
returns: 'Subscribed', errors: [['400 Bad Request', 'Not in the directory.'], NO_DIRECTORY],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'server', name: 'server', title: 'The server',
|
||||
summary: 'Its counts and version, and live updates.',
|
||||
items: [
|
||||
{
|
||||
method: 'GET', path: '/api/status', slug: 'get-status',
|
||||
summary: 'How many feeds, files waiting and files downloaded, and the version.',
|
||||
doc: '<p>The numbers <code>ipx status</code> prints, for a dashboard.</p>',
|
||||
returns: 'Status', example: ipxCurl('GET', '/api/status'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/events', slug: 'get-events',
|
||||
summary: 'A live stream of checks and downloads as they happen (server-sent events).',
|
||||
doc: '<p>Each message’s data is one JSON <a href="/docs/api/ipx/types/Event"><code>Event</code></a>. Every event of a check reaches everyone; a feed’s new row (<code>feed_row</code>) only those who subscribe to it.</p>',
|
||||
returns: 'text/event-stream of Event',
|
||||
example: `curl -N -H "Authorization: Bearer ipx_…" "${U}/api/events"\ndata: {"ev":"feed_start","feed":"99-invisible"}\ndata: {"ev":"feed_done","feed":"99-invisible","new":1,"downloaded":1,"failed":0,"torrents":0}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'admin', name: 'admin', title: 'Admin',
|
||||
summary: 'Server settings, accounts, the log and the directory’s administration. Admins only.',
|
||||
items: [
|
||||
{
|
||||
method: 'GET', path: '/api/settings', slug: 'get-settings', access: 'signed in',
|
||||
summary: 'The server’s settings. Anyone signed in may read them.',
|
||||
returns: 'Settings',
|
||||
},
|
||||
{
|
||||
method: 'PATCH', path: '/api/settings', slug: 'patch-settings', access: 'admin',
|
||||
summary: 'Change the server’s settings. They take effect at once.',
|
||||
body: 'SettingsPatch', returns: '204 No Content',
|
||||
errors: [['400 Bad Request', 'A value that does not parse, such as a schedule.'], NOT_ADMIN],
|
||||
example: ipxCurl('PATCH', '/api/settings', '{"schedule":"every 2h","max_total_gb":200}'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/users', slug: 'get-users', access: 'admin',
|
||||
summary: 'Every account.', returns: 'Vec<UserRow>', errors: [NOT_ADMIN],
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/users', slug: 'post-users', access: 'admin',
|
||||
summary: 'Add an account.',
|
||||
doc: '<p>With no password, the account signs in only through single sign-on.</p>',
|
||||
body: 'NewUser', returns: '201 Created',
|
||||
errors: [['400 Bad Request', 'No name, or one that exists already.'], NOT_ADMIN],
|
||||
example: ipxCurl('POST', '/api/users', '{"name":"sam","password":"…"}'),
|
||||
},
|
||||
{
|
||||
method: 'PATCH', path: '/api/users/{id}', slug: 'patch-user', access: 'admin',
|
||||
summary: 'Make an account an admin, or not.',
|
||||
pathParams: [['id', 'i64', 'The account’s id.']],
|
||||
body: 'UserPatch', returns: '204 No Content',
|
||||
errors: [['400 Bad Request', 'No such account, or the only admin, who cannot stop being one.'], NOT_ADMIN],
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/api/users/{id}', slug: 'delete-user', access: 'admin',
|
||||
summary: 'Remove an account, with its subscriptions and read state. Files stay.',
|
||||
pathParams: [['id', 'i64', 'The account’s id.']],
|
||||
returns: '204 No Content',
|
||||
errors: [['400 Bad Request', 'No such account, or the only admin, who cannot be removed.'], NOT_ADMIN],
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/logs', slug: 'get-logs', access: 'admin',
|
||||
summary: 'The newest lines of the server’s log, or those after a given one.',
|
||||
query: 'LogQuery', returns: 'LogPage', errors: [NOT_ADMIN],
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/directory-status', slug: 'get-directory-status', access: 'admin',
|
||||
summary: 'Who the directory takes this server’s token to be, and how the last share went.',
|
||||
returns: 'DirectoryStatus', errors: [NOT_ADMIN],
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/api/directory/{id}', slug: 'delete-listed', access: 'admin',
|
||||
summary: 'Remove a feed from the directory and keep it out.',
|
||||
doc: '<p>Only when this server’s directory token is <code>rwa</code>; the directory refuses otherwise.</p>',
|
||||
pathParams: [['id', 'String', 'The directory’s id for the feed.']],
|
||||
returns: '204 No Content', errors: [NOT_ADMIN, NO_DIRECTORY],
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/api/directory/{id}/refresh', slug: 'post-listed-refresh', access: 'admin',
|
||||
summary: 'Have the directory check a feed now. Needs an <code>rwa</code> token.',
|
||||
pathParams: [['id', 'String', 'The directory’s id for the feed.']],
|
||||
returns: '204 No Content', errors: [NOT_ADMIN, NO_DIRECTORY],
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/api/directory-admin', slug: 'get-directory-admin', access: 'admin',
|
||||
summary: 'The servers sharing with the directory, and the feeds it keeps out. Needs <code>rwa</code>.',
|
||||
returns: 'DirectoryAdmin', errors: [NOT_ADMIN, NO_DIRECTORY],
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/api/directory-blocked/{id}', slug: 'delete-directory-blocked', access: 'admin',
|
||||
summary: 'Let a feed the directory keeps out back in. Needs <code>rwa</code>.',
|
||||
pathParams: [['id', 'String', 'The directory’s id for the feed.']],
|
||||
returns: '204 No Content', errors: [NOT_ADMIN, NO_DIRECTORY],
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/api/directory-instances/{name}', slug: 'delete-directory-instance', access: 'admin',
|
||||
summary: 'Drop a server’s share from the directory until it next shares. Needs <code>rwa</code>.',
|
||||
pathParams: [['name', 'String', 'The server’s token name.']],
|
||||
returns: '204 No Content', errors: [NOT_ADMIN, NO_DIRECTORY],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
types: [
|
||||
{ name: 'Credentials', doc: 'A name and password.', fields: [['name', 'String', ''], ['password', 'String', '']] },
|
||||
{ name: 'Me', doc: 'Who is signed in.', fields: [
|
||||
['name', 'String', 'The account’s name, often an email address.'],
|
||||
['admin', 'bool', ''],
|
||||
['blocked', 'Vec<String>', 'Words that hide an item in every feed you read. <code>GET /api/me</code> only, as are the fields below.'],
|
||||
['sign_out', 'Option<String>', 'Where signing out should go, for someone single sign-on signed in.'],
|
||||
['deadair_saved', 'i64', 'Seconds DeadAir has saved you, all told.'],
|
||||
['version', 'String', 'ipx’s version.'],
|
||||
] },
|
||||
{ name: 'MePatch', doc: 'What <code>PATCH /api/me</code> changes.', fields: [['blocked', 'Option<Vec<String>>', 'Replaces the list.']] },
|
||||
{ name: 'Token', doc: 'An API token, as listed.', fields: [['id', 'i64', ''], ['name', 'String', ''], ['created', 'i64', ''], ['last_used', 'Option<i64>', '']] },
|
||||
{ name: 'NewToken', doc: 'A token to make.', fields: [['name', 'String', 'What it is for, to know it by when revoking it.']] },
|
||||
{ name: 'NewTokenMade', doc: 'A token just made: the only time it is shown.', fields: [['id', 'i64', ''], ['name', 'String', ''], ['token', 'String', 'Begins <code>ipx_</code>. Send it as <code>Authorization: Bearer</code>.']] },
|
||||
{ name: 'FeedRow', doc: 'A feed as you see it: the feed, your settings for it and its counts for you.', fields: [
|
||||
['id', 'String', ''], ['url', 'String', ''], ['title', 'Option<String>', ''], ['image', 'Option<String>', ''],
|
||||
['folder', 'Option<String>', ''],
|
||||
['category', 'Option<String>', 'The directory category an admin gave it.'],
|
||||
['feed_category', 'Option<String>', 'The one the feed names itself, which wins.'],
|
||||
['keywords', 'Vec<String>', 'Your words: with any, only episodes that mention one are downloaded.'],
|
||||
['blocked', 'Vec<String>', 'Your words that hide an episode of this feed.'],
|
||||
['deadair', 'bool', 'Played with its silences shortened.'],
|
||||
['deadair_pause', 'i64', 'The pause DeadAir leaves where it cuts, in milliseconds.'],
|
||||
['allow_explicit', 'bool', ''], ['auto_download', 'bool', ''],
|
||||
['max_new_per_check', 'Option<usize>', 'Your own limit, or none for the server’s.'],
|
||||
['group', 'Option<String>', 'The OPML list it came from.'],
|
||||
['orphaned', 'bool', 'In a list that no longer has it, kept for its downloads.'],
|
||||
['managed', 'bool', ''],
|
||||
['schedule', 'Option<String>', 'Its own schedule, such as <code>every 2h</code>.'],
|
||||
['schedule_mins', 'Option<u64>', 'The same in minutes.'],
|
||||
['every_mins', 'u64', 'How often it is checked, all things considered.'],
|
||||
['last_checked', 'Option<i64>', ''], ['next_check', 'Option<i64>', ''],
|
||||
['last_error', 'Option<String>', ''],
|
||||
['failing', 'Option<FailingRow>', 'Set once an error has held for a day.'],
|
||||
['entries', 'i64', ''], ['downloaded', 'i64', ''], ['unread', 'i64', ''],
|
||||
['subscribers', 'i64', 'People on this server, you included.'],
|
||||
['pinned', 'bool', 'At the top of your list.'],
|
||||
['private', 'bool', 'Kept out of the directory.'],
|
||||
['private_by_address', 'bool', 'Private whatever it is marked: a login, or a key in its address.'],
|
||||
] },
|
||||
{ name: 'FailingRow', doc: 'Why a feed has been failing.', fields: [['reason', 'String', 'In words.'], ['new_url', 'Option<String>', 'Where it seems to have moved.']] },
|
||||
{ name: 'NewFeed', doc: 'A feed to subscribe to.', fields: [
|
||||
['url', 'String', 'A feed’s address, an OPML list’s, or a site’s page that links its feed.'],
|
||||
['folder', 'Option<String>', ''],
|
||||
['keywords', 'Vec<String>', 'Download only episodes that mention one. Empty for all.'],
|
||||
['allow_explicit', 'bool', 'Download explicit episodes too. False if left out.'],
|
||||
] },
|
||||
{ name: 'Added', doc: 'A feed subscribed to.', fields: [['id', 'String', 'Its id here.'], ['existing', 'bool', 'You subscribed to it already.']] },
|
||||
{ name: 'FeedPatch', doc: 'What <code>PATCH /api/feeds/{id}</code> changes. Leave out what stays; <code>null</code> clears a field that can be cleared.', fields: [
|
||||
['keywords', 'Option<Vec<String>>', 'Yours.'], ['blocked', 'Option<Vec<String>>', 'Yours.'],
|
||||
['allow_explicit', 'Option<bool>', 'Yours.'], ['auto_download', 'Option<bool>', 'Yours.'],
|
||||
['max_new_per_check', 'Option<Option<usize>>', 'Yours; <code>null</code> for the server’s.'],
|
||||
['pinned', 'Option<bool>', 'Yours.'],
|
||||
['deadair', 'Option<Option<bool>>', 'Yours; <code>null</code> follows its OPML list’s.'],
|
||||
['deadair_pause', 'Option<i64>', 'Yours: 200, 300, 400 or 500.'],
|
||||
['private', 'Option<bool>', 'Anyone subscribed may mark it private; only an admin unmarks it.'],
|
||||
['url', 'Option<String>', 'Admin.'], ['schedule', 'Option<Option<String>>', 'Admin.'],
|
||||
['folder', 'Option<Option<String>>', 'Admin.'], ['category', 'Option<Option<String>>', 'Admin.'],
|
||||
] },
|
||||
{ name: 'Marked', doc: '', fields: [['marked', 'i64', 'How many episodes were marked.']] },
|
||||
{ name: 'HowMany', doc: '', fields: [['count', 'i64', 'From 1 to 100; 5 if left out.']] },
|
||||
{ name: 'Queued', doc: '', fields: [['queued', 'usize', 'How many files were queued.']] },
|
||||
{ name: 'FetchBody', doc: 'What to check.', fields: [['feed', 'Option<String>', 'One feed; all of yours if left out.'], ['force', 'bool', 'Check even if it is not due.']] },
|
||||
{ name: 'OpmlBody', doc: '', fields: [['xml', 'String', 'The OPML file’s text.']] },
|
||||
{ name: 'Imported', doc: '', fields: [['added', 'usize', ''], ['already', 'usize', 'Feeds you had.']] },
|
||||
{ name: 'Page', doc: 'Which episodes, as query parameters.', fields: [
|
||||
['offset', 'i64', '0 if left out.'], ['limit', 'i64', '50 if left out.'],
|
||||
['filter', 'Option<String>', '<code>unread</code>, <code>downloaded</code> or <code>flagged</code> (kept).'],
|
||||
['q', 'Option<String>', 'Words to look for in titles and show notes.'],
|
||||
['sort', 'Option<String>', '<code>published</code>, <code>title</code>, <code>feed</code>, <code>type</code>, <code>size</code> or <code>kept</code>. Newest first if left out.'],
|
||||
['dir', 'Option<String>', '<code>asc</code> or <code>desc</code>.'],
|
||||
] },
|
||||
{ name: 'EntryPage', doc: 'A page of episodes.', fields: [['total', 'i64', 'How many match, over every page.'], ['entries', 'Vec<EntryRow>', '']] },
|
||||
{ name: 'EntryRow', doc: 'An episode or post, with your state for it.', fields: [
|
||||
['guid', 'String', ''], ['feed_id', 'String', ''], ['title', 'Option<String>', ''], ['link', 'Option<String>', ''],
|
||||
['published', 'Option<i64>', ''],
|
||||
['description', 'Option<String>', 'Show notes, HTML, already sanitized.'],
|
||||
['read', 'bool', ''], ['flagged', 'bool', 'Kept: its file is never cleared to save space.'],
|
||||
['image', 'Option<String>', ''], ['duration', 'Option<i64>', 'Seconds.'],
|
||||
['episode', 'Option<i64>', ''], ['season', 'Option<i64>', ''],
|
||||
['position', 'i64', 'Where you are in it, in seconds.'],
|
||||
['enclosures', 'Vec<EncRow>', 'Its files.'],
|
||||
] },
|
||||
{ name: 'EncRow', doc: 'An episode’s file.', fields: [
|
||||
['id', 'i64', 'What <code>/media/{id}</code> and the file routes take.'],
|
||||
['feed_id', 'String', ''], ['guid', 'String', ''], ['url', 'String', 'Where the publisher has it.'],
|
||||
['mime', 'Option<String>', ''], ['length', 'Option<i64>', 'Bytes.'],
|
||||
['path', 'Option<String>', 'Where it is on the server, once downloaded.'],
|
||||
['state', 'String', '<code>pending</code> (a check will download it), <code>held</code> (back catalogue, downloaded on request), <code>downloading</code>, <code>done</code>, <code>skipped</code> (a filter or a failure) or <code>reaped</code> (deleted).'],
|
||||
['last_error', 'Option<String>', ''],
|
||||
['deadair', 'Option<i64>', 'Seconds DeadAir saves, when you play it shortened. Absent otherwise.'],
|
||||
['deadair_pending', 'bool', 'DeadAir is still working on it. Absent when false.'],
|
||||
] },
|
||||
{ name: 'Flags', doc: '', fields: [['read', 'Option<bool>', ''], ['flagged', 'Option<bool>', 'Kept.']] },
|
||||
{ name: 'Position', doc: '', fields: [['secs', 'i64', 'Seconds in.'], ['duration', 'Option<i64>', 'The length the player measured, for an episode whose feed gives none.']] },
|
||||
{ name: 'Force', doc: 'A query parameter.', fields: [['force', 'bool', 'Delete it even though someone else wants it.']] },
|
||||
{ name: 'PopularRow', doc: 'A feed in the directory. Never its address: subscribe by its id.', fields: [
|
||||
['id', 'String', 'The directory’s id for it.'], ['title', 'Option<String>', ''], ['image', 'Option<String>', ''],
|
||||
['subscribers', 'i64', 'On every server sharing with the directory.'],
|
||||
['subscribed', 'bool', 'Yours already.'], ['feed', 'Option<String>', 'Its id here, when it is yours.'],
|
||||
['category', 'Option<String>', ''], ['subcategory', 'Option<String>', ''],
|
||||
['podcast', 'bool', 'Has audio or video.'],
|
||||
] },
|
||||
{ name: 'Listed', doc: 'A feed’s page in the directory.', fields: [
|
||||
['description', 'Option<String>', 'What it says it is, sanitized.'],
|
||||
['failing', 'Option<String>', 'Why its last check failed, when it did.'],
|
||||
['items', 'Vec<ListedItem>', 'Its latest twenty.'],
|
||||
['can_admin', 'bool', 'You may remove or refresh it.'],
|
||||
] },
|
||||
{ name: 'ListedItem', doc: '', fields: [['guid', 'String', ''], ['title', 'Option<String>', ''], ['link', 'Option<String>', ''], ['published', 'Option<i64>', ''], ['duration', 'Option<i64>', ''], ['description', 'Option<String>', 'Sanitized.']] },
|
||||
{ name: 'Subscribed', doc: '', fields: [['id', 'String', 'The feed’s id here.']] },
|
||||
{ name: 'Status', doc: '', fields: [['feeds', 'usize', ''], ['pending', 'usize', 'Files a check will download.'], ['downloaded', 'usize', ''], ['version', 'String', '']] },
|
||||
{ name: 'Event', doc: 'One live update. <code>ev</code> says which, and the rest depends on it.', fields: [
|
||||
['feed_start', '{ feed }', 'A feed is being checked.'],
|
||||
['feed_skip', '{ feed }', 'Not due.'],
|
||||
['feed_done', '{ feed, new, downloaded, failed, torrents }', ''],
|
||||
['feed_error', '{ feed, msg }', ''],
|
||||
['feed_row', '{ row: FeedRow }', 'A feed you subscribe to changed.'],
|
||||
['progress', '{ feed, enclosure, file, done, total }', 'Bytes of a download, in whole percents.'],
|
||||
['download_done', '{ feed, enclosure, path, bytes }', ''],
|
||||
['download_error', '{ feed, enclosure, msg, url }', ''],
|
||||
['deadair_done', '{ feed, enclosure, saved_s }', 'DeadAir finished a file.'],
|
||||
['scan_done', '{ feeds }', 'A check finished; how many feeds it looked at.'],
|
||||
] },
|
||||
{ name: 'Settings', doc: 'The server’s settings.', fields: [
|
||||
['schedule', 'String', 'How often feeds are checked, such as <code>every 60m</code>.'], ['every_mins', 'u64', 'The same in minutes.'],
|
||||
['max_new_per_check', 'usize', 'The newest episodes a check downloads, a feed.'],
|
||||
['media_types', 'Vec<String>', 'What is downloaded, such as <code>audio</code>, <code>video</code>.'],
|
||||
['download_dir', 'String', ''], ['max_total_gb', 'f64', 'Disk to use; 0 for no limit.'],
|
||||
['max_age_days', 'u64', '0 for no limit.'], ['art_cache_mb', 'u64', 'Artwork kept.'],
|
||||
['directory_url', 'String', ''], ['directory_token_set', 'bool', 'The token itself is never sent back.'],
|
||||
['directory_share', 'bool', ''],
|
||||
] },
|
||||
{ name: 'SettingsPatch', doc: 'What <code>PATCH /api/settings</code> changes. Leave out what stays.', fields: [
|
||||
['schedule', 'Option<String>', ''], ['max_new_per_check', 'Option<usize>', ''], ['media_types', 'Option<Vec<String>>', ''],
|
||||
['max_total_gb', 'Option<f64>', ''], ['max_age_days', 'Option<u64>', ''], ['art_cache_mb', 'Option<u64>', ''],
|
||||
['directory_url', 'Option<String>', 'Empty for no directory.'], ['directory_token', 'Option<String>', 'Replaces it; empty clears it.'],
|
||||
['directory_share', 'Option<bool>', ''],
|
||||
] },
|
||||
{ name: 'UserRow', doc: 'An account.', fields: [['id', 'i64', ''], ['name', 'String', ''], ['admin', 'bool', ''], ['password', 'bool', 'Has one; without, it signs in only by single sign-on.'], ['created', 'Option<i64>', ''], ['last_login', 'Option<i64>', '']] },
|
||||
{ name: 'NewUser', doc: '', fields: [['name', 'String', 'No commas, semicolons or line breaks.'], ['password', 'String', 'Empty for single sign-on only.'], ['admin', 'bool', '']] },
|
||||
{ name: 'UserPatch', doc: '', fields: [['admin', 'bool', '']] },
|
||||
{ name: 'LogQuery', doc: 'Query parameters.', fields: [['after', 'u64', 'The last <code>seq</code> you have; 0 for the newest lines.'], ['limit', 'usize', '200 if left out.']] },
|
||||
{ name: 'LogPage', doc: '', fields: [['lines', 'Vec<LogLine>', ''], ['latest', 'u64', 'The newest <code>seq</code>, to ask after next time.']] },
|
||||
{ name: 'LogLine', doc: '', fields: [['seq', 'u64', ''], ['ts', 'i64', ''], ['level', 'String', ''], ['target', 'String', ''], ['msg', 'String', '']] },
|
||||
{ name: 'DirectoryStatus', doc: '', fields: [
|
||||
['configured', 'bool', 'An address and token are set.'], ['name', 'Option<String>', 'The token’s name, as the directory knows it.'],
|
||||
['access', 'Option<String>', '<code>ro</code>, <code>rw</code> or <code>rwa</code>.'], ['error', 'Option<String>', 'Why the directory would not say.'],
|
||||
['shared', 'Option<SnapshotResult>', 'How the last share went.'],
|
||||
] },
|
||||
{ name: 'DirectoryAdmin', doc: '', fields: [['instances', 'Vec<Instance>', 'Servers sharing.'], ['blocked', 'Vec<BlockedRow>', '']] },
|
||||
{ name: 'BlockedRow', doc: 'A feed the directory keeps out. Never its address.', fields: [['id', 'String', ''], ['title', 'Option<String>', ''], ['at', 'i64', 'When.']] },
|
||||
{ name: 'Instance', doc: 'A server sharing with the directory.', fields: [['name', 'String', 'Its token’s name.'], ['feeds', 'i64', ''], ['subscribers', 'i64', '']] },
|
||||
{ name: 'SnapshotResult', doc: 'What the directory made of a share.', fields: [['accepted', 'usize', ''], ['refused_private', 'usize', 'Addresses that look like someone’s paid access.'], ['refused_blocked', 'usize', ''], ['refused_invalid', 'usize', 'Not http(s).']] },
|
||||
],
|
||||
};
|
||||
|
||||
export const directory = {
|
||||
name: 'ipx_directory',
|
||||
label: 'ipx-directory',
|
||||
root: '/docs/api/directory',
|
||||
changelog: 'crates/directory/CHANGELOG.md',
|
||||
intro: `<p>The HTTP API of the directory of public podcasts that iPX servers share, at
|
||||
<code>${D}/v1</code>. Its pages at <a href="${D}">${D.replace('https://', '')}</a> are anyone’s
|
||||
to browse; the API needs a token for everything.</p>
|
||||
<h2 id="auth">Tokens</h2>
|
||||
<pre><code>Authorization: Bearer <token></code></pre>
|
||||
<p>A token has a name and one of three levels of access: <code>ro</code> reads,
|
||||
<code>rw</code> also shares, and <code>rwa</code> also removes and blocks feeds and drops a
|
||||
server’s share. Tokens are given out by whoever runs the directory, and none can be made or
|
||||
revoked over the API.</p>
|
||||
<h2 id="errors">Errors</h2>
|
||||
<p>A request that fails answers with its status and <code>{"error": "…"}</code>:
|
||||
<code>401</code> no token or an unknown one, <code>403</code> a token without the access,
|
||||
<code>404</code> not listed.</p>
|
||||
<h2 id="ids">Ids</h2>
|
||||
<p>A feed’s <code>id</code> is the first 16 hex digits of the SHA-256 of its address with the
|
||||
scheme and host in lower case and no default port or fragment, so every server arrives at the
|
||||
same one. Descriptions are the publisher’s own HTML, unsanitized: sanitize them before you
|
||||
show them.</p>`,
|
||||
groups: [
|
||||
{
|
||||
id: 'feeds', name: 'feeds', title: 'Feeds',
|
||||
summary: 'What the directory lists.',
|
||||
items: [
|
||||
{
|
||||
method: 'GET', path: '/v1/me', slug: 'get-me', access: 'ro',
|
||||
summary: 'The token’s name and access.', returns: 'Me', example: dirCurl('GET', '/v1/me'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/v1/feeds', slug: 'get-feeds', access: 'ro',
|
||||
summary: 'Every feed listed, A to Z.', returns: 'Vec<Listing>', example: dirCurl('GET', '/v1/feeds'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/v1/popular', slug: 'get-popular', access: 'ro',
|
||||
summary: 'The most subscribed feeds.', query: 'Limit', returns: 'Vec<Listing>',
|
||||
example: dirCurl('GET', '/v1/popular?limit=5'),
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/v1/feeds/{id}', slug: 'get-feed', access: 'ro',
|
||||
summary: 'One feed, with its description and latest twenty items.',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']],
|
||||
returns: 'FeedPage', errors: [['404 Not Found', 'Not listed.']],
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/healthz', slug: 'get-healthz', access: 'none',
|
||||
summary: '<code>ok</code> when the directory can read its database.', returns: 'text/plain',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'share', name: 'share', title: 'Sharing',
|
||||
summary: 'A server telling the directory what its people follow.',
|
||||
items: [
|
||||
{
|
||||
method: 'POST', path: '/v1/snapshot', slug: 'post-snapshot', access: 'rw',
|
||||
summary: 'Share: every public feed this server’s people follow, and how many follow each.',
|
||||
doc: '<p>Replaces everything this token shared before, so send the whole list each time. At most 20,000 feeds. Addresses that look private (a login, a key in the query, a paid-feed host) are refused and counted, never stored. A feed is listed once the directory has read it as one.</p>',
|
||||
body: 'Vec<SnapshotEntry>', returns: 'SnapshotResult',
|
||||
errors: [['413 Payload Too Large', 'More than 20,000 feeds.']],
|
||||
example: dirCurl('POST', '/v1/snapshot', '[{"url":"https://feeds.99percentinvisible.org/99percentinvisible","subscribers":3}]'),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'admin', name: 'admin', title: 'Administering it',
|
||||
summary: 'Removing and blocking feeds, and the servers sharing. <code>rwa</code> tokens only.',
|
||||
items: [
|
||||
{
|
||||
method: 'DELETE', path: '/v1/feeds/{id}', slug: 'delete-feed', access: 'rwa',
|
||||
summary: 'Remove a feed and block it, so no server’s share brings it back.',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']], returns: '204 No Content',
|
||||
},
|
||||
{
|
||||
method: 'POST', path: '/v1/feeds/{id}/refresh', slug: 'post-refresh', access: 'rwa',
|
||||
summary: 'Check a feed now, answering with its page.',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']], returns: 'FeedPage',
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/v1/blocked', slug: 'get-blocked', access: 'rwa',
|
||||
summary: 'The feeds kept out.', returns: 'Vec<Blocked>',
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/v1/blocked/{id}', slug: 'delete-blocked', access: 'rwa',
|
||||
summary: 'Let a blocked feed back in.',
|
||||
pathParams: [['id', 'String', 'The feed’s id.']], returns: '204 No Content',
|
||||
},
|
||||
{
|
||||
method: 'GET', path: '/v1/instances', slug: 'get-instances', access: 'rwa',
|
||||
summary: 'Each token holding a share, with how many feeds and subscribers it gave.',
|
||||
returns: 'Vec<Instance>',
|
||||
},
|
||||
{
|
||||
method: 'DELETE', path: '/v1/instances/{name}', slug: 'delete-instance', access: 'rwa',
|
||||
summary: 'Drop one token’s share, its counts with it, until it next shares.',
|
||||
doc: '<p>To keep a server out for good, revoke its token instead.</p>',
|
||||
pathParams: [['name', 'String', 'The token’s name.']], returns: '204 No Content',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
types: [
|
||||
{ name: 'Me', doc: 'A token, as the directory knows it.', fields: [['name', 'String', ''], ['access', 'Access', '']] },
|
||||
{ name: 'Access', doc: 'A token’s access: <code>"ro"</code>, <code>"rw"</code> or <code>"rwa"</code>.', fields: [] },
|
||||
{ name: 'Limit', doc: 'A query parameter.', fields: [['limit', 'Option<u64>', 'From 1 to 100; 10 if left out.']] },
|
||||
{ name: 'Listing', doc: 'A feed listed.', fields: [
|
||||
['id', 'String', ''], ['url', 'String', 'Its address, to subscribe to anywhere.'], ['title', 'Option<String>', ''], ['image', 'Option<String>', ''],
|
||||
['category', 'Option<String>', 'Apple’s category, from the feed’s own.'], ['subcategory', 'Option<String>', ''],
|
||||
['podcast', 'bool', 'Audio or video in its latest items.'],
|
||||
['subscribers', 'i64', 'Summed over every server’s latest share.'],
|
||||
] },
|
||||
{ name: 'FeedPage', doc: 'A feed’s page: every field of <a href="/docs/api/directory/types/Listing"><code>Listing</code></a>, and these.', fields: [
|
||||
['description', 'Option<String>', 'The feed’s own HTML, unsanitized.'],
|
||||
['failing', 'Option<String>', 'Why its last check failed, in words.'],
|
||||
['items', 'Vec<Item>', 'Its latest twenty.'],
|
||||
] },
|
||||
{ name: 'Item', doc: 'An episode or post. Never its file.', fields: [['guid', 'String', ''], ['title', 'Option<String>', ''], ['link', 'Option<String>', ''], ['published', 'Option<i64>', 'Unix seconds.'], ['duration', 'Option<i64>', 'Seconds.'], ['description', 'Option<String>', 'Unsanitized.']] },
|
||||
{ name: 'SnapshotEntry', doc: 'One feed in a share.', fields: [['url', 'String', ''], ['subscribers', 'i64', ''], ['category', 'Option<String>', 'A category for a feed that names none itself.']] },
|
||||
{ name: 'SnapshotResult', doc: 'What the directory made of a share.', fields: [['accepted', 'usize', ''], ['refused_private', 'usize', ''], ['refused_blocked', 'usize', ''], ['refused_invalid', 'usize', 'Not http(s).']] },
|
||||
{ name: 'Blocked', doc: '', fields: [['id', 'String', ''], ['url', 'Option<String>', ''], ['title', 'Option<String>', ''], ['at', 'i64', 'When.']] },
|
||||
{ name: 'Instance', doc: '', fields: [['name', 'String', 'The token’s name.'], ['feeds', 'i64', ''], ['subscribers', 'i64', '']] },
|
||||
],
|
||||
};
|
||||
@@ -10,3 +10,5 @@ cp "$here/index.html" "$here/site.css" "$here/wave.svg" "$here/gitea.svg" "$here
|
||||
cp "$here/../web/InterVariable.woff2" "$here/dist/fonts/inter.woff2"
|
||||
cp "$here/../web/logo.svg" "$here/../web/favicon.png" "$here/dist/"
|
||||
cp -r "$here/shots" "$here/dist/"
|
||||
# The docs: the guides and the API references, generated (#223).
|
||||
node "$here/gen.mjs"
|
||||
|
||||
24
site/docs.mjs
Normal file
24
site/docs.mjs
Normal file
@@ -0,0 +1,24 @@
|
||||
// The guides: a page each, from site/guides, with the docs' front page written here (#223).
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const read = name => fs.readFileSync(path.join(here, 'guides', name), 'utf8');
|
||||
|
||||
const front = `<h1>Docs</h1>
|
||||
<p class="lede">How to run iPX on your own server, and how to talk to it and to the directory from a program of your own.</p>
|
||||
<dl class="cards">
|
||||
<div><dt><a href="/docs/install">Install ipx and ipx-web</a></dt><dd>Build the two containers, start them, sign in and add people.</dd></div>
|
||||
<div><dt><a href="/docs/cli">The command line</a></dt><dd>The <code>ipx</code> commands, and the control socket a program on the same machine can use.</dd></div>
|
||||
<div><dt><a href="/docs/directory">The directory</a></dt><dd>Browsing it, connecting your iPX to it, and running one of your own.</dd></div>
|
||||
<div><dt><a href="/docs/api/ipx/">ipx API reference</a></dt><dd>Every endpoint of an iPX server, what it takes and what it gives.</dd></div>
|
||||
<div><dt><a href="/docs/api/directory/">ipx-directory API reference</a></dt><dd>The directory's API, for reading what it lists and sharing with it.</dd></div>
|
||||
</dl>`;
|
||||
|
||||
export const guides = [
|
||||
{ href: '/docs/', file: 'docs/index.html', name: 'Overview', title: 'iPX docs', description: 'How to run iPX on your own server, and how to use its API and the directory’s.', body: front },
|
||||
{ href: '/docs/install', file: 'docs/install.html', name: 'Install', title: 'Install ipx and ipx-web - iPX docs', description: 'Run iPX and its page on your own server with Docker.', body: read('install.html') },
|
||||
{ href: '/docs/cli', file: 'docs/cli.html', name: 'Command line', title: 'The command line - iPX docs', description: 'The ipx commands, and its control socket.', body: read('cli.html') },
|
||||
{ href: '/docs/directory', file: 'docs/directory.html', name: 'Directory', title: 'The directory - iPX docs', description: 'Browse the directory, connect your iPX to it, or run your own.', body: read('directory.html') },
|
||||
];
|
||||
212
site/gen.mjs
Normal file
212
site/gen.mjs
Normal file
@@ -0,0 +1,212 @@
|
||||
// The docs pages, into site/dist/docs: the guides in docs.mjs, and an API reference for each
|
||||
// service from api.mjs, laid out as docs.rs lays out a crate (#223): a root page listing its
|
||||
// modules and types, a page a module listing its endpoints, a page an endpoint and a page a type.
|
||||
// No script: the site's Content-Security-Policy allows none of its own.
|
||||
//
|
||||
// node site/gen.mjs (site/build.sh runs it)
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { ipx, directory } from './api.mjs';
|
||||
import { guides } from './docs.mjs';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const dist = path.join(here, 'dist');
|
||||
const SRC = 'https://git.sdf1.net/rays/ipx/src/branch/main';
|
||||
|
||||
const esc = s => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
|
||||
/// The version a reference documents: its service's last release, from its changelog, not the
|
||||
/// -dev version between releases.
|
||||
function released(changelog) {
|
||||
const m = fs.readFileSync(path.join(here, '..', changelog), 'utf8').match(/^## \[(\d+\.\d+\.\d+)\]/m);
|
||||
return m ? m[1] : '';
|
||||
}
|
||||
|
||||
function write(rel, html) {
|
||||
const file = path.join(dist, rel);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, html);
|
||||
}
|
||||
|
||||
function shell({ title, description, sidebar, body, current }) {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>${esc(title)}</title>
|
||||
<meta name="description" content="${esc(description)}">
|
||||
<meta name="color-scheme" content="light">
|
||||
<link rel="icon" href="/favicon.png">
|
||||
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="/site.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="bar">
|
||||
<a class="home" href="/"><img src="/logo.svg" alt="" width="36" height="36">iPX</a>
|
||||
<nav aria-label="Elsewhere">
|
||||
<a href="/docs/" aria-current="true">Docs</a>
|
||||
<a href="https://directory.ipxreader.app">Directory</a>
|
||||
<a class="src" href="https://git.sdf1.net/rays/ipx" title="Source code on git.sdf1.net"><img src="/gitea.svg" alt="Source code" width="28" height="28"></a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="docs">
|
||||
<aside class="side">${sidebar}</aside>
|
||||
<main class="doc">${body}</main>
|
||||
</div>
|
||||
<footer>
|
||||
<p>iPX is free and open source under the MIT licence.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
/* ---------------- the guides ---------------- */
|
||||
|
||||
const REFS = [[ipx, 'ipx'], [directory, 'ipx-directory']];
|
||||
|
||||
function guideSidebar(cur) {
|
||||
const li = (href, name, on) => `<li><a href="${href}"${on ? ' aria-current="page"' : ''}>${name}</a></li>`;
|
||||
return `<nav aria-label="Docs">
|
||||
<h2 class="side-h">Guides</h2>
|
||||
<ul>${guides.map(g => li(g.href, g.name, g.href === cur)).join('')}</ul>
|
||||
<h2 class="side-h">API reference</h2>
|
||||
<ul>${REFS.map(([r, label]) => li(r.root + '/', label, false)).join('')}</ul>
|
||||
</nav>`;
|
||||
}
|
||||
|
||||
for (const g of guides) {
|
||||
write(g.file, shell({ title: g.title, description: g.description, sidebar: guideSidebar(g.href), body: g.body, current: 'docs' }));
|
||||
}
|
||||
|
||||
/* ---------------- the references ---------------- */
|
||||
|
||||
const METHOD_CLASS = { GET: 'm-get', POST: 'm-post', PATCH: 'm-patch', PUT: 'm-patch', DELETE: 'm-delete' };
|
||||
|
||||
function reference(api) {
|
||||
const label = api.label || api.name;
|
||||
const version = released(api.changelog);
|
||||
const typeNames = new Set(api.types.map(t => t.name));
|
||||
const typeHref = n => `${api.root}/types/${n}`;
|
||||
const itemHref = (g, it) => `${api.root}/${g.id}/${it.slug}`;
|
||||
const fnName = it => it.slug.replace(/-/g, '_');
|
||||
// A Rust type, its names that are types of this API linked.
|
||||
const ty = s => esc(s).replace(/\b[A-Z][A-Za-z]+\b/g, n => typeNames.has(n) ? `<a class="t" href="${typeHref(n)}">${n}</a>` : n);
|
||||
const isType = s => /^[A-Z]/.test(s) && /[A-Za-z>]$/.test(s) && !/\s/.test(s.replace(/, /g, ','));
|
||||
const access = it => it.access || 'signed in';
|
||||
|
||||
// Which endpoints mention each type, for its "Used by", as docs.rs lists where a type turns up.
|
||||
const usedBy = new Map();
|
||||
for (const g of api.groups) for (const it of g.items) {
|
||||
for (const s of [it.body, it.query, it.returns].filter(Boolean)) {
|
||||
for (const n of s.match(/\b[A-Z][A-Za-z]+\b/g) || []) if (typeNames.has(n)) {
|
||||
if (!usedBy.has(n)) usedBy.set(n, []);
|
||||
if (!usedBy.get(n).some(([, x]) => x === it)) usedBy.get(n).push([g, it]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Types inside types: a type used only as a field is reached from the type that holds it.
|
||||
for (const t of api.types) for (const [, ft] of t.fields) {
|
||||
for (const n of ft.match(/\b[A-Z][A-Za-z]+\b/g) || []) if (typeNames.has(n) && n !== t.name) {
|
||||
if (!usedBy.has(n)) usedBy.set(n, []);
|
||||
if (!usedBy.get(n).some(([, x]) => x === t)) usedBy.get(n).push([null, t]);
|
||||
}
|
||||
}
|
||||
|
||||
const crumbs = (...parts) => `<p class="path"><a href="${api.root}/">${esc(api.name)}</a>${parts.map(([h, n]) => `::<a href="${h}">${n}</a>`).join('')}</p>`;
|
||||
const top = `<a class="crate" href="${api.root}/"><img src="/logo.svg" alt="" width="40" height="40"><span><b>${esc(label)}</b>${version ? `<span class="ver">${version}</span>` : ''}</span></a>`;
|
||||
const back = `<p class="side-back"><a href="/docs/">All docs</a></p>`;
|
||||
|
||||
function sidebar({ group, item, type } = {}) {
|
||||
let s = top;
|
||||
if (group) {
|
||||
s += `<h2 class="side-h">Module <a href="${api.root}/${group.id}/">${group.name}</a></h2>
|
||||
<ul class="items">${group.items.map(it => `<li><a class="${METHOD_CLASS[it.method]}" href="${itemHref(group, it)}" title="${it.method} ${esc(it.path)}"${it === item ? ' aria-current="page"' : ''}><span class="verb">${it.method}</span> ${fnName(it)}</a></li>`).join('')}</ul>`;
|
||||
}
|
||||
s += `<h2 class="side-h">Modules</h2><ul>${api.groups.map(g => `<li><a href="${api.root}/${g.id}/"${g === group && !item ? ' aria-current="page"' : ''}>${g.name}</a></li>`).join('')}</ul>`;
|
||||
s += `<h2 class="side-h">Types</h2><ul class="types">${api.types.map(t => `<li><a class="t" href="${typeHref(t.name)}"${t === type ? ' aria-current="page"' : ''}>${t.name}</a></li>`).join('')}</ul>`;
|
||||
return `<nav aria-label="${esc(label)} reference">${s}</nav>${back}`;
|
||||
}
|
||||
|
||||
const page = (rel, title, description, side, body) =>
|
||||
write(rel, shell({ title, description, sidebar: side, body, current: 'docs' }));
|
||||
|
||||
// The root: what the crate page shows on docs.rs, its modules and types.
|
||||
page(`${api.root.slice(1)}/index.html`, `${label} API`, `The HTTP API of ${label}, endpoint by endpoint.`, sidebar(),
|
||||
`<h1 class="item"><span class="kind">API</span> <span class="name">${esc(label)}</span>${version ? ` <span class="ver">${version}</span>` : ''}</h1>
|
||||
${api.intro}
|
||||
<h2 id="modules">Modules</h2>
|
||||
<dl class="list">${api.groups.map(g => `<dt><a href="${api.root}/${g.id}/">${g.name}</a></dt><dd>${g.summary}</dd>`).join('')}</dl>
|
||||
<h2 id="types">Types</h2>
|
||||
<dl class="list">${api.types.map(t => `<dt><a class="t" href="${typeHref(t.name)}">${t.name}</a></dt><dd>${t.doc || ''}</dd>`).join('')}</dl>`);
|
||||
|
||||
for (const g of api.groups) {
|
||||
page(`${api.root.slice(1)}/${g.id}/index.html`, `${api.name}::${g.name}`, g.title, sidebar({ group: g }),
|
||||
`${crumbs()}<h1 class="item"><span class="kind">Module</span> ${esc(api.name)}::<span class="name">${g.name}</span></h1>
|
||||
<p>${g.summary}</p>
|
||||
<h2 id="endpoints">Endpoints</h2>
|
||||
<dl class="list">${g.items.map(it => `<dt><a class="${METHOD_CLASS[it.method]}" href="${itemHref(g, it)}"><span class="verb">${it.method}</span> ${esc(it.path)}</a></dt><dd>${it.summary}</dd>`).join('')}</dl>`);
|
||||
|
||||
for (const it of g.items) {
|
||||
const decl = [
|
||||
`<span class="verb ${METHOD_CLASS[it.method]}">${it.method}</span> ${esc(it.path)}`,
|
||||
it.query && ` query ${ty(it.query)}`,
|
||||
it.body && ` body ${ty(it.body)}`,
|
||||
` -> ${isType(it.returns) ? ty(it.returns) : esc(it.returns)}`,
|
||||
].filter(Boolean).join('\n');
|
||||
const fieldsOf = n => api.types.find(t => t.name === n)?.fields || [];
|
||||
const rows = list => `<dl class="fields">${list.map(([n, t, d]) => `<dt id="${it.slug}-${n}"><code>${esc(n)}: ${ty(t)}</code></dt><dd>${d || ''}</dd>`).join('')}</dl>`;
|
||||
let body = `${crumbs([`${api.root}/${g.id}/`, g.name])}
|
||||
<h1 class="item"><span class="kind">Endpoint</span> ${esc(api.name)}::${g.name}::<span class="name fn">${fnName(it)}</span><a class="srclink" href="${SRC}/${api.name === 'ipx' ? 'crates/ipx/src/web.rs' : 'crates/directory/src/lib.rs'}">Source</a></h1>
|
||||
<pre class="decl"><code>${decl}</code></pre>
|
||||
<p class="summary">${it.summary}</p>
|
||||
${it.doc || ''}
|
||||
<p class="access">Access: <b>${esc(access(it))}</b></p>`;
|
||||
if (it.pathParams) body += `<h2>Path parameters</h2>${rows(it.pathParams)}`;
|
||||
if (it.query) body += `<h2>Query</h2><p>${ty(it.query)}, as query parameters:</p>${rows(fieldsOf(it.query))}`;
|
||||
if (it.body) body += `<h2>Body</h2><p>${ty(it.body)}, as JSON.</p>`;
|
||||
body += `<h2>Returns</h2><p>${isType(it.returns) ? `${ty(it.returns)}, as JSON.` : esc(it.returns)}</p>`;
|
||||
if (it.errors?.length) body += `<h2>Errors</h2><dl class="fields">${it.errors.map(([c, d]) => `<dt><code>${esc(c)}</code></dt><dd>${d}</dd>`).join('')}</dl>`;
|
||||
if (it.example) body += `<h2>Example</h2><pre><code>${esc(it.example)}</code></pre>`;
|
||||
page(`${api.root.slice(1)}/${g.id}/${it.slug}.html`, `${it.method} ${it.path} - ${label}`, it.summary.replace(/<[^>]+>/g, ''), sidebar({ group: g, item: it }), body);
|
||||
}
|
||||
}
|
||||
|
||||
page(`${api.root.slice(1)}/types/index.html`, `${api.name}::types`, `The types ${label}'s API takes and gives.`, sidebar(),
|
||||
`${crumbs()}<h1 class="item"><span class="kind">Module</span> ${esc(api.name)}::<span class="name">types</span></h1>
|
||||
<dl class="list">${api.types.map(t => `<dt><a class="t" href="${typeHref(t.name)}">${t.name}</a></dt><dd>${t.doc || ''}</dd>`).join('')}</dl>`);
|
||||
|
||||
for (const t of api.types) {
|
||||
const decl = t.name === 'Event'
|
||||
? `enum Event {\n${t.fields.map(([n, f]) => ` ${n} ${ty(f)},`).join('\n')}\n}`
|
||||
: t.fields.length
|
||||
? `struct ${t.name} {\n${t.fields.map(([n, f]) => ` ${n}: ${ty(f)},`).join('\n')}\n}`
|
||||
: `enum ${t.name}`;
|
||||
const uses = usedBy.get(t.name) || [];
|
||||
let body = `${crumbs([`${api.root}/types/`, 'types'])}
|
||||
<h1 class="item"><span class="kind">${t.name === 'Event' || !t.fields.length ? 'Enum' : 'Struct'}</span> ${esc(api.name)}::types::<span class="name t">${t.name}</span></h1>
|
||||
<pre class="decl"><code>${decl}</code></pre>
|
||||
${t.doc ? `<p class="summary">${t.doc}</p>` : ''}`;
|
||||
if (t.fields.length) {
|
||||
body += `<h2>${t.name === 'Event' ? 'Variants' : 'Fields'}</h2><dl class="fields">${t.fields.map(([n, f, d]) =>
|
||||
`<dt id="${n}"><a class="anchor" href="#${n}" aria-label="Link to ${esc(n)}">§</a><code>${esc(n)}${t.name === 'Event' ? ' ' : ': '}${ty(f)}</code></dt><dd>${d || ''}</dd>`).join('')}</dl>`;
|
||||
}
|
||||
if (uses.length) {
|
||||
body += `<h2>Used by</h2><ul class="uses">${uses.map(([g, x]) => g
|
||||
? `<li><a class="${METHOD_CLASS[x.method]}" href="${itemHref(g, x)}"><span class="verb">${x.method}</span> ${esc(x.path)}</a></li>`
|
||||
: `<li><a class="t" href="${typeHref(x.name)}">${x.name}</a></li>`).join('')}</ul>`;
|
||||
}
|
||||
page(`${api.root.slice(1)}/types/${t.name}.html`, `${t.name} - ${label}`, (t.doc || `${t.name} in ${label}'s API`).replace(/<[^>]+>/g, ''), sidebar({ type: t }), body);
|
||||
}
|
||||
|
||||
// Every link to a type must name one there is: a misspelt type in api.mjs is otherwise a
|
||||
// name in plain text, which looks right and leads nowhere.
|
||||
for (const g of api.groups) for (const it of g.items) for (const s of [it.body, it.query].filter(Boolean)) {
|
||||
for (const n of s.match(/\b[A-Z][A-Za-z]+\b/g)) if (!typeNames.has(n) && !['Vec', 'Option'].includes(n)) throw new Error(`${it.path}: no type ${n}`);
|
||||
}
|
||||
}
|
||||
|
||||
reference(ipx);
|
||||
reference(directory);
|
||||
22
site/guides/cli.html
Normal file
22
site/guides/cli.html
Normal file
@@ -0,0 +1,22 @@
|
||||
<h1>The command line</h1>
|
||||
<p>The same <code>ipx</code> program that runs the server is its command line. Run it in the container with <code>docker exec ipx ipx …</code>; when the server is running, it does the work and the command shows what happened.</p>
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>Command</th><th>What it does</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><code>ipx list</code></td><td>Every podcast and its state</td></tr>
|
||||
<tr><td><code>ipx status</code></td><td>How many podcasts, how many files waiting and downloaded</td></tr>
|
||||
<tr><td><code>ipx fetch [id] [--force]</code></td><td>Check everything that is due, or one podcast; <code>--force</code> checks it even if it is not due</td></tr>
|
||||
<tr><td><code>ipx add <url></code>, <code>ipx rm <id></code></td><td>Add a podcast, or take it out</td></tr>
|
||||
<tr><td><code>ipx import <file></code>, <code>ipx export <file></code></td><td>OPML in or out</td></tr>
|
||||
<tr><td><code>ipx reap [--dry-run]</code></td><td>Clear old files now, to stay within the space you set</td></tr>
|
||||
<tr><td><code>ipx user add|list|passwd|rm</code></td><td>Accounts</td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<h2>The control socket</h2>
|
||||
<p>A program on the same machine can also talk to the running server over its control socket, one JSON command a line, and read back one event a line:</p>
|
||||
<pre><code>printf '{"cmd":"fetch","force":true}\n' | socat - UNIX-CONNECT:$XDG_RUNTIME_DIR/ipx.sock
|
||||
{"ev":"feed_start","feed":"atp"}
|
||||
{"ev":"download_done","feed":"atp","enclosure":42,"path":"…","bytes":3000000}
|
||||
{"ev":"feed_done","feed":"atp","new":1,"downloaded":1,"failed":0,"torrents":0}
|
||||
{"ev":"scan_done","feeds":1}</code></pre>
|
||||
<p>The commands are <code>fetch</code> (optional <code>feed</code>, <code>force</code>), <code>download</code> (<code>enclosure</code>), <code>reap</code> (optional <code>dry_run</code>) and <code>status</code>.</p>
|
||||
32
site/guides/directory.html
Normal file
32
site/guides/directory.html
Normal file
@@ -0,0 +1,32 @@
|
||||
<h1>The directory</h1>
|
||||
<p>The directory gathers the public podcasts that iPX servers' listeners follow, and how many follow each. It never holds a file and never learns who listens.</p>
|
||||
|
||||
<h2>Browsing it</h2>
|
||||
<p>Anyone can browse <a href="https://directory.ipxreader.app">directory.ipxreader.app</a> without signing in: the most followed, the categories, everything A to Z, and a page for each podcast with its latest episodes and its address, to subscribe to in any podcast app.</p>
|
||||
|
||||
<h2>Connecting your iPX</h2>
|
||||
<p>In iPX, an admin opens Admin, Directory and enters the directory's address, <code>https://directory.ipxreader.app</code>, and the token its operator gave your server. Everyone on your server then has the Directory at the top of their list, and subscribes from it in one click.</p>
|
||||
<p>Turn on sharing to add your server's podcasts to it. iPX sends only the podcasts' addresses and how many people on your server follow each, never who. It leaves out anything that looks private: a podcast someone marked Private, one with a login or a key in its address, and paid feeds such as Patreon's.</p>
|
||||
|
||||
<h2>Its API</h2>
|
||||
<p>Anything the pages show, a program can read through the directory's API with a token: see the <a href="/docs/api/directory/">ipx-directory API reference</a>.</p>
|
||||
|
||||
<h2>Running your own</h2>
|
||||
<p>The directory is in the same repository. Build it, give it a database (Postgres or SQLite) and a config file, and make a token for each server that will use it:</p>
|
||||
<pre><code>docker build -f Dockerfile.directory -t ipx-directory .</code></pre>
|
||||
<pre><code>services:
|
||||
ipx-directory:
|
||||
image: ipx-directory
|
||||
container_name: ipx-directory
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
DIRECTORY_DATABASE_URL: "postgres://ipx_directory:password@db-host:5432/ipx_directory"
|
||||
ports:
|
||||
- "8100:8100"
|
||||
volumes:
|
||||
- ./directory:/config:ro # directory.toml</code></pre>
|
||||
<pre><code># directory/directory.toml
|
||||
bind = "0.0.0.0:8100"
|
||||
database_url_env = "DIRECTORY_DATABASE_URL"</code></pre>
|
||||
<pre><code>docker exec ipx-directory ipx-directory token new my-server --access rw</code></pre>
|
||||
<p>That prints the token, to give to the server, and the lines to add to <code>directory.toml</code>, which keeps only its SHA-256. The directory reads the file again within a minute, so adding or revoking a token needs no restart. It checks each podcast every six hours.</p>
|
||||
67
site/guides/install.html
Normal file
67
site/guides/install.html
Normal file
@@ -0,0 +1,67 @@
|
||||
<h1>Install ipx and ipx-web</h1>
|
||||
<p class="lede">iPX is two containers: <strong>ipx</strong>, which checks your podcasts, downloads them and answers the API, and <strong>ipx-web</strong>, which serves the page and passes the API on to ipx.</p>
|
||||
<p>You need Docker with Compose. There are no published images yet, so you build both from the source:</p>
|
||||
<pre><code>git clone https://git.sdf1.net/rays/ipx.git
|
||||
cd ipx
|
||||
docker build -t ipx .
|
||||
docker build -f Dockerfile.web -t ipx-web .</code></pre>
|
||||
<p>The repository has a sample <code>docker-compose.yml</code> that runs both, with the database in SQLite and everything ipx keeps in three folders beside the file:</p>
|
||||
<pre><code>services:
|
||||
ipx:
|
||||
image: ipx
|
||||
container_name: ipx
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
PUID: "99" # who owns the files it writes
|
||||
PGID: "100"
|
||||
TZ: "UTC"
|
||||
ports:
|
||||
- "6881:6881/tcp" # BitTorrent
|
||||
- "6881:6881/udp"
|
||||
volumes:
|
||||
- ./config:/config # config.toml, written on first start
|
||||
- ./data:/data # the database
|
||||
- ./downloads:/downloads
|
||||
|
||||
ipx-web:
|
||||
image: ipx-web
|
||||
container_name: ipx-web
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
IPX_UPSTREAM: "ipx:8099"
|
||||
ports:
|
||||
- "8099:8080" # the page
|
||||
depends_on:
|
||||
- ipx</code></pre>
|
||||
<pre><code>docker compose up -d</code></pre>
|
||||
<p>ipx has no port of its own: everything reaches it through ipx-web, on port 8099. Open <code>http://<your server>:8099</code> and sign in as <strong>admin</strong> with the password <strong>ipodderx</strong>, then change it:</p>
|
||||
<pre><code>echo -n 'a good password' | docker exec -i ipx ipx user passwd admin</code></pre>
|
||||
<p>The password is read from what you pipe in, so it stays out of your shell's history.</p>
|
||||
|
||||
<h2>Adding people</h2>
|
||||
<p>An admin adds people in Admin, Accounts, or from the command line:</p>
|
||||
<pre><code>echo -n 'their password' | docker exec -i ipx ipx user add sam</code></pre>
|
||||
<p>Each person starts with no podcasts and subscribes to their own. Two people subscribing to the same show cost nothing extra: it is fetched once and each file is kept once.</p>
|
||||
|
||||
<h2>Settings</h2>
|
||||
<p>How often podcasts are checked, how much disk to use, how many new episodes to download and the rest are in Admin on the page, and take effect straight away. <code>/config/config.toml</code> holds only what ipx needs before it can read its database: where downloads go, BitTorrent, and who gets in.</p>
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>Environment variable</th><th>What it does</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><code>IPX_DATABASE_URL</code></td><td>A <code>postgres://user:password@host:5432/database</code> address, to keep everything in Postgres instead of SQLite</td></tr>
|
||||
<tr><td><code>PUID</code>, <code>PGID</code></td><td>The user and group that own the files ipx writes</td></tr>
|
||||
<tr><td><code>IPX_LOG_FORMAT</code></td><td><code>json</code> logs one JSON object a line, for Loki and the like</td></tr>
|
||||
<tr><td><code>OTEL_EXPORTER_OTLP_ENDPOINT</code></td><td>Sends traces of requests, checks and downloads to an OpenTelemetry collector; set <code>WEB_TRACING=on</code> on ipx-web too</td></tr>
|
||||
<tr><td><code>IPX_UPSTREAM</code></td><td>On ipx-web: where ipx is, <code>ipx:8099</code> by default</td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
|
||||
<h2>Reaching it from outside</h2>
|
||||
<p>The page is plain HTTP. If anyone will reach it from outside your network, put HTTPS in front of it: a reverse proxy you already run, or a Cloudflare tunnel. People can then sign in through Cloudflare Access or Authentik instead of a password; <a href="https://git.sdf1.net/rays/ipx/src/branch/main/docs/sso.md">single sign-on</a> says how.</p>
|
||||
|
||||
<h2>Updating</h2>
|
||||
<pre><code>git pull
|
||||
docker build -t ipx .
|
||||
docker build -f Dockerfile.web -t ipx-web .
|
||||
docker compose up -d</code></pre>
|
||||
<p>Your podcasts, accounts and downloads are in the three folders and are kept.</p>
|
||||
@@ -14,6 +14,7 @@
|
||||
<header class="bar">
|
||||
<a class="home" href="/"><img src="/logo.svg" alt="" width="36" height="36">iPX</a>
|
||||
<nav aria-label="Elsewhere">
|
||||
<a href="/docs/">Docs</a>
|
||||
<a href="https://directory.ipxreader.app">Directory</a>
|
||||
<a class="src" href="https://git.sdf1.net/rays/ipx" title="Source code on git.sdf1.net"><img src="/gitea.svg" alt="Source code" width="28" height="28"></a>
|
||||
</nav>
|
||||
|
||||
@@ -90,6 +90,84 @@ h2{margin:0 0 1.5rem;color:var(--navy);font-weight:800;font-size:clamp(1.75rem,4
|
||||
.also dd{margin:.45rem 0 0;max-width:34rem}
|
||||
|
||||
|
||||
/* Docs (#223): a sidebar and a column, as docs.rs lays out a crate. The sidebar is the dial's
|
||||
sky; an endpoint's name is the scale's blue, a type's green, and each method has its own
|
||||
colour, every one AA on the page. Code to read is dark, as on the home page; a declaration is
|
||||
light, as docs.rs shows one. On a phone the sidebar follows the page instead of leading it. */
|
||||
.docs{max-width:72rem;margin:0 auto;padding-inline:1.5rem;display:grid;grid-template-columns:15rem minmax(0,1fr);gap:3rem;align-items:start}
|
||||
.docs main.doc{max-width:50rem;margin:0;padding:0}
|
||||
.side{position:sticky;top:1rem;max-height:calc(100vh - 2rem);overflow:auto;padding:1rem .75rem;background:var(--sky);border-radius:1rem;font-size:.92rem}
|
||||
.side ul{list-style:none;margin:0;padding:0}
|
||||
.side li a{display:block;padding:.2rem .5rem;border-radius:.4rem;color:var(--ink);text-decoration:none;overflow-wrap:anywhere}
|
||||
.side li a:hover{background:#fff}
|
||||
.side a[aria-current=page]{background:#fff;font-weight:700}
|
||||
.side-h{margin:1.1rem .5rem .35rem;color:var(--muted);font-size:.78rem;font-weight:700;letter-spacing:.06em;text-transform:uppercase}
|
||||
.side-h a{color:inherit}
|
||||
.side-back{margin:1rem .5rem 0}
|
||||
.crate{display:flex;align-items:center;gap:.6rem;padding:.25rem .5rem;color:var(--navy);text-decoration:none}
|
||||
.crate img{border-radius:9px}
|
||||
.crate b{display:block;font-size:1.1rem}
|
||||
.ver{color:var(--muted);font-size:.85rem;font-weight:500}
|
||||
.mono,.items a,.uses a,.list dt,.path,.decl,.fields dt,.item .name{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
||||
.items a,.uses a{font-size:.82rem}
|
||||
.items .verb{display:inline-block;min-width:3.6em}
|
||||
.verb{font-weight:700}
|
||||
.m-get .verb,.verb.m-get{color:#2f6aa0}
|
||||
.m-post .verb,.verb.m-post{color:#1d6b44}
|
||||
.m-patch .verb,.verb.m-patch{color:#875400}
|
||||
.m-delete .verb,.verb.m-delete{color:#b3261e}
|
||||
a.t,.item .name.t{color:#1d6b44}
|
||||
|
||||
.doc h1{margin:2rem 0 0;color:var(--navy);font-weight:900;font-size:clamp(2.6rem,8vw,4rem);line-height:1;letter-spacing:-.04em}
|
||||
.doc h1.item{margin-top:.25rem;font-size:clamp(1.35rem,4vw,1.85rem);font-weight:500;letter-spacing:-.01em;line-height:1.3;overflow-wrap:anywhere}
|
||||
.item .kind{font-family:Inter,system-ui,sans-serif;color:var(--muted)}
|
||||
.item .name{font-weight:700;color:var(--scale)}
|
||||
.srclink{float:right;margin-left:1rem;font:500 .9rem/2.4 Inter,system-ui,sans-serif}
|
||||
.path{margin:2rem 0 0;font-size:.9rem;color:var(--muted)}
|
||||
.path a{color:inherit}
|
||||
.lede{margin:1.5rem 0 0;color:var(--muted);font-size:1.125rem}
|
||||
.doc h2{margin:2.5rem 0 .75rem;padding-bottom:.35rem;border-bottom:1px solid var(--rule);font-size:1.35rem;letter-spacing:-.01em}
|
||||
.doc p{margin:.75rem 0}
|
||||
.summary{font-size:1.06rem}
|
||||
.access{color:var(--muted)}
|
||||
.access b{color:var(--ink)}
|
||||
.doc code{font:500 .9em/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
||||
.doc :not(pre)>code{padding:.08em .3em;background:var(--sky);border-radius:.3em;overflow-wrap:anywhere}
|
||||
.doc dt>code,.doc a>code{background:none;padding:0}
|
||||
.doc pre{margin:1rem 0;padding:1rem 1.15rem;background:var(--navy);color:#e6f1fa;border-radius:.8rem;overflow-x:auto}
|
||||
.doc pre code{font-size:.85rem}
|
||||
.doc pre.decl{background:#fff;color:var(--ink);border:1px solid var(--rule)}
|
||||
.decl a{text-decoration:none}
|
||||
.scroll{margin:1rem 0;overflow-x:auto}
|
||||
.doc table{width:100%;border-collapse:collapse;font-size:.95rem}
|
||||
.doc th,.doc td{padding:.55rem .75rem .55rem 0;border-bottom:1px solid var(--rule);text-align:left;vertical-align:top}
|
||||
.doc th{color:var(--navy);font-weight:700}
|
||||
.doc td:first-child code{white-space:nowrap}
|
||||
/* An item table: the name, and the first line of what it is. */
|
||||
.list{display:grid;grid-template-columns:minmax(0,max-content) minmax(0,1fr);gap:.4rem 1.5rem;margin:0}
|
||||
.list dt{font-size:.88rem;overflow-wrap:anywhere}
|
||||
.list dt a{text-decoration:none}
|
||||
.list dt a:hover{text-decoration:underline}
|
||||
.list dd{margin:0}
|
||||
.fields dt{position:relative;margin-top:1rem;font-size:.92rem;overflow-wrap:anywhere}
|
||||
.fields dd{margin:.25rem 0 0 1.5rem}
|
||||
.anchor{position:absolute;left:-1.1rem;color:var(--muted);text-decoration:none;opacity:0}
|
||||
.fields dt:hover .anchor,.anchor:focus-visible{opacity:1}
|
||||
.uses{padding-left:1.25rem}
|
||||
.cards{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem;margin:2rem 0 0}
|
||||
.cards div{padding:1.1rem 1.25rem;background:#fff;border:1px solid var(--rule);border-radius:1rem}
|
||||
.cards dt{font-weight:750;font-size:1.1rem}
|
||||
.cards dd{margin:.35rem 0 0;color:var(--muted)}
|
||||
.bar nav a[aria-current]{text-decoration:underline;text-decoration-color:var(--needle);text-decoration-thickness:2px}
|
||||
@media (max-width:800px){
|
||||
.docs{grid-template-columns:minmax(0,1fr);gap:2rem;padding-inline:1rem}
|
||||
.side{position:static;max-height:none;order:2}
|
||||
.srclink{float:none;display:block;margin:0;line-height:1.8}
|
||||
.list{grid-template-columns:minmax(0,1fr);gap:.15rem}
|
||||
.list dd{margin-bottom:.6rem}
|
||||
.cards{grid-template-columns:minmax(0,1fr)}
|
||||
}
|
||||
|
||||
footer{margin-top:5rem;padding-block:1.75rem 3rem;border-top:1px solid var(--rule);color:var(--muted);font-size:.95rem}
|
||||
footer p{margin:0}
|
||||
|
||||
|
||||
@@ -8,8 +8,7 @@
|
||||
// It builds a release binary (debug Argon2 alone takes a second a sign-in, which would measure
|
||||
// the build, not ipx), serves generated feeds from this process, starts a daemon on its own
|
||||
// config and data under /tmp/ipx-load, wiped first, seeds listeners, then runs each k6 script.
|
||||
// While each runs, `ipx status` -- the Docker healthcheck -- is run every second, and the run
|
||||
// fails if any answer takes as long as the healthcheck's 5s timeout.
|
||||
// While each runs, `ipx status` is run every second, and the run fails if any answer takes 5s.
|
||||
//
|
||||
// The daemon is on SQLite unless --postgres, which puts it in IPX_TEST_DATABASE_URL, the
|
||||
// database the Rust tests use on Postgres too (ipodderx_test on the server production's is on, in
|
||||
|
||||
@@ -68,6 +68,18 @@ for (const [name, fn] of drive) {
|
||||
}
|
||||
}
|
||||
|
||||
// A trace is one tap's (#219): the same id while requests keep coming, a new one after a quiet
|
||||
// minute, so a refresh hours later is not filed under the last tap.
|
||||
if (PAGE === 'index.html') {
|
||||
const id = () => ctx.traceparent().split('-')[1];
|
||||
vm.runInContext('Date.now = (n => () => n)(1e12)', ctx);
|
||||
const first = id();
|
||||
vm.runInContext('Date.now = (n => () => n)(1e12 + 30_000)', ctx);
|
||||
if (id() !== first) { console.error('FAIL: a trace ended 30 s into a tap'); process.exit(1); }
|
||||
vm.runInContext('Date.now = (n => () => n)(1e12 + 120_000)', ctx);
|
||||
if (id() === first) { console.error('FAIL: a trace outlived a quiet minute'); process.exit(1); }
|
||||
}
|
||||
|
||||
// theme.ts keeps the Settings theme controls in step when Settings is open, and looks before it
|
||||
// touches them. The admin page has no Settings, so those are the ones it may ask for and not find.
|
||||
const OPTIONAL = new Set(['#stheme', '#smode', '#smodefield']);
|
||||
|
||||
132
tests/page-unit.js
Normal file
132
tests/page-unit.js
Normal file
@@ -0,0 +1,132 @@
|
||||
// Unit tests for the page's own functions (#234): the script as shipped, loaded into the stub DOM
|
||||
// page-smoke.js uses, and its helpers called directly. The browser suite tests what people do;
|
||||
// this tests the small pieces it is made of, in a second, with nothing running.
|
||||
//
|
||||
// node --test tests/page-unit.js
|
||||
//
|
||||
// The files in web/src are one script, not modules. Its top-level `function`s are properties of
|
||||
// the context; its top-level `const`s are not, but a script run in the same context sees them, as
|
||||
// a second <script> on a page would, so `run` evaluates an expression there.
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { makeContext, vm } = require('./dom-stub.js');
|
||||
const { buildPage } = require('../web/build.mjs');
|
||||
|
||||
const { html, js } = buildPage('index.html');
|
||||
const { ctx } = makeContext(html, js);
|
||||
vm.createContext(ctx);
|
||||
vm.runInContext(js, ctx, { filename: 'index.html<script>', timeout: 5000 });
|
||||
const run = expr => vm.runInContext(expr, ctx);
|
||||
// Time as the page sees it, for the helpers that count from now.
|
||||
const NOW = 1_800_000_000;
|
||||
run(`Date.now = () => ${NOW * 1000}`);
|
||||
|
||||
test('esc makes text safe to put in markup and attributes', () => {
|
||||
assert.equal(run(`esc('<a href="x">Tom & Jerry\\'s</a>')`), '<a href="x">Tom & Jerry's</a>');
|
||||
assert.equal(run('esc(null)'), '');
|
||||
assert.equal(run('esc(undefined)'), '');
|
||||
});
|
||||
|
||||
test('clock reads seconds as a player does', () => {
|
||||
assert.equal(run('clock(0)'), '0:00');
|
||||
assert.equal(run('clock(65)'), '1:05');
|
||||
assert.equal(run('clock(3661)'), '1:01:01');
|
||||
assert.equal(run('clock(59.9)'), '0:59');
|
||||
assert.equal(run('clock(-5)'), '0:00');
|
||||
assert.equal(run('clock(undefined)'), '0:00');
|
||||
});
|
||||
|
||||
test('mb sizes a file in the unit that reads best', () => {
|
||||
assert.equal(run('mb(0)'), '');
|
||||
// An article's small image is not "0 KB" or "0 MB".
|
||||
assert.equal(run('mb(100)'), '1 KB');
|
||||
assert.equal(run('mb(2048)'), '2 KB');
|
||||
assert.equal(run('mb(5 * 1048576)'), '5 MB');
|
||||
assert.equal(run('mb(1.5 * 1073741824)'), '1.5 GB');
|
||||
});
|
||||
|
||||
test('ago says how long since, and never for nothing', () => {
|
||||
assert.equal(run('ago(0)'), 'never');
|
||||
assert.equal(run(`ago(${NOW - 10})`), '1m ago');
|
||||
assert.equal(run(`ago(${NOW - 45 * 60})`), '45m ago');
|
||||
assert.equal(run(`ago(${NOW - 5 * 3600})`), '5h ago');
|
||||
assert.equal(run(`ago(${NOW - 3 * 86400})`), '3d ago');
|
||||
// Past a month, a date: whatever the locale, it names the year.
|
||||
assert.match(run(`ago(${NOW - 90 * 86400})`), /2026/);
|
||||
});
|
||||
|
||||
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');
|
||||
assert.equal(run(`due(${NOW + 90 * 60})`), 'in 2h');
|
||||
assert.equal(run(`due(${NOW + 3 * 86400})`), 'in 3d');
|
||||
});
|
||||
|
||||
test('DeadAir savings read as time', () => {
|
||||
assert.equal(run('spanText(40)'), '40 s');
|
||||
assert.equal(run('spanText(12 * 60 + 5)'), '12 min');
|
||||
assert.equal(run('spanText(3 * 3600 + 12 * 60)'), '3 h 12 min');
|
||||
assert.equal(run('shorter(45)'), '45 s shorter');
|
||||
assert.equal(run('shorter(150)'), '3 min shorter');
|
||||
});
|
||||
|
||||
test('initials and plural', () => {
|
||||
assert.equal(run(`initials('The Verge')`), 'TV');
|
||||
assert.equal(run(`initials('accidental tech podcast')`), 'AT');
|
||||
assert.equal(run(`initials('')`), '?');
|
||||
assert.equal(run(`initials('!!!')`), '?');
|
||||
assert.equal(run(`plural(1, 'feed')`), '1 feed');
|
||||
assert.equal(run(`plural(0, 'feed')`), '0 feeds');
|
||||
assert.equal(run(`plural(2, 'feed')`), '2 feeds');
|
||||
});
|
||||
|
||||
test("kindOf names a file by its type, or else its address's extension", () => {
|
||||
const kind = enc => run(`kindOf(${JSON.stringify(enc)})`);
|
||||
assert.equal(kind({ mime: 'image/png' }), 'image');
|
||||
assert.equal(kind({ mime: 'Video/MP4' }), 'video');
|
||||
assert.equal(kind({ mime: 'audio/mpeg' }), 'audio');
|
||||
assert.equal(kind({ mime: 'application/pdf' }), 'pdf');
|
||||
assert.equal(kind({ mime: 'application/x-bittorrent' }), 'torrent');
|
||||
assert.equal(kind({ url: 'https://x/ep.MP3?token=1' }), 'mp3');
|
||||
assert.equal(kind({ url: 'https://x/download' }), 'file');
|
||||
assert.equal(kind({ url: 'https://x/a.toolongext' }), 'file');
|
||||
assert.equal(kind({}), 'file');
|
||||
});
|
||||
|
||||
test('an item without a title is named by its file', () => {
|
||||
const name = e => run(`entryName(${JSON.stringify(e)})`);
|
||||
assert.deepEqual({ ...name({ title: 'Episode 1' }) }, { text: 'Episode 1', derived: false });
|
||||
assert.deepEqual({ ...name({ title: ' ', enclosures: [{ url: 'https://x/My%20Show%20101.mp3?x=1' }] }) },
|
||||
{ text: 'My Show 101', derived: true });
|
||||
// A name that does not decode is shown as it is, not dropped.
|
||||
assert.deepEqual({ ...name({ enclosures: [{ url: 'https://x/100%.mp3' }] }) }, { text: '100%', derived: true });
|
||||
});
|
||||
|
||||
test('the directory sorts by name as people read, and by subscribers', () => {
|
||||
const sorted = (list, by) => 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']);
|
||||
assert.deepEqual([...sorted([{ title: 'B', subscribers: 1 }, { title: 'C', subscribers: 5 }, { title: 'A', subscribers: 1 }], 'bySubs')],
|
||||
['C', 'A', 'B']);
|
||||
});
|
||||
|
||||
test('feeds with something unread go first, in the order they came', () => {
|
||||
const ids = run(`[{id:'a',unread:0},{id:'b',unread:3},{id:'c',unread:0},{id:'d',unread:1}].sort(unreadFirst).map(f => f.id)`);
|
||||
assert.deepEqual([...ids], ['b', 'd', 'a', 'c']);
|
||||
});
|
||||
|
||||
test('words for filters split on commas, blanks dropped', () => {
|
||||
assert.deepEqual([...run(`splitWords(' one, two words ,, three ')`)], ['one', 'two words', 'three']);
|
||||
assert.deepEqual([...run(`splitWords('')`)], []);
|
||||
});
|
||||
|
||||
test("a file plays from DeadAir's playlist when it has one", () => {
|
||||
assert.equal(run(`mediaSrc({ id: 7, deadair: null })`), '/media/7');
|
||||
assert.equal(run(`mediaSrc({ id: 7 })`), '/media/7');
|
||||
assert.equal(run(`mediaSrc({ id: 7, deadair: 0 })`), '/media/7/deadair.m3u8');
|
||||
});
|
||||
|
||||
test('a Patreon feed is told by its address', () => {
|
||||
assert.equal(run(`isPatreon({ url: 'https://www.patreon.com/rss/show?auth=x' })`), true);
|
||||
assert.equal(run(`isPatreon({ url: 'https://example.com/feed' })`), false);
|
||||
assert.equal(run('isPatreon(null)'), false);
|
||||
});
|
||||
@@ -1697,15 +1697,30 @@ test('a pinned feed, even one from inside a folder, goes to the top of the list'
|
||||
test('a feed being checked shows a spinner on its row, and no toast', async ({ page }) => {
|
||||
const row = page.locator('#feedlist .feed', { hasText: 'Test Show' });
|
||||
await expect(row).toBeVisible();
|
||||
await page.evaluate(() => setScanning('test-show', true));
|
||||
// A check of a few milliseconds leaves the count where it is, or every count blinked as a scan
|
||||
// went by; the spinner comes once the check has taken a moment (#232).
|
||||
const atOnce = await page.evaluate(() => {
|
||||
setScanning('test-show', true);
|
||||
return document.querySelector('#feedlist .feed[data-id="test-show"]').classList.contains('scanning');
|
||||
});
|
||||
expect(atOnce, 'no spinner the moment a check starts').toBe(false);
|
||||
await expect(row).toHaveClass(/\bscanning\b/);
|
||||
await expect(row.locator('.badge'), 'the spinner stands in for the count').toBeHidden();
|
||||
await page.evaluate(() => setScanning('test-show', false));
|
||||
await expect(row).not.toHaveClass(/\bscanning\b/);
|
||||
await expect(row.locator('.badge')).toBeVisible();
|
||||
// The button turns from the press to the end of the scan it asked for (#233): a scheduled
|
||||
// scan's end, or the end of a scan of one other feed, leaves it turning.
|
||||
const spins = () => document.body.classList.contains('scan-any');
|
||||
expect(await page.evaluate(spins => { spinStart(null); spinEnd({ only: null, forced: false });
|
||||
const a = document.body.classList.contains('scan-any'); spinEnd({ only: 'test-show', forced: true });
|
||||
return a && document.body.classList.contains('scan-any'); })).toBe(true);
|
||||
await page.evaluate(() => spinEnd({ only: null, forced: true }));
|
||||
expect(await page.evaluate(spins)).toBe(false);
|
||||
// Checking every feed says so on the rows, not in a toast (issue #37).
|
||||
await page.locator('#scanAll').click();
|
||||
await page.waitForTimeout(1500);
|
||||
expect(await page.evaluate(() => { scanAll(); return document.body.classList.contains('scan-any'); }),
|
||||
'turning the moment it is pressed').toBe(true);
|
||||
await expect(page.locator('body')).not.toHaveClass(/\bscan-any\b/, { timeout: 15_000 });
|
||||
await expect(page.locator('.toast', { hasText: /Scanning|Checking| new/ })).toHaveCount(0);
|
||||
});
|
||||
|
||||
@@ -1766,20 +1781,28 @@ test('Share hands the feed, the item and the file to the share sheet', async ({
|
||||
]);
|
||||
});
|
||||
|
||||
test('a refresh button turns while what it checks is being checked', async ({ page }) => {
|
||||
test('a refresh button turns from the press to the end of the scan it asked for', async ({ page }) => {
|
||||
await page.locator('.feed', { hasText: 'Test Show' }).click();
|
||||
const spin = sel => page.locator(sel).evaluate(el => getComputedStyle(el).animationName);
|
||||
const btn = '.fhead [data-a=scan] .i';
|
||||
await expect(page.locator(btn)).toBeVisible();
|
||||
expect(await spin(btn)).toBe('none');
|
||||
await page.evaluate(() => setScanning('test-show', true));
|
||||
// Pressed: this feed's button turns, the toolbar's does not (#78, #233).
|
||||
await page.evaluate(() => spinStart('test-show'));
|
||||
expect(await spin(btn)).toBe('ipxspin');
|
||||
expect(await spin('#scanAll .i')).toBe('ipxspin');
|
||||
// Another feed being checked turns the toolbar's, not this page's.
|
||||
await page.evaluate(() => { setScanning('test-show', false); setScanning('multi-show', true); });
|
||||
expect(await spin('#scanAll .i')).toBe('none');
|
||||
// Feeds being checked one by one no longer start or stop it (#231).
|
||||
await page.evaluate(() => { setScanning('test-show', true); setScanning('test-show', false); });
|
||||
expect(await spin(btn)).toBe('ipxspin');
|
||||
// Another feed's scan ending, or a scheduled one's, leaves it turning; its own stops it.
|
||||
await page.evaluate(() => { spinEnd({ only: 'multi-show', forced: true }); spinEnd({ only: null, forced: false }); });
|
||||
expect(await spin(btn)).toBe('ipxspin');
|
||||
await page.evaluate(() => spinEnd({ only: 'test-show', forced: true }));
|
||||
expect(await spin(btn)).toBe('none');
|
||||
// The toolbar's turns for a scan of every feed, until that scan ends.
|
||||
await page.evaluate(() => spinStart(null));
|
||||
expect(await spin('#scanAll .i')).toBe('ipxspin');
|
||||
await page.evaluate(() => setScanning('multi-show', false));
|
||||
await page.evaluate(() => spinEnd({ only: null, forced: true }));
|
||||
expect(await spin('#scanAll .i')).toBe('none');
|
||||
});
|
||||
|
||||
@@ -1913,6 +1936,36 @@ test('DeadAir is off until turned on for a show, then plays it shortened, with y
|
||||
await page.locator('#ssave').click();
|
||||
await expect.poll(async () => (await entry()).enclosures[0].deadair).toBeLessThan(usual);
|
||||
|
||||
// Someone else on the same show at the usual pause, at the same address at the same time: one
|
||||
// file on disk, a playlist each, and neither kept by a cache to be handed to the other.
|
||||
{
|
||||
const { execFileSync } = require('child_process');
|
||||
const setup = require('./global-setup');
|
||||
const env = { ...process.env, IPX_CONFIG: `${setup.root}/config/config.toml`, IPX_DATA_DIR: `${setup.root}/data` };
|
||||
try { execFileSync('./target/debug/ipx', ['user', 'add', 'quinn'], { input: 'quinnpassword', env }); }
|
||||
catch (e) { if (!String(e.stderr || e.stdout).includes('already exists')) throw e; }
|
||||
const ctx = await page.context().browser().newContext();
|
||||
const quinn = await ctx.newPage();
|
||||
await quinn.goto('/login');
|
||||
await quinn.locator('#name').fill('quinn');
|
||||
await quinn.locator('#pw').fill('quinnpassword');
|
||||
await quinn.locator('button[type=submit]').click();
|
||||
await expect(quinn.locator('#feedlist')).toBeVisible();
|
||||
await quinn.request.post('/api/feeds', { data: { url: 'http://127.0.0.1:8792/quiet.xml' } });
|
||||
await quinn.request.patch(`/api/feeds/${encodeURIComponent(id)}`, { data: { deadair: true } });
|
||||
const enc = (await entry()).enclosures[0].id;
|
||||
const fetchList = async p => { const r = await p.request.get(`/media/${enc}/deadair.m3u8`);
|
||||
return { status: r.status(), cache: r.headers()['cache-control'], body: await r.text() }; };
|
||||
const [mine, theirs] = await Promise.all([fetchList(page), fetchList(quinn)]);
|
||||
const length = l => l.body.match(/#EXTINF:([\d.]+)/g).reduce((s, x) => s + Number(x.slice(8)), 0);
|
||||
expect([mine.status, theirs.status]).toEqual([200, 200]);
|
||||
expect([mine.cache, theirs.cache]).toEqual(['no-store', 'no-store']);
|
||||
expect(mine.body).not.toBe(theirs.body);
|
||||
expect(length(theirs), 'the usual pause cuts more than the longer one').toBeLessThan(length(mine));
|
||||
await quinn.request.delete(`/api/feeds/${encodeURIComponent(id)}`);
|
||||
await ctx.close();
|
||||
}
|
||||
|
||||
// Saved without its dead air too (#186): smaller than the original, named to say so.
|
||||
const saved = await page.evaluate(async id => {
|
||||
const [d, o, p] = await Promise.all([fetch(`/media/${id}/deadair`), fetch(`/media/${id}`), fetch(`/media/${id}/deadair.mp3`, { headers: { Range: 'bytes=0-99' } })]);
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
"target": "es2022",
|
||||
"lib": ["es2022", "dom", "dom.iterable"],
|
||||
"noEmit": true,
|
||||
"strict": false,
|
||||
// Strict throughout (#235, #236). $ assumes the element is there: the page check proves the
|
||||
// ones wired at load exist, and a lookup that may find nothing says so with ?.
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["web/src/*.ts"]
|
||||
|
||||
@@ -11,6 +11,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.0.2] - 2026-10-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- The refresh buttons turn from the moment they are pressed until the scan they asked for has finished, smoothly, instead of jerking back upright between one feed and the next (#231, #233).
|
||||
- A feed's unread count stays put while a scan checks it quickly; the spinner takes its place only when a check takes a moment (#232).
|
||||
|
||||
### Security
|
||||
|
||||
- The ipx-web image no longer carries curl, which Caddy's base image shipped and nothing used: 8.22.0 there is affected by CVE-2026-92392 (#237).
|
||||
|
||||
## [1.0.1] - 2026-10-13
|
||||
|
||||
### Fixed
|
||||
|
||||
- A live update or a list refresh that fails because the network is gone (a laptop asleep) is no longer reported as an error, an error page from Cloudflare no longer becomes a request's message, and requests a minute or more after a tap start a trace of their own instead of joining that tap's (#219).
|
||||
|
||||
## [1.0.0] - 2026-10-12
|
||||
|
||||
### Added
|
||||
@@ -32,5 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
- On a phone, the Subscribe button on a Directory feed's page is full size again, not squashed to a sliver (#212).
|
||||
|
||||
[unreleased]: https://git.sdf1.net/rays/ipx/compare/web-v1.0.0...main
|
||||
[unreleased]: https://git.sdf1.net/rays/ipx/compare/web-v1.0.2...main
|
||||
[1.0.2]: https://git.sdf1.net/rays/ipx/compare/web-v1.0.1...web-v1.0.2
|
||||
[1.0.1]: https://git.sdf1.net/rays/ipx/compare/web-v1.0.0...web-v1.0.1
|
||||
[1.0.0]: https://git.sdf1.net/rays/ipx/releases/tag/web-v1.0.0
|
||||
|
||||
@@ -56,17 +56,17 @@ async function drawServer(){
|
||||
<div class="field"><label>Download folder</label>
|
||||
<span class="hint" style="overflow-wrap:anywhere">${esc(g.download_dir)}</span></div>
|
||||
<div class="cardacts"><button class="btn primary" id="gsave">${ICON.check} Save</button></div>`;
|
||||
$('#gsave').onclick = async () => {
|
||||
$<HTMLButtonElement>('#gsave').onclick = async () => {
|
||||
try{
|
||||
await api('/api/settings', {method: 'PATCH', body: JSON.stringify({
|
||||
schedule: `every ${Math.max(1, Number($('#gnum').value) || 1)}${$('#gunit').value}`,
|
||||
max_new_per_check: Math.max(0, Number($('#gmax').value) || 0),
|
||||
media_types: $('#gtypes').value.split(',').map(t => t.trim()).filter(Boolean),
|
||||
max_total_gb: Number($('#gquota').value) || 0,
|
||||
max_age_days: Number($('#gage').value) || 0,
|
||||
art_cache_mb: Math.max(0, Number($('#gart').value) || 0)})});
|
||||
schedule: `every ${Math.max(1, Number($<HTMLInputElement>('#gnum').value) || 1)}${$<HTMLSelectElement>('#gunit').value}`,
|
||||
max_new_per_check: Math.max(0, Number($<HTMLInputElement>('#gmax').value) || 0),
|
||||
media_types: $<HTMLInputElement>('#gtypes').value.split(',').map((t: string) => t.trim()).filter(Boolean),
|
||||
max_total_gb: Number($<HTMLInputElement>('#gquota').value) || 0,
|
||||
max_age_days: Number($<HTMLInputElement>('#gage').value) || 0,
|
||||
art_cache_mb: Math.max(0, Number($<HTMLInputElement>('#gart').value) || 0)})});
|
||||
toast('Settings saved');
|
||||
}catch(e){ toast(e.message, true); }
|
||||
}catch(e){ toast(why(e), true); }
|
||||
};
|
||||
}
|
||||
|
||||
@@ -99,15 +99,15 @@ async function drawDirectorySettings(){
|
||||
await api('/api/settings', {method: 'PATCH', body: JSON.stringify(patch)});
|
||||
toast(said);
|
||||
drawDirectorySettings();
|
||||
}catch(e){ toast(e.message, true); }
|
||||
}catch(e){ toast(why(e), true); }
|
||||
};
|
||||
$('#dsave').onclick = () => {
|
||||
const patch: Record<string, unknown> = {directory_url: $('#durl').value.trim(), directory_share: $('#dshare').checked};
|
||||
$<HTMLButtonElement>('#dsave').onclick = () => {
|
||||
const patch: Record<string, unknown> = {directory_url: $<HTMLInputElement>('#durl').value.trim(), directory_share: $<HTMLInputElement>('#dshare').checked};
|
||||
// Blank leaves the token as it is; Clear is the way to remove it.
|
||||
if($('#dtoken').value.trim()) patch.directory_token = $('#dtoken').value.trim();
|
||||
if($<HTMLInputElement>('#dtoken').value.trim()) patch.directory_token = $<HTMLInputElement>('#dtoken').value.trim();
|
||||
save(patch, 'Directory settings saved');
|
||||
};
|
||||
const clear = $('#dclear');
|
||||
const clear = $<HTMLButtonElement>('#dclear');
|
||||
if(clear) clear.onclick = () => save({directory_token: ''}, 'Token cleared');
|
||||
drawDirectoryStatus();
|
||||
}
|
||||
@@ -115,7 +115,7 @@ async function drawDirectorySettings(){
|
||||
async function drawDirectoryStatus(){
|
||||
const el = $('#dstatus');
|
||||
let s;
|
||||
try{ s = await api('/api/directory-status'); }catch(e){ el.textContent = e.message; return; }
|
||||
try{ s = await api('/api/directory-status'); }catch(e){ el.textContent = why(e); return; }
|
||||
if(!el.isConnected) return;
|
||||
const lines: string[] = [];
|
||||
if(!s.configured) lines.push('Not set up: it needs an address and a token.');
|
||||
@@ -137,8 +137,8 @@ async function drawDirectoryStatus(){
|
||||
/// sharing with it, and the feeds removed from it.
|
||||
async function drawDirectoryAdmin(){
|
||||
const box = $('#dadmin');
|
||||
let a;
|
||||
try{ a = await api('/api/directory-admin'); }catch(e){ box.innerHTML = `<p class="hint">${esc(e.message)}</p>`; return; }
|
||||
let a: DirAdmin;
|
||||
try{ a = await api('/api/directory-admin'); }catch(e){ box.innerHTML = `<p class="hint">${esc(why(e))}</p>`; return; }
|
||||
if(!box.isConnected) return;
|
||||
box.innerHTML = `<h2>Servers</h2>
|
||||
<p class="hint">Each server sharing with the directory, by its token's name. Dropping one removes its
|
||||
@@ -155,29 +155,29 @@ async function drawDirectoryAdmin(){
|
||||
<small style="display:block;color:var(--faint)">Removed ${dateOf(b.at)}</small></div>
|
||||
<button class="btn" data-a="unblock">Unblock</button></div>`).join('')
|
||||
: '<p class="hint">Nothing is blocked.</p>'}`;
|
||||
box.onclick = async ev => {
|
||||
box.onclick = async (ev: MouseEvent) => {
|
||||
const b = (ev.target as Element).closest<HTMLElement>('[data-a]');
|
||||
if(!b) return;
|
||||
const row = b.closest<HTMLElement>('.urow');
|
||||
try{
|
||||
if(b.dataset.a === 'drop'){
|
||||
const name = row.dataset.name;
|
||||
const name = row!.dataset.name!;
|
||||
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'){
|
||||
await api(`/api/directory-blocked/${encodeURIComponent(row.dataset.id)}`, {method: 'DELETE'});
|
||||
await api(`/api/directory-blocked/${encodeURIComponent(row!.dataset.id!)}`, {method: 'DELETE'});
|
||||
toast('Unblocked. It comes back with the next snapshot that has it');
|
||||
}
|
||||
drawDirectoryAdmin();
|
||||
}catch(e){ toast(e.message, true); }
|
||||
}catch(e){ toast(why(e), true); }
|
||||
};
|
||||
}
|
||||
|
||||
/* ---------------- accounts ---------------- */
|
||||
async function drawAccounts(){
|
||||
const box = $('#accounts');
|
||||
const users = await api('/api/users') || [];
|
||||
const users: Account[] = await api('/api/users') || [];
|
||||
box.innerHTML = `<h2>Accounts</h2>
|
||||
${users.map(u => `<div class="inline urow" data-id="${u.id}">
|
||||
<div style="flex:1;min-width:0"><b style="overflow-wrap:anywhere">${esc(u.name)}</b>
|
||||
@@ -195,44 +195,44 @@ async function drawAccounts(){
|
||||
<span class="hint">At least 8 characters. Leave the password empty for someone who signs in
|
||||
through the proxy. New people start with no feeds.</span></div>
|
||||
<div class="cardacts"><button class="btn primary" id="uadd">${ICON.plus} Add</button></div>`;
|
||||
const change = async (u, opts) => {
|
||||
const change = async (u: Account, opts: RequestInit) => {
|
||||
try{
|
||||
await api(`/api/users/${u.id}`, opts);
|
||||
// Demoting yourself takes this page away; go back to the app rather than stay on a page
|
||||
// the server no longer answers. Only on success: a refusal's toast has to stay readable.
|
||||
if(u.name === me?.name){ location.href = '/'; return; }
|
||||
}catch(e){ toast(e.message, true); }
|
||||
}catch(e){ toast(why(e), true); }
|
||||
drawAccounts(); // on a refusal, this puts the checkbox back where the server left it
|
||||
};
|
||||
for(const row of $$('#accounts [data-id]')){
|
||||
const u = users.find(x => String(x.id) === row.dataset.id);
|
||||
$('[data-a="admin"]', row).onchange = e =>
|
||||
change(u, {method: 'PATCH', body: JSON.stringify({admin: e.target.checked})});
|
||||
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 = () => {
|
||||
if(confirm(`Remove ${u.name}? Their subscriptions and read state go with them. Downloaded files stay.`))
|
||||
change(u, {method: 'DELETE'});
|
||||
};
|
||||
}
|
||||
$('#uadd').onclick = async () => {
|
||||
$<HTMLButtonElement>('#uadd').onclick = async () => {
|
||||
try{
|
||||
await api('/api/users', {method: 'POST', body: JSON.stringify({
|
||||
name: $('#uname').value, password: $('#upass').value, admin: $('#uadmin').checked})});
|
||||
name: $<HTMLInputElement>('#uname').value, password: $<HTMLInputElement>('#upass').value, admin: $<HTMLInputElement>('#uadmin').checked})});
|
||||
toast('Added'); drawAccounts();
|
||||
}catch(e){ toast(e.message, true); } // keep what was typed
|
||||
}catch(e){ toast(why(e), true); } // keep what was typed
|
||||
};
|
||||
}
|
||||
|
||||
/* ---------------- log ---------------- */
|
||||
let logTimer = null, logSeq = 0, logLines = [], logFilter = '', logLevel = '', logTab = 'all';
|
||||
let logTimer: number|null = null, logSeq = 0, logLines: LogLine[] = [], logFilter = '', logLevel = '', logTab = 'all';
|
||||
// Which sources belong to each tab. "daemon" is the control protocol itself: every
|
||||
// command in and every event out, whatever sent it.
|
||||
const LOG_TABS = {
|
||||
const LOG_TABS: Record<string, ((t: string) => boolean)|null> = {
|
||||
all: null,
|
||||
daemon: t => t === 'ipx::io',
|
||||
scan: t => t === 'ipx::scan',
|
||||
web: t => t === 'ipx::http',
|
||||
};
|
||||
const LEVELS = {ERROR: 3, WARN: 2, INFO: 1, DEBUG: 0, TRACE: 0};
|
||||
const LEVELS: Record<string,number> = {ERROR: 3, WARN: 2, INFO: 1, DEBUG: 0, TRACE: 0};
|
||||
|
||||
function drawLogView(){
|
||||
logSeq = 0; logLines = [];
|
||||
@@ -259,14 +259,14 @@ function drawLogView(){
|
||||
The buffer keeps debug detail even when the terminal does not; <b>IPX_UI_LOG</b> changes
|
||||
what it captures.</span>`;
|
||||
for(const b of $$('#logtabs button')) b.onclick = () => {
|
||||
logTab = b.dataset.t;
|
||||
logTab = b.dataset.t!;
|
||||
for(const x of $$('#logtabs button')) x.classList.toggle('on', x.dataset.t === logTab);
|
||||
drawLog();
|
||||
};
|
||||
$('#loglevel').onchange = e => { logLevel = e.target.value; drawLog(); };
|
||||
$('#logq').oninput = e => { logFilter = e.target.value.toLowerCase(); drawLog(); };
|
||||
$('#logcopy').onclick = () => copyText(visibleLog().map(l =>
|
||||
`${new Date(l.ts * 1000).toISOString()} ${l.level} ${l.target} ${l.msg}`).join('\n'), $('#logcopy'));
|
||||
$<HTMLSelectElement>('#loglevel').onchange = (e: Event) => { logLevel = (e.target as HTMLSelectElement).value; drawLog(); };
|
||||
$<HTMLInputElement>('#logq').oninput = (e: Event) => { logFilter = (e.target as HTMLInputElement).value.toLowerCase(); drawLog(); };
|
||||
$<HTMLButtonElement>('#logcopy').onclick = () => copyText(visibleLog().map(l =>
|
||||
`${new Date(l.ts * 1000).toISOString()} ${l.level} ${l.target} ${l.msg}`).join('\n'), $<HTMLButtonElement>('#logcopy'));
|
||||
pollLog();
|
||||
if(!logTimer) logTimer = setInterval(pollLog, 2000);
|
||||
}
|
||||
@@ -281,7 +281,7 @@ async function pollLog(){
|
||||
}else if(!logLines.length){ drawLog(); }
|
||||
}catch(e){
|
||||
const box = $('#logbox');
|
||||
if(box) box.innerHTML = `<p class="empty">Lost contact with the daemon: ${esc(e.message)}</p>`;
|
||||
if(box) box.innerHTML = `<p class="empty">Lost contact with the daemon: ${esc(why(e))}</p>`;
|
||||
}
|
||||
}
|
||||
function visibleLog(){
|
||||
@@ -294,7 +294,7 @@ function visibleLog(){
|
||||
}
|
||||
function drawLog(){
|
||||
const box = $('#logbox'); if(!box) return;
|
||||
const follow = $('#logfollow')?.checked;
|
||||
const follow = $<HTMLInputElement>('#logfollow')?.checked;
|
||||
const rows = visibleLog();
|
||||
box.innerHTML = rows.length ? rows.map(l => {
|
||||
const t = new Date(l.ts * 1000).toLocaleTimeString();
|
||||
|
||||
@@ -9,9 +9,9 @@ function closeModal(){
|
||||
$('#modal').classList.remove('on');
|
||||
}
|
||||
|
||||
$('#modal').onclick=e=>{ if(e.target.id==='modal') closeModal(); };
|
||||
$('#modal').onclick=(e: MouseEvent)=>{ if((e.target as Element).id==='modal') closeModal(); };
|
||||
|
||||
$('#addFeed').onclick=()=>{
|
||||
$<HTMLButtonElement>('#addFeed').onclick=()=>{
|
||||
openModal(`<h3>Add a feed</h3>
|
||||
<div class="field"><label>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>
|
||||
@@ -20,17 +20,17 @@ $('#addFeed').onclick=()=>{
|
||||
<label class="check"><input type="checkbox" id="nexp"> Allow items marked explicit</label>
|
||||
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Cancel" aria-label="Cancel">${ICON.close}</button>
|
||||
<button class="btn ico primary" id="nsave" title="Add feed" aria-label="Add feed">${ICON.plus}</button></div>`);
|
||||
$('#nurl').focus();
|
||||
$('#nsave').onclick=async()=>{
|
||||
const url=$('#nurl').value.trim(); if(!url) return;
|
||||
$('#nsave').disabled=true; $('#nsave').title='Adding…';
|
||||
$<HTMLInputElement>('#nurl').focus();
|
||||
$<HTMLButtonElement>('#nsave').onclick=async()=>{
|
||||
const url=$<HTMLInputElement>('#nurl').value.trim(); if(!url) return;
|
||||
$<HTMLButtonElement>('#nsave').disabled=true; $<HTMLButtonElement>('#nsave').title='Adding…';
|
||||
try{
|
||||
const r=await api('/api/feeds',{method:'POST',body:JSON.stringify({
|
||||
url, allow_explicit:$('#nexp').checked,
|
||||
keywords:$('#nkw').value.split(',').map(s=>s.trim()).filter(Boolean)})});
|
||||
url, allow_explicit:$<HTMLInputElement>('#nexp').checked,
|
||||
keywords:$<HTMLInputElement>('#nkw').value.split(',').map((s: string)=>s.trim()).filter(Boolean)})});
|
||||
closeModal(); toast(r.existing?`Already subscribed as ${r.id}`:`Added ${r.id}`);
|
||||
await loadFeeds(true); selectFeed(r.id);
|
||||
}catch(e){ toast(e.message,true); $('#nsave').title='Add feed'; $('#nsave').disabled=false; }
|
||||
}catch(e){ toast(why(e),true); $<HTMLButtonElement>('#nsave').title='Add feed'; $<HTMLButtonElement>('#nsave').disabled=false; }
|
||||
};
|
||||
};
|
||||
|
||||
@@ -43,7 +43,7 @@ let dirError='';
|
||||
/// One listed feed: a tile in the Directory's grid or, given its place, a row in its chart. The
|
||||
/// parts are the same either way; the class lays them out. Yours opens its feed; any other, its
|
||||
/// page in the Directory, to see what it is before you take it (#128).
|
||||
function listedFeed(p,cls,rank?: number){
|
||||
function listedFeed(p: DirFeed,cls: string,rank?: number){
|
||||
const el=document.createElement('div');
|
||||
el.className=cls+(p.subscribed?' mine':'');
|
||||
el.tabIndex=0; el.dataset.id=p.id;
|
||||
@@ -64,47 +64,47 @@ function listedFeed(p,cls,rank?: number){
|
||||
if(p.subscribed){ el.onclick=()=>selectFeed(p.feed||p.id); return el; }
|
||||
el.onclick=()=>{ dirShow=p.id; $('#content').scrollTop=0; drawDirectory(undefined,'.dback'); };
|
||||
// Its own click, not the tile's as well.
|
||||
$('[data-a="sub"]',el).onclick=ev=>{ ev.stopPropagation(); subscribeListed(p); };
|
||||
$('[data-a="sub"]',el).onclick=(ev: Event)=>{ ev.stopPropagation(); subscribeListed(p); };
|
||||
return el;
|
||||
}
|
||||
|
||||
async function subscribeListed(p){
|
||||
async function subscribeListed(p: DirFeed){
|
||||
try{
|
||||
const r=await api(`/api/popular/${encodeURIComponent(p.id)}`,{method:'POST'});
|
||||
toast(`Subscribed to ${NAME(p)}`);
|
||||
await loadFeeds(true); selectFeed(r.id);
|
||||
}catch(e){ toast(e.message,true); }
|
||||
}catch(e){ toast(why(e),true); }
|
||||
}
|
||||
|
||||
// Where you are in the Directory: what kind of feed, which category and subcategory, in what
|
||||
// order. Out here because a search redraws the page, and the kind and order hold across visits.
|
||||
let dirKind='All', dirCat=null, dirSub=null, dirSort='az', dirRows=[];
|
||||
let dirKind='All', dirCat: string|null=null, dirSub: string|null=null, dirSort='az', dirRows: DirFeed[]=[];
|
||||
// The feed whose page is open over all that, by id; going back leaves the rest as it was.
|
||||
let dirShow=null;
|
||||
let dirShow: string|null=null;
|
||||
// The two pages that are not a category: every feed, and the feeds that name none. A category is
|
||||
// Apple's or one an admin typed, neither of which starts with a colon.
|
||||
const EVERY=':every', OTHER=':other';
|
||||
const NAME=p=>(p.title||p.id);
|
||||
const byName=(a,b)=>NAME(a).localeCompare(NAME(b),undefined,{sensitivity:'base',numeric:true});
|
||||
const bySubs=(a,b)=>b.subscribers-a.subscribers||byName(a,b);
|
||||
const NAME=(p: {title: string|null, id: string})=>(p.title||p.id);
|
||||
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={
|
||||
const DIR_SORTS: Record<string,[string,(a: DirFeed,b: DirFeed)=>number]>={
|
||||
subscribers:['Most subscribers',bySubs],
|
||||
az:['Name, A to Z',byName],
|
||||
za:['Name, Z to A',(a,b)=>byName(b,a)],
|
||||
za:['Name, Z to A',(a: DirFeed,b: DirFeed)=>byName(b,a)],
|
||||
};
|
||||
const KINDS={All:()=>true,Podcasts:p=>p.podcast,Blogs:p=>!p.podcast};
|
||||
const KIND_WORD={All:'feed',Podcasts:'podcast',Blogs:'blog'};
|
||||
const KINDS: Record<string,(p: DirFeed)=>boolean>={All:()=>true,Podcasts:p=>p.podcast,Blogs:p=>!p.podcast};
|
||||
const KIND_WORD: Record<string,string>={All:'feed',Podcasts:'podcast',Blogs:'blog'};
|
||||
|
||||
/// The Directory, as Apple's is laid out: it opens on the most subscribed feeds and the
|
||||
/// categories, and a category has a page of its own, its subcategories along the top of its
|
||||
/// grid. What a feed is (Podcasts, anything with audio or video, or Blogs, the rest) holds across
|
||||
/// every page, and the search box looks through the lot. One fetch draws all of it.
|
||||
async function renderDirectory(url,box){
|
||||
async function renderDirectory(url: string,box: HTMLElement){
|
||||
// Each visit starts at the front, as going back to a tab does.
|
||||
dirCat=null; dirSub=null; dirShow=null;
|
||||
dirError='';
|
||||
try{ dirRows=await api(url)||[]; }catch(e){ dirRows=[]; dirError=e.message; }
|
||||
try{ dirRows=await api(url)||[]; }catch(e){ dirRows=[]; dirError=why(e); }
|
||||
drawDirectory(box);
|
||||
return dirRows.length;
|
||||
}
|
||||
@@ -117,24 +117,24 @@ function drawDirectory(box=$('#directory'), focus?: string){
|
||||
const both=dirRows.some(KINDS.Podcasts)&&dirRows.some(KINDS.Blogs);
|
||||
if(!both) dirKind='All';
|
||||
const rows=dirRows.filter(KINDS[dirKind]), word=KIND_WORD[dirKind];
|
||||
const count=n=>`${n.toLocaleString()} ${word}${n===1?'':'s'}`;
|
||||
const of=c=>p=>c===EVERY||(c===OTHER?!p.category:p.category===c);
|
||||
const count=(n: number)=>`${n.toLocaleString()} ${word}${n===1?'':'s'}`;
|
||||
const of=(c: string)=>(p: DirFeed)=>c===EVERY||(c===OTHER?!p.category:p.category===c);
|
||||
// A kind can leave a category with nothing in it; that goes back to the front.
|
||||
if(dirCat&&!rows.some(of(dirCat))) dirCat=null;
|
||||
const catName=c=>c===EVERY?`All ${word}s`:c===OTHER?'Other':c;
|
||||
const top=list=>list.filter(p=>p.subscribers).sort(bySubs).slice(0,10);
|
||||
const btn=(k,v,label,on)=>`<button type="button" data-${k}="${esc(v)}" aria-pressed="${on}"${on?' class="on"':''}>${label}</button>`;
|
||||
const catName=(c: string)=>c===EVERY?`All ${word}s`:c===OTHER?'Other':c;
|
||||
const top=(list: DirFeed[])=>list.filter(p=>p.subscribers).sort(bySubs).slice(0,10);
|
||||
const btn=(k: string,v: string,label: string,on: boolean)=>`<button type="button" data-${k}="${esc(v)}" aria-pressed="${on}"${on?' class="on"':''}>${label}</button>`;
|
||||
// back: where its button goes, '' for the front; none on the front itself.
|
||||
const head=(title,sub,back?)=>`<div class="dhead">${back==null?'':
|
||||
const head=(title: string,sub: string,back?: string)=>`<div class="dhead">${back==null?'':
|
||||
`<button type="button" class="dback" data-go="${esc(back)}">${ICON.left}${esc(back?catName(back):'Directory')}</button>`}
|
||||
<div class="dtitle"><h2>${esc(title)}</h2>${both?`<div class="tabs" role="group" aria-label="Kind">${
|
||||
Object.keys(KINDS).map(k=>btn('kind',k,k,k===dirKind)).join('')}</div>`:''}</div>
|
||||
<p class="sub">${esc(sub)}</p></div>`;
|
||||
const sec=(title,body,extra='')=>`<section class="dsec">${title?`<div class="dsech"><h3>${esc(title)}</h3>${extra}</div>`:''}${body}</section>`;
|
||||
const sec=(title: string,body: string,extra='')=>`<section class="dsec">${title?`<div class="dsech"><h3>${esc(title)}</h3>${extra}</div>`:''}${body}</section>`;
|
||||
const tools=(pills='')=>`<div class="dtools">${pills||'<span class="grow"></span>'}<select id="dirsort" aria-label="Sort">${
|
||||
Object.entries(DIR_SORTS).map(([k,[label]])=>`<option value="${k}"${k===dirSort?' selected':''}>${label}</option>`).join('')}</select></div>`;
|
||||
const q=S.q.trim(), grid='<div class="tiles" id="dtiles"></div>', board='<div class="chart" id="dchart"></div>';
|
||||
let html, chart=[], tiles=null;
|
||||
let html: string, chart: DirFeed[]=[], tiles: DirFeed[]|null=null;
|
||||
const show=dirShow&&dirRows.find(p=>p.id===dirShow);
|
||||
if(show){
|
||||
const n=show.subscribers;
|
||||
@@ -154,21 +154,21 @@ function drawDirectory(box=$('#directory'), focus?: string){
|
||||
html=head(`Results for “${q}”`,tiles.length?count(tiles.length):`No ${word} here has that in its name.`,dirCat||'')+tools()+grid;
|
||||
}else if(!dirCat){
|
||||
chart=top(rows);
|
||||
const cats=new Map<string,any[]>();
|
||||
for(const p of rows){ const c=p.category||OTHER; if(!cats.has(c)) cats.set(c,[]); cats.get(c).push(p); }
|
||||
const cats=new Map<string,DirFeed[]>();
|
||||
for(const p of rows){ const c=p.category||OTHER; if(!cats.has(c)) cats.set(c,[]); cats.get(c)!.push(p); }
|
||||
// Other, the feeds with no category, goes last.
|
||||
const order=[...cats.keys()].sort((a,b)=>Number(a===OTHER)-Number(b===OTHER)||a.localeCompare(b));
|
||||
html=head('Directory',`${count(rows.length)} shared by iPX servers. Private feeds are never listed.`)
|
||||
+(chart.length?sec('Most subscribed',board):'')
|
||||
+sec('Categories',`<div class="cats">${order.map(c=>catTile(c,catName(c),count(cats.get(c).length),cats.get(c))).join('')}</div>`,
|
||||
+sec('Categories',`<div class="cats">${order.map(c=>catTile(c,catName(c),count(cats.get(c)!.length),cats.get(c)!)).join('')}</div>`,
|
||||
`<button type="button" class="dall" data-go="${EVERY}">See all ${rows.length.toLocaleString()}</button>`);
|
||||
}else{
|
||||
const inCat=rows.filter(of(dirCat));
|
||||
const subs=dirCat===EVERY?[]:[...new Set(inCat.map(p=>p.subcategory).filter(Boolean))].sort();
|
||||
if(!subs.includes(dirSub)) dirSub=null;
|
||||
const subs=dirCat===EVERY?[]:[...new Set(inCat.map(p=>p.subcategory).filter((s): s is string=>!!s))].sort();
|
||||
if(!dirSub||!subs.includes(dirSub)) dirSub=null;
|
||||
if(dirCat!==EVERY) chart=top(inCat);
|
||||
tiles=inCat.filter(p=>!dirSub||p.subcategory===dirSub);
|
||||
const pill=(v,label,n)=>btn('sub',v,`${esc(label)}<small>${n}</small>`,(dirSub||'')===v);
|
||||
const pill=(v: string,label: string,n: number)=>btn('sub',v,`${esc(label)}<small>${n}</small>`,(dirSub||'')===v);
|
||||
html=head(catName(dirCat),dirCat===OTHER?`${count(inCat.length)} that name no category`:count(inCat.length),'')
|
||||
+(chart.length?sec('Most subscribed',board):'')
|
||||
// Its own heading only when the chart is above it, to say where one list ends.
|
||||
@@ -178,25 +178,25 @@ function drawDirectory(box=$('#directory'), focus?: string){
|
||||
box.innerHTML=html;
|
||||
if(show){ $('.show [data-a="sub"]',box).onclick=()=>subscribeListed(show); fillShow(box,show); }
|
||||
const c=$('#dchart',box);
|
||||
if(c){ c.style.setProperty('--rows',String(Math.ceil(chart.length/2))); chart.forEach((p,i)=>c.appendChild(listedFeed(p,'rank',i+1))); }
|
||||
if(c){ c.style.setProperty('--rows',String(Math.ceil(chart.length/2))); chart.forEach((p: DirFeed,i: number)=>c.appendChild(listedFeed(p,'rank',i+1))); }
|
||||
const t=$('#dtiles',box);
|
||||
if(t) for(const p of tiles.sort(DIR_SORTS[dirSort][1])) t.appendChild(listedFeed(p,'tile'));
|
||||
box.onclick=ev=>{
|
||||
if(t&&tiles) for(const p of tiles.sort(DIR_SORTS[dirSort][1])) t.appendChild(listedFeed(p,'tile'));
|
||||
box.onclick=(ev: MouseEvent)=>{
|
||||
const b=(ev.target as Element).closest<HTMLElement>('[data-go],[data-kind],[data-sub],[data-back]');
|
||||
if(!b) return;
|
||||
// Back from a feed's page, onto the tile or row it was opened from.
|
||||
if(b.dataset.back!=null){ const id=dirShow; dirShow=null; return drawDirectory(box,`[data-id="${CSS.escape(id)}"]`); }
|
||||
if(b.dataset.back!=null){ const id=dirShow??''; dirShow=null; return drawDirectory(box,`[data-id="${CSS.escape(id)}"]`); }
|
||||
if(b.dataset.kind!=null){ dirKind=b.dataset.kind; return drawDirectory(box,`[data-kind="${CSS.escape(dirKind)}"]`); }
|
||||
if(b.dataset.sub!=null){ dirSub=b.dataset.sub||null; return drawDirectory(box,`[data-sub="${CSS.escape(b.dataset.sub)}"]`); }
|
||||
// Going anywhere ends a search.
|
||||
if(S.q){ S.q=''; $('#epSearch').value=''; }
|
||||
if(S.q){ S.q=''; $<HTMLInputElement>('#epSearch').value=''; }
|
||||
const from=dirCat;
|
||||
dirCat=b.dataset.go||null; dirSub=null; dirShow=null;
|
||||
$('#content').scrollTop=0;
|
||||
// Into a page, onto its way back; back out, onto the tile you went in by.
|
||||
drawDirectory(box,dirCat?'.dback':from?`[data-go="${CSS.escape(from)}"]:not(.dback)`:undefined);
|
||||
};
|
||||
const s=$('#dirsort',box);
|
||||
const s=$<HTMLSelectElement>('#dirsort',box);
|
||||
if(s) s.onchange=()=>{ dirSort=s.value; drawDirectory(box,'#dirsort'); };
|
||||
if(focus) $(focus,box)?.focus();
|
||||
}
|
||||
@@ -204,11 +204,11 @@ function drawDirectory(box=$('#directory'), focus?: string){
|
||||
/// A listed feed's page, filled in: what it says it is, its first lines unless you ask for the
|
||||
/// rest, and its latest items, each one's title, opening its post on the publisher's site where
|
||||
/// it has one, its first lines, and when and how long.
|
||||
async function fillShow(box,p){
|
||||
async function fillShow(box: HTMLElement,p: DirFeed){
|
||||
const list=$('#dshow',box), about=$('#dabout',box);
|
||||
let got;
|
||||
let got: {description: string|null, failing: string|null, items: ListedItem[], can_admin: boolean};
|
||||
try{ got=await api(`/api/directory/${encodeURIComponent(p.id)}`); }
|
||||
catch(e){ list.innerHTML=`<p class="hint">${esc(e.message)}</p>`; return; }
|
||||
catch(e){ list.innerHTML=`<p class="hint">${esc(why(e))}</p>`; return; }
|
||||
// Gone back, or on to another, while it loaded.
|
||||
if(dirShow!==p.id||!list.isConnected) return;
|
||||
// Some feeds give their title again as their description, which says nothing new.
|
||||
@@ -233,12 +233,12 @@ async function fillShow(box,p){
|
||||
+`<button class="btn ico danger" data-a="dremove" title="Remove from the directory" aria-label="Remove from the directory">${ICON.trash}</button>`);
|
||||
$('[data-a="drefresh"]',acts).onclick=async()=>{
|
||||
try{ await api(`/api/directory/${encodeURIComponent(p.id)}/refresh`,{method:'POST'}); toast('Checked'); fillShow(box,p); }
|
||||
catch(e){ toast(e.message,true); }
|
||||
catch(e){ toast(why(e),true); }
|
||||
};
|
||||
$('[data-a="dremove"]',acts).onclick=async()=>{
|
||||
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(e.message,true); }
|
||||
catch(e){ return toast(why(e),true); }
|
||||
toast(`Removed ${NAME(p)} from the directory`);
|
||||
dirRows=dirRows.filter(r=>r.id!==p.id); dirShow=null;
|
||||
drawDirectory(box);
|
||||
@@ -256,7 +256,7 @@ async function fillShow(box,p){
|
||||
|
||||
/// A category as a tile: its name, how many feeds, and the covers of its three most subscribed
|
||||
/// fanned in the corner, so each one is coloured by what is in it, as Apple's are.
|
||||
function catTile(c,name,count,rows){
|
||||
function catTile(c: string,name: string,count: string,rows: DirFeed[]){
|
||||
// Covers before initials, which are all Other had; the likeliest first, and first is in front:
|
||||
// the fan is drawn back to front.
|
||||
const art=[...rows].sort((a,b)=>Number(!a.image)-Number(!b.image)||bySubs(a,b)).slice(0,3).reverse();
|
||||
@@ -265,20 +265,20 @@ function catTile(c,name,count,rows){
|
||||
}
|
||||
|
||||
/// The Directory and Currently Listening open in the main pane, as the original's Directory did.
|
||||
async function renderListed(v){
|
||||
async function renderListed(v: {title: string, icon: string, url?: string, blurb?: string}){
|
||||
const box=$('#content');
|
||||
box.classList.add('plain');
|
||||
$('#tbRemove').disabled=true;
|
||||
$<HTMLButtonElement>('#tbRemove').disabled=true;
|
||||
syncTools(null);
|
||||
if(v===VIEWS[':directory']){
|
||||
$('#epSearch').placeholder='Find a feed…';
|
||||
$<HTMLInputElement>('#epSearch').placeholder='Find a feed…';
|
||||
box.innerHTML='<div id="directory"><p class="hint">Loading…</p></div>';
|
||||
$('#count').textContent=v.title;
|
||||
const n=await renderDirectory(v.url,$('#directory'));
|
||||
if(VIEWS[S.feed]===v) $('#count').textContent=`${v.title}: ${plural(n,'feed')}`;
|
||||
const n=await renderDirectory(v.url!,$('#directory'));
|
||||
if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'feed')}`;
|
||||
return;
|
||||
}
|
||||
$('#epSearch').placeholder='Search items…';
|
||||
$<HTMLInputElement>('#epSearch').placeholder='Search items…';
|
||||
box.innerHTML=`
|
||||
<div class="fhead slim">
|
||||
<div class="art">${v.icon}</div>
|
||||
@@ -287,21 +287,21 @@ async function renderListed(v){
|
||||
<div class="childlist" id="listening"><p class="hint">Loading…</p></div>`;
|
||||
$('#count').textContent=v.title;
|
||||
// The search box looks through these too, title and text, as it does a feed's items (#127).
|
||||
const n=await renderListening(S.q?`${v.url}&q=${encodeURIComponent(S.q)}`:v.url,$('#listening',box));
|
||||
if(VIEWS[S.feed]===v) $('#count').textContent=`${v.title}: ${plural(n,'episode')}`;
|
||||
const n=await renderListening(S.q?`${v.url}&q=${encodeURIComponent(S.q)}`:v.url!,$('#listening',box));
|
||||
if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'episode')}`;
|
||||
}
|
||||
|
||||
/// 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.
|
||||
async function renderListening(url,box){
|
||||
let rows=[];
|
||||
async function renderListening(url: string,box: HTMLElement){
|
||||
let rows: Entry[]=[];
|
||||
try{ rows=(await api(url)).entries||[]; }catch{}
|
||||
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){
|
||||
// Carries its episode, for paintListenRow to repaint as the player moves.
|
||||
const el: HTMLDivElement & {entry?: any}=document.createElement('div');
|
||||
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||'')+
|
||||
@@ -319,8 +319,8 @@ async function renderListening(url,box){
|
||||
}
|
||||
|
||||
/// One row's time left, progress and play button, taken from the player when it is the one in it.
|
||||
function paintListenRow(el){
|
||||
const e=el.entry, now=player.guid===e.guid&&player.feed===e.feed_id;
|
||||
function paintListenRow(el: HTMLElement & {entry?: Entry}){
|
||||
const e=el.entry!, now=player.guid===e.guid&&player.feed===e.feed_id;
|
||||
// Zero until the player has sought to where you left off; the saved position stands till then.
|
||||
if(now&&audio.currentTime) e.position=Math.floor(audio.currentTime);
|
||||
// The player's own length first: a feed's can be minutes out.
|
||||
@@ -335,32 +335,32 @@ function paintListenRow(el){
|
||||
}
|
||||
/// 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 $$('#listening .childrow'))
|
||||
for(const el of $$<HTMLElement & {entry?: Entry}>('#listening .childrow'))
|
||||
if(el.entry&&(el.classList.contains('now')||player.guid===el.entry.guid)) paintListenRow(el);
|
||||
}
|
||||
|
||||
/// Takes an episode off Currently Listening by forgetting where you got to: the list is every
|
||||
/// episode with a saved position short of the end, so the position is what has to go.
|
||||
async function forget(e){
|
||||
async function forget(e: Entry){
|
||||
// Closed without saving first, or the player's next save would put it straight back.
|
||||
if(player.guid===e.guid){ player.guid=null; $('#pclose').click(); }
|
||||
if(player.guid===e.guid){ player.guid=null; $<HTMLButtonElement>('#pclose').click(); }
|
||||
try{
|
||||
await api(`/api/entries/${encodeURIComponent(e.feed_id)}/${encodeURIComponent(e.guid)}/position`,
|
||||
{method:'POST',body:JSON.stringify({secs:0})});
|
||||
}catch(err){ toast(err.message,true); }
|
||||
}catch(err){ toast(why(err),true); }
|
||||
if(S.feed===':listening') renderListed(VIEWS[':listening']);
|
||||
}
|
||||
|
||||
// The toolbar acts on whatever is selected: the feed on the left, the item in the table.
|
||||
$('#tbRemove').onclick=()=>{ const f=S.feeds.find(x=>x.id===S.feed); if(f) removeFeed(f); };
|
||||
$('#tbPlay').onclick=()=>{ const e=cur(); if(e) play(e); };
|
||||
$('#tbRead').onclick=()=>{ const e=cur(); if(e) epAction('read',e,null); };
|
||||
$('#tbFlag').onclick=()=>{ const e=cur(); if(e) epAction('flag',e,null); };
|
||||
let searchT;
|
||||
$('#epSearch').oninput=ev=>{ clearTimeout(searchT);
|
||||
$<HTMLButtonElement>('#tbRemove').onclick=()=>{ const f=S.feeds.find(x=>x.id===S.feed); if(f) removeFeed(f); };
|
||||
$<HTMLButtonElement>('#tbPlay').onclick=()=>{ const e=cur(); if(e) play(e); };
|
||||
$<HTMLButtonElement>('#tbRead').onclick=()=>{ const e=cur(); if(e) epAction('read',e,null); };
|
||||
$<HTMLButtonElement>('#tbFlag').onclick=()=>{ const e=cur(); if(e) epAction('flag',e,null); };
|
||||
let searchT: number;
|
||||
$<HTMLInputElement>('#epSearch').oninput=(ev: Event)=>{ clearTimeout(searchT);
|
||||
// The Directory looks through what it already has; Currently Listening and the rest ask the
|
||||
// server (#126, #127).
|
||||
searchT=setTimeout(()=>{ S.q=ev.target.value; S.offset=0;
|
||||
searchT=setTimeout(()=>{ S.q=(ev.target as HTMLInputElement).value; S.offset=0;
|
||||
if(S.feed===':directory'){ dirShow=null; drawDirectory(); }
|
||||
else if(S.feed===':listening') renderListed(VIEWS[':listening']);
|
||||
else loadEntries(); },250); };
|
||||
@@ -368,13 +368,13 @@ $('#epSearch').oninput=ev=>{ clearTimeout(searchT);
|
||||
window.matchMedia?.('(max-width:820px)')?.addEventListener?.('change',()=>{ const e=cur(); if(e) showDetail(e); });
|
||||
|
||||
let expanded = new Set(JSON.parse(localStorage.getItem('ipx.expanded')||'[]'));
|
||||
function toggleGroup(id){
|
||||
function toggleGroup(id: string){
|
||||
expanded.has(id) ? expanded.delete(id) : expanded.add(id);
|
||||
try{ localStorage.setItem('ipx.expanded', JSON.stringify([...expanded])); }catch{}
|
||||
renderFeeds();
|
||||
}
|
||||
let globalMax = 3;
|
||||
function due(ts){
|
||||
function due(ts: number){
|
||||
const d = ts - Date.now()/1000;
|
||||
if(d <= 0) return 'due now';
|
||||
if(d < 3600) return 'in '+Math.max(1,Math.round(d/60))+'m';
|
||||
@@ -385,7 +385,7 @@ function due(ts){
|
||||
/// Your settings: the theme, your subscriptions as OPML, and, to read, what the server does
|
||||
/// with feeds. The server's own settings, the accounts and the log are on /admin, which only an
|
||||
/// admin is sent (issue #19); this used to hold them too, shown to admins only.
|
||||
function deadSavedText(me){
|
||||
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 show\'s settings, or beside the speed while it plays, to cut the dead air from it.';
|
||||
@@ -429,45 +429,45 @@ async function prefsModal(){
|
||||
<div class="field"><label>Feeds are checked every</label>
|
||||
<span class="hint">${everyText(g.every_mins)}, for every feed that does not set its own.
|
||||
${admin?'This and the rest of the server\'s settings are on the <a href="/admin">admin page</a>.':'Only an admin changes this.'}</span></div>`);
|
||||
$('#stheme').onchange=e=>setTheme(e.target.value,undefined,true);
|
||||
$('#smode').onchange=e=>setTheme(undefined,e.target.value,true);
|
||||
$('#gopml').onclick=opmlModal;
|
||||
$<HTMLSelectElement>('#stheme').onchange=(e: Event)=>setTheme((e.target as HTMLSelectElement).value,undefined,true);
|
||||
$<HTMLSelectElement>('#smode').onchange=(e: Event)=>setTheme(undefined,(e.target as HTMLSelectElement).value,true);
|
||||
$<HTMLButtonElement>('#gopml').onclick=opmlModal;
|
||||
drawTokens();
|
||||
$('#tokadd').onclick=async()=>{
|
||||
const name=$('#tokname').value.trim(); if(!name){ $('#tokname').focus(); return; }
|
||||
$<HTMLButtonElement>('#tokadd').onclick=async()=>{
|
||||
const name=$<HTMLInputElement>('#tokname').value.trim(); if(!name){ $<HTMLInputElement>('#tokname').focus(); return; }
|
||||
try{
|
||||
const t=await api('/api/tokens',{method:'POST',body:JSON.stringify({name})});
|
||||
$('#tokname').value='';
|
||||
$<HTMLInputElement>('#tokname').value='';
|
||||
await drawTokens();
|
||||
// Shown this once: only its hash is kept, so a lost token is revoked and made again.
|
||||
$('#tokens').insertAdjacentHTML('afterbegin',`<div class="field" id="toknew"><span class="hint">Your new token,
|
||||
${esc(t.name)}. Copy it now: it is not shown again.</span>
|
||||
<div class="inline"><input type="text" id="tokval" readonly value="${esc(t.token)}">
|
||||
<button class="btn ico" id="tokcopy" title="Copy" aria-label="Copy">${ICON.copy}</button></div></div>`);
|
||||
$('#tokcopy').onclick=()=>copyText(t.token,$('#tokcopy'));
|
||||
$('#tokval').select();
|
||||
}catch(err){ toast(err.message,true); }
|
||||
$<HTMLButtonElement>('#tokcopy').onclick=()=>copyText(t.token,$<HTMLButtonElement>('#tokcopy'));
|
||||
$<HTMLInputElement>('#tokval').select();
|
||||
}catch(err){ toast(why(err),true); }
|
||||
};
|
||||
$('#sblock').onchange=async e=>{
|
||||
const blocked=splitWords(e.target.value);
|
||||
$<HTMLInputElement>('#sblock').onchange=async (e: Event)=>{
|
||||
const blocked=splitWords((e.target as HTMLInputElement).value);
|
||||
try{
|
||||
await api('/api/me',{method:'PATCH',body:JSON.stringify({blocked})});
|
||||
if(S.me) S.me.blocked=blocked;
|
||||
toast('Saved'); await loadFeeds(true); loadEntries();
|
||||
}catch(err){ toast(err.message,true); }
|
||||
}catch(err){ toast(why(err),true); }
|
||||
};
|
||||
}
|
||||
|
||||
/// Your API tokens, each with when it was made and last used, and a button to revoke it.
|
||||
async function drawTokens(){
|
||||
const box=$('#tokens'); if(!box) return;
|
||||
const list=await api('/api/tokens').catch(()=>[]);
|
||||
const list: {id: number, name: string, created: number, last_used: number|null}[]=await api('/api/tokens').catch((): []=>[]);
|
||||
box.innerHTML=list.map(t=>`<div class="tokrow"><span><b>${esc(t.name)}</b>
|
||||
<span class="hint">made ${dateOf(t.created)}, last used ${ago(t.last_used)}</span></span>
|
||||
<button class="btn ico" data-tok="${t.id}" title="Revoke ${esc(t.name)}" aria-label="Revoke ${esc(t.name)}">${ICON.trash}</button></div>`).join('');
|
||||
for(const b of $$('[data-tok]',box)) b.onclick=async()=>{
|
||||
try{ await api(`/api/tokens/${b.dataset.tok}`,{method:'DELETE'}); toast('Revoked'); drawTokens(); }
|
||||
catch(err){ toast(err.message,true); }
|
||||
catch(err){ toast(why(err),true); }
|
||||
};
|
||||
}
|
||||
|
||||
@@ -486,37 +486,37 @@ function chipsHTML(words: string[], input: string){
|
||||
placeholder="${words.length?'':CHIP_HINT}" enterkeyhint="done" autocomplete="off" spellcheck="false">`;
|
||||
}
|
||||
/// The words in a chip box, with whatever is typed and not yet a chip.
|
||||
function chipWords(box){
|
||||
return [...$$('.chip',box).map(c=>c.dataset.w), ...splitWords($('.chipin',box).value)];
|
||||
function chipWords(box: ParentNode){
|
||||
return [...$$('.chip',box).map(c=>c.dataset.w), ...splitWords($<HTMLInputElement>('.chipin',box).value)];
|
||||
}
|
||||
function wireChips(box){
|
||||
const input=$('.chipin',box);
|
||||
function wireChips(box: HTMLElement){
|
||||
const input=$<HTMLInputElement>('.chipin',box);
|
||||
// The hint only in an empty box: beside chips it reads as one more.
|
||||
const hint=()=>{ input.placeholder=$$('.chip',box).length?'':CHIP_HINT; };
|
||||
const add=()=>{
|
||||
const have=$$('.chip',box).map(c=>c.dataset.w.toLowerCase());
|
||||
const have=$$('.chip',box).map(c=>c.dataset.w!.toLowerCase());
|
||||
for(const w of splitWords(input.value)){
|
||||
if(have.includes(w.toLowerCase())) continue;
|
||||
input.insertAdjacentHTML('beforebegin',chipHTML(w)); have.push(w.toLowerCase());
|
||||
}
|
||||
input.value=''; hint();
|
||||
};
|
||||
input.onkeydown=e=>{
|
||||
input.onkeydown=(e: KeyboardEvent)=>{
|
||||
if(e.key==='Enter'||e.key===','){ e.preventDefault(); add(); }
|
||||
else if(e.key==='Backspace'&&!input.value){ input.previousElementSibling?.remove(); hint(); }
|
||||
};
|
||||
// Typed and left without Enter is still meant: Save takes it either way.
|
||||
input.onblur=add;
|
||||
box.onclick=e=>{
|
||||
const x=e.target.closest('.chipx');
|
||||
if(x){ x.parentElement.remove(); hint(); }
|
||||
box.onclick=(e: MouseEvent)=>{
|
||||
const x=(e.target as Element).closest('.chipx');
|
||||
if(x){ x.parentElement!.remove(); hint(); }
|
||||
input.focus();
|
||||
};
|
||||
}
|
||||
|
||||
/// Your settings for one feed, under its address (#167). What it says is what will happen, in this feed's numbers: the download limit was a bare
|
||||
/// box whose blank, number and 0 were explained in bold small print.
|
||||
function settingsModal(f, newUrl?: string){
|
||||
function settingsModal(f: Feed, newUrl?: string){
|
||||
const kids=S.feeds.filter(c=>c.group===f.id).length;
|
||||
const isGroup=kids>0;
|
||||
const parent=f.managed?S.feeds.find(p=>p.id===f.group):null;
|
||||
@@ -524,7 +524,7 @@ function settingsModal(f, newUrl?: string){
|
||||
const name=f.title||f.id;
|
||||
// Blank follows the server's default; 0 is every item (#166).
|
||||
let mode=f.max_new_per_check==null?'default':f.max_new_per_check===0?'all':'newest';
|
||||
let newest=f.max_new_per_check>0?f.max_new_per_check:(globalMax||3);
|
||||
let newest=f.max_new_per_check&&f.max_new_per_check>0?f.max_new_per_check:(globalMax||3);
|
||||
const whose=isGroup
|
||||
? `Your settings for the ${plural(kids,'show')} in this ${isPatreon(f)?'Patreon creator':'OPML subscription'}. A show you set on its own keeps its own.`
|
||||
: parent
|
||||
@@ -576,7 +576,7 @@ function settingsModal(f, newUrl?: string){
|
||||
// What only matters while it downloads on its own folds away, out of reach, when it does not.
|
||||
const deps=$('#sdeps'), inner=$('.fdepsin',deps);
|
||||
inner.inert=!f.auto_download;
|
||||
$('#sauto').onchange=e=>{ deps.classList.toggle('off',!e.target.checked); inner.inert=!e.target.checked; };
|
||||
$<HTMLInputElement>('#sauto').onchange=(e: Event)=>{ deps.classList.toggle('off',!(e.target as HTMLInputElement).checked); inner.inert=!(e.target as HTMLInputElement).checked; };
|
||||
|
||||
// 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).
|
||||
@@ -591,7 +591,7 @@ function settingsModal(f, newUrl?: string){
|
||||
? `The server's default: downloads the newest ${globalMax}${each} on its own.${older}`
|
||||
: `The server's default: downloads every item${each}, the whole back catalogue.`;
|
||||
const limit=()=>mode==='all'||(mode==='default'&&!globalMax)?Infinity:mode==='default'?globalMax:newest;
|
||||
let bars=[];
|
||||
let bars: HTMLElement[]=[];
|
||||
const draw=(words: boolean)=>{
|
||||
// The newest items with a file, as hold_back counts them: one whose files a filter all
|
||||
// skipped holds no place.
|
||||
@@ -605,21 +605,21 @@ function settingsModal(f, newUrl?: string){
|
||||
}
|
||||
if(!words) return;
|
||||
$('#swcap').innerHTML=caption();
|
||||
const n=$('#smax');
|
||||
const n=$<HTMLInputElement>('#smax');
|
||||
if(n) n.oninput=()=>{ newest=Math.max(1,Math.floor(Number(n.value))||1); draw(false); };
|
||||
};
|
||||
for(const r of $$('[name=swin]')) r.onchange=()=>{ mode=r.value; draw(true); };
|
||||
for(const r of $$<HTMLInputElement>('[name=swin]')) r.onchange=()=>{ mode=r.value; draw(true); };
|
||||
// Breathing room only matters with DeadAir on: greyed out, not hidden, so it can be seen beforehand.
|
||||
$('#sdead').onchange=e=>{ $('#sdpause').disabled=!e.target.checked; };
|
||||
const pause=$('#sdpause'), pauseText=()=>{ const s=`${pause.value/1000} s`; $('#sdpauseout').textContent=s; pause.setAttribute('aria-valuetext',s); };
|
||||
$<HTMLInputElement>('#sdead').onchange=(e: Event)=>{ $<HTMLInputElement>('#sdpause').disabled=!(e.target as HTMLInputElement).checked; };
|
||||
const pause=$<HTMLInputElement>('#sdpause'), pauseText=()=>{ const s=`${Number(pause.value)/1000} s`; $('#sdpauseout').textContent=s; pause.setAttribute('aria-valuetext',s); };
|
||||
pause.oninput=pauseText; pauseText();
|
||||
draw(true);
|
||||
// The feed's own newest items, each as tall as it is long, so the strip reads as this show.
|
||||
if(!isGroup) api(`/api/feeds/${encodeURIComponent(f.id)}/entries?limit=40`).then(page=>{
|
||||
const items=page?.entries||[];
|
||||
const items: Entry[]=page?.entries||[];
|
||||
const strip=$('#sepwin'); if(!items.length||!strip) return;
|
||||
const longest=Math.max(1,...items.map(e=>e.duration||0));
|
||||
strip.innerHTML=items.map((e,i)=>{
|
||||
strip.innerHTML=items.map((e: Entry,i: number)=>{
|
||||
const file=e.enclosures.some(x=>x.state!=='skipped');
|
||||
const h=e.duration?Math.round(30+70*Math.sqrt(e.duration/longest)):60;
|
||||
return `<i class="${file?'':'nofile'}" style="--h:${h}%;--n:${i}"></i>`;
|
||||
@@ -634,65 +634,65 @@ function settingsModal(f, newUrl?: string){
|
||||
if(x<=b.getBoundingClientRect().right) break;
|
||||
}
|
||||
newest=Math.max(1,n);
|
||||
if(mode!=='newest'){ mode='newest'; $('[name=swin][value=newest]').checked=true; draw(true); }
|
||||
else { $('#smax').value=String(newest); draw(false); }
|
||||
if(mode!=='newest'){ mode='newest'; $<HTMLInputElement>('[name=swin][value=newest]').checked=true; draw(true); }
|
||||
else { $<HTMLInputElement>('#smax').value=String(newest); draw(false); }
|
||||
};
|
||||
strip.onpointerdown=e=>{ strip.setPointerCapture(e.pointerId); pick(e.clientX); };
|
||||
strip.onpointermove=e=>{ if(strip.hasPointerCapture(e.pointerId)) pick(e.clientX); };
|
||||
strip.onpointerdown=(e: PointerEvent)=>{ strip.setPointerCapture(e.pointerId); pick(e.clientX); };
|
||||
strip.onpointermove=(e: PointerEvent)=>{ if(strip.hasPointerCapture(e.pointerId)) pick(e.clientX); };
|
||||
}).catch(()=>{});
|
||||
|
||||
wireChips($('#skw'));
|
||||
if($('#sblock')) wireChips($('#sblock'));
|
||||
$('#scopy').onclick=()=>copyText($('#surl').value,$('#scopy'));
|
||||
$<HTMLButtonElement>('#scopy').onclick=()=>copyText($<HTMLInputElement>('#surl').value,$<HTMLButtonElement>('#scopy'));
|
||||
// Opened to follow a feed that moved: the new address is what there is to look at.
|
||||
if(newUrl){ $('#surl').scrollIntoView({block:'center'}); $('#surl').focus(); }
|
||||
if(newUrl){ $<HTMLInputElement>('#surl').scrollIntoView({block:'center'}); $<HTMLInputElement>('#surl').focus(); }
|
||||
|
||||
$('#ssave').onclick=async()=>{
|
||||
$<HTMLButtonElement>('#ssave').onclick=async()=>{
|
||||
try{
|
||||
const patch: Record<string, unknown>={
|
||||
keywords:chipWords($('#skw')),
|
||||
max_new_per_check:mode==='default'?null:mode==='all'?0:newest,
|
||||
auto_download:$('#sauto').checked, allow_explicit:$('#sexp').checked, deadair:$('#sdead').checked,
|
||||
deadair_pause:Number($('#sdpause').value)};
|
||||
auto_download:$<HTMLInputElement>('#sauto').checked, allow_explicit:$<HTMLInputElement>('#sexp').checked, deadair:$<HTMLInputElement>('#sdead').checked,
|
||||
deadair_pause:Number($<HTMLInputElement>('#sdpause').value)};
|
||||
if($('#sblock')) patch.blocked=chipWords($('#sblock'));
|
||||
// Sent only when it changed: anyone may mark a feed private, but only an admin unmark it.
|
||||
const priv=$('#sprivate');
|
||||
const priv=$<HTMLInputElement>('#sprivate');
|
||||
if(!priv.disabled&&priv.checked!==!!f.private) patch.private=priv.checked;
|
||||
// The address is the same for everyone: an admin's to change, for a feed that moved, and the
|
||||
// API refuses it from anyone else. The folder and category are not this dialog's at all.
|
||||
if(admin) patch.url=$('#surl').value.trim();
|
||||
if(admin) patch.url=$<HTMLInputElement>('#surl').value.trim();
|
||||
await api(`/api/feeds/${encodeURIComponent(f.id)}`,{method:'PATCH',body:JSON.stringify(patch)});
|
||||
closeModal(); toast('Saved. It applies from the next check.');
|
||||
await loadFeeds(true); renderFeed(); loadEntries();
|
||||
}catch(e){ toast(e.message,true); }
|
||||
}catch(e){ toast(why(e),true); }
|
||||
};
|
||||
}
|
||||
|
||||
function downloadLatestModal(f){
|
||||
function downloadLatestModal(f: Feed){
|
||||
openModal(`<h3>Download latest items</h3>
|
||||
<div class="field"><label>How many of the newest undownloaded items?</label>
|
||||
<input type="number" id="dcount" min="1" max="100" value="5">
|
||||
<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>`);
|
||||
$('#dgo').onclick=async()=>{
|
||||
const n=Number($('#dcount').value)||5;
|
||||
$<HTMLButtonElement>('#dgo').onclick=async()=>{
|
||||
const n=Number($<HTMLInputElement>('#dcount').value)||5;
|
||||
try{
|
||||
const r=await api(`/api/feeds/${encodeURIComponent(f.id)}/download-latest`,
|
||||
{method:'POST',body:JSON.stringify({count:n})});
|
||||
closeModal(); toast(`Queued ${r.queued} item${r.queued===1?'':'s'}`);
|
||||
}catch(e){ toast(e.message,true); }
|
||||
}catch(e){ toast(why(e),true); }
|
||||
};
|
||||
}
|
||||
|
||||
function removeFeed(f){
|
||||
function removeFeed(f: Feed){
|
||||
openModal(`<h3>Unsubscribe?</h3>
|
||||
<p style="color:var(--dim)">Removes <b>${esc(f.title||f.id)}</b> from your feeds. Anyone else
|
||||
reading it keeps it, along with their own read state.
|
||||
Downloaded files and history are kept, so re-adding it will not pull the back catalogue again.</p>
|
||||
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Cancel" aria-label="Cancel">${ICON.close}</button>
|
||||
<button class="btn ico danger" id="rgo" title="Unsubscribe" aria-label="Unsubscribe">${ICON.circleMinus}</button></div>`);
|
||||
$('#rgo').onclick=async()=>{
|
||||
$<HTMLButtonElement>('#rgo').onclick=async()=>{
|
||||
await api(`/api/feeds/${encodeURIComponent(f.id)}`,{method:'DELETE'});
|
||||
closeModal(); toast('Unsubscribed'); S.feed=null;
|
||||
await loadFeeds(); if(!S.feeds.length) renderFeed();
|
||||
@@ -711,11 +711,11 @@ function opmlModal(){
|
||||
<textarea id="opmlText" rows="6" style="width:100%;background:var(--bg);border:1px solid var(--line);color:var(--fg);border-radius:8px;padding:8px;font:12px monospace"></textarea></div>
|
||||
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Close" aria-label="Close">${ICON.close}</button>
|
||||
<button class="btn ico primary" id="oimp" title="Import: subscribe to every feed in it" aria-label="Import">${ICON.plus}</button></div>`);
|
||||
$('#oimp').onclick=async()=>{
|
||||
$<HTMLButtonElement>('#oimp').onclick=async()=>{
|
||||
// A chosen file is read here and sent as text, so the server never stores it. Clearing
|
||||
// the picker lets go of it on this side too, whether it was refused or imported.
|
||||
const pick=$('#opmlFile'), file=pick.files[0];
|
||||
const xml=file ? await file.text() : $('#opmlText').value;
|
||||
const pick=$<HTMLInputElement>('#opmlFile'), file=pick.files![0];
|
||||
const xml=file ? await file.text() : $<HTMLTextAreaElement>('#opmlText').value;
|
||||
const letGo=()=>{ pick.value=''; };
|
||||
// A quick look before sending anything. The server parses it properly and has the last word.
|
||||
if(!/<opml[\s>]/i.test(xml)){
|
||||
@@ -724,17 +724,21 @@ function opmlModal(){
|
||||
try{
|
||||
const r=await api('/api/opml',{method:'POST',body:JSON.stringify({xml})});
|
||||
letGo(); closeModal(); toast(`Subscribed to ${r.added} feed(s)`+(r.already?`, ${r.already} you already had`:'')); loadFeeds(true);
|
||||
}catch(e){ letGo(); toast(e.message,true); }
|
||||
}catch(e){ letGo(); toast(why(e),true); }
|
||||
};
|
||||
}
|
||||
|
||||
// No toast: the spinners on the rows being checked say it (issue #37).
|
||||
async function scanAll(){ await api('/api/fetch',{method:'POST',body:JSON.stringify({force:true})}); }
|
||||
$('#scanAll').onclick=scanAll;
|
||||
$('#prefs').onclick=prefsModal;
|
||||
async function scanAll(){
|
||||
spinStart(null);
|
||||
try{ await api('/api/fetch',{method:'POST',body:JSON.stringify({force:true})}); }
|
||||
catch(e){ spinEnd(); throw e; }
|
||||
}
|
||||
$<HTMLButtonElement>('#scanAll').onclick=scanAll;
|
||||
$<HTMLButtonElement>('#prefs').onclick=prefsModal;
|
||||
// Someone the proxy signed in is signed out by the proxy: ipx's own sign-out cannot stick while
|
||||
// the proxy still vouches for them. /api/me says where, when that is the case.
|
||||
$('#signout').onclick=async()=>{ await api('/api/logout',{method:'POST'}); location.href=S.me?.sign_out||'/login'; };
|
||||
$<HTMLButtonElement>('#signout').onclick=async()=>{ await api('/api/logout',{method:'POST'}); location.href=S.me?.sign_out||'/login'; };
|
||||
api('/api/me').then(u=>{
|
||||
S.me=u;
|
||||
$('#who').textContent=u.name+(u.admin?' · admin':'');
|
||||
@@ -746,18 +750,18 @@ api('/api/me').then(u=>{
|
||||
// A browser with no theme of its own takes the one the account kept from before, once.
|
||||
if(u.theme&&!/(^|; )ipx_theme=/.test(document.cookie)) setTheme(u.theme.name,u.theme.mode,true);
|
||||
}).catch(()=>{});
|
||||
$('#feedFilter').oninput=renderFeeds;
|
||||
$<HTMLInputElement>('#feedFilter').oninput=renderFeeds;
|
||||
// The feed list from the keyboard: Enter or Space opens a row, Right and Left open and close a
|
||||
// folder. Handled keys stop here, or the player's own Space and arrows would act on them too.
|
||||
$('#feedlist').onkeydown=ev=>{
|
||||
const row=ev.target.closest('[data-id]'); if(!row) return;
|
||||
const id=row.dataset.id;
|
||||
$('#feedlist').onkeydown=(ev: KeyboardEvent)=>{
|
||||
const row=(ev.target as Element).closest<HTMLElement>('[data-id]'); if(!row) return;
|
||||
const id=row.dataset.id!;
|
||||
if((ev.key==='Enter'||ev.key===' ')&&ev.target===row) row.click();
|
||||
else if(row.classList.contains('group')&&
|
||||
(ev.key==='ArrowRight'&&!expanded.has(id)||ev.key==='ArrowLeft'&&expanded.has(id))) toggleGroup(id);
|
||||
else return;
|
||||
ev.preventDefault(); ev.stopPropagation();
|
||||
};
|
||||
$('#burger').onclick=()=>nav(!$('#sidebar').classList.contains('open'));
|
||||
$<HTMLButtonElement>('#burger').onclick=()=>nav(!$('#sidebar').classList.contains('open'));
|
||||
$('#scrim').onclick=()=>nav(false);
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/* ---------------- live events ---------------- */
|
||||
let sse;
|
||||
let sse: EventSource;
|
||||
/// The feed list and the open list, taken again from the server. The events keep both current,
|
||||
/// and one missed is a count wrong until a reload: reading an item sends none to your other
|
||||
/// pages, so one read on another device stayed unread here, and an iPhone stops the stream while
|
||||
/// the app is in the background, when everything is missed (#168).
|
||||
const catchUp=(()=>{ let t; return ()=>{ clearTimeout(t); t=setTimeout(()=>{
|
||||
const catchUp=(()=>{ let t: number; return ()=>{ clearTimeout(t); t=setTimeout(()=>{
|
||||
loadFeeds(true).catch(()=>{});
|
||||
if(S.feed) loadEntries().catch(()=>{});
|
||||
},300); }; })();
|
||||
@@ -14,10 +14,11 @@ function connect(){
|
||||
sse=new EventSource('/api/events');
|
||||
// Back after a drop: whatever was sent meanwhile went to nobody.
|
||||
sse.onopen=()=>{ if(dropped){ dropped=false; catchUp(); } };
|
||||
const soon=(fn,ms=500)=>{ let t; return ()=>{ clearTimeout(t); t=setTimeout(fn,ms); }; };
|
||||
const refreshEntries=soon(()=>{ if(S.feed) loadEntries(); });
|
||||
const soon=(fn: ()=>void,ms=500)=>{ let t: number; return ()=>{ clearTimeout(t); t=setTimeout(fn,ms); }; };
|
||||
// Caught: a network gone when one fires (a laptop asleep) was an unhandled rejection (#219).
|
||||
const refreshEntries=soon(()=>{ if(S.feed) loadEntries().catch(()=>{}); });
|
||||
// Every scan's events reach everyone; only this person's feeds are theirs to show or refresh.
|
||||
const mine=id=>S.feeds.some(f=>f.id===id);
|
||||
const mine=(id: string)=>S.feeds.some(f=>f.id===id);
|
||||
sse.onmessage=m=>{
|
||||
let ev; try{ ev=JSON.parse(m.data) }catch{ return }
|
||||
if(ev.ev==='progress'){
|
||||
@@ -25,7 +26,7 @@ function connect(){
|
||||
// Only the row actually downloading. Without the enclosure id this used to paint
|
||||
// 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'); }
|
||||
if(bar){ bar.style.width=pct+'%'; bar.parentElement!.classList.add('live'); }
|
||||
$('#count') && ($('#count').textContent=`downloading ${ev.file} — ${pct.toFixed(0)}%`);
|
||||
}
|
||||
else if(ev.ev==='download_done'){
|
||||
@@ -65,9 +66,11 @@ function connect(){
|
||||
// every open page reloaded the whole list each time (#103).
|
||||
// Rows came as feed_row events. ponytail: a feed an OPML drops stays in the list until the
|
||||
// page reloads; reload the list here when a scan synced an OPML if that ever matters.
|
||||
else if(ev.ev==='scan_done'){ scanning.clear(); paintScanning(); if(ev.feeds) refreshEntries(); }
|
||||
else if(ev.ev==='scan_done'){ scanning.clear(); paintScanning(); spinEnd(ev); if(ev.feeds) refreshEntries(); }
|
||||
// The worker's job failed, so the scan someone is waiting on will send no scan_done.
|
||||
else if(ev.ev==='error') spinEnd();
|
||||
};
|
||||
sse.onerror=()=>{ sse.close(); dropped=true; setTimeout(connect,4000); };
|
||||
}
|
||||
connect();
|
||||
loadFeeds();
|
||||
loadFeeds().catch(()=>{});
|
||||
|
||||
@@ -3,16 +3,16 @@ function renderFeed(){
|
||||
paintScanning(); // another feed's page may be the one open now
|
||||
const box=$('#content');
|
||||
box.classList.remove('plain');
|
||||
const v=VIEWS[S.feed];
|
||||
const v=VIEWS[S.feed ?? ''];
|
||||
if(v&&v.url) return renderListed(v);
|
||||
const f=v?null:S.feeds.find(x=>x.id===S.feed);
|
||||
$('#tbRemove').disabled=!f;
|
||||
$<HTMLButtonElement>('#tbRemove').disabled=!f;
|
||||
syncTools(null);
|
||||
if(!v&&!f){ box.innerHTML='<p class="empty">Add a feed to get started.</p>'; $('#count').textContent=''; return; }
|
||||
const name=f?(f.title||f.id):v.title;
|
||||
$('#epSearch').placeholder=`Search ${name}…`;
|
||||
$<HTMLInputElement>('#epSearch').placeholder=`Search ${name}…`;
|
||||
const kids=f?S.feeds.filter(c=>c.group===f.id):[];
|
||||
if(kids.length){ box.classList.add('plain'); renderGroup(f,kids); return; }
|
||||
if(kids.length){ box.classList.add('plain'); renderGroup(f!,kids); return; }
|
||||
const unreadAll=S.feeds.reduce((n,x)=>n+(x.unread||0),0);
|
||||
box.innerHTML = (f ? `
|
||||
<div class="fhead slim">
|
||||
@@ -61,7 +61,7 @@ function renderFeed(){
|
||||
if(f) pane.className='one';
|
||||
pane.innerHTML='<div id="list">'+sortHead()+
|
||||
'<div id="eps"></div></div><div id="files"></div><div id="grab"></div><div id="detail"></div>';
|
||||
$$('.ephead [data-sort]',pane).forEach(b=>b.onclick=()=>sortBy(b.dataset.sort));
|
||||
$$('.ephead [data-sort]',pane).forEach(b=>b.onclick=()=>sortBy(b.dataset.sort!));
|
||||
box.appendChild(pane);
|
||||
pane.style.setProperty('--listh', localStorage.getItem('ipx.listh') || '60%');
|
||||
dragSplit(pane);
|
||||
@@ -69,9 +69,9 @@ function renderFeed(){
|
||||
S.sel=null;
|
||||
showDetail(null);
|
||||
|
||||
$$('#content .acts .btn').forEach(b=>b.onclick=()=>f?feedAction(b.dataset.a,f):allAction(b.dataset.a));
|
||||
$$('#content .acts .btn').forEach(b=>b.onclick=()=>f?feedAction(b.dataset.a!,f):allAction(b.dataset.a!));
|
||||
$$('#content .tabs button').forEach(b=>b.onclick=()=>{
|
||||
S.filter=b.dataset.f; S.offset=0;
|
||||
S.filter=b.dataset.f!; S.offset=0;
|
||||
try{ localStorage.setItem('ipx.filter',S.filter); }catch{}
|
||||
renderFeed(); loadEntries();
|
||||
});
|
||||
@@ -89,7 +89,7 @@ function sortHead(){
|
||||
`${on?`<span class="arr ${S.sort.dir}">${ICON.caret}</span>`:''}</button>`;
|
||||
}).join('')+'<span></span></div>';
|
||||
}
|
||||
function sortBy(col){
|
||||
function sortBy(col: string){
|
||||
const first=['published','size','kept'].includes(col)?'desc':'asc';
|
||||
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{}
|
||||
@@ -99,9 +99,9 @@ function sortBy(col){
|
||||
/// An OPML subscription's page lists the feeds inside it rather than items, but keeps
|
||||
/// every action a normal feed has -- it is still an ordinary feed entry underneath.
|
||||
// A Patreon creator split into its shows is drawn like an OPML, and named for what it is.
|
||||
const isPatreon=f=>/patreon\.com\//.test(f&&f.url||'');
|
||||
const isPatreon=(f: {url: string}|null)=>/patreon\.com\//.test(f&&f.url||'');
|
||||
|
||||
function renderGroup(f,kids){
|
||||
function renderGroup(f: Feed,kids: Feed[]){
|
||||
const unread=kids.reduce((n,c)=>n+c.unread,0);
|
||||
const saved=kids.reduce((n,c)=>n+c.downloaded,0);
|
||||
const gone=kids.filter(c=>c.orphaned).length;
|
||||
@@ -132,10 +132,10 @@ function renderGroup(f,kids){
|
||||
<span style="color:var(--faint);font-size:12.5px">${esc(f.url)}</span>
|
||||
</div>
|
||||
<div class="childlist" id="kidlist"></div>`;
|
||||
$$('#content .acts .btn').forEach(b=>b.onclick=()=>feedAction(b.dataset.a,f));
|
||||
$$('#content .acts .btn').forEach(b=>b.onclick=()=>feedAction(b.dataset.a!,f));
|
||||
wireFailBanner($('#content'),f);
|
||||
const draw=()=>{
|
||||
const q=($('#kidSearch').value||'').trim().toLowerCase();
|
||||
const q=($<HTMLInputElement>('#kidSearch').value||'').trim().toLowerCase();
|
||||
const box=$('#kidlist'); box.innerHTML='';
|
||||
const rows=kids.filter(c=>!q||(c.title||c.id).toLowerCase().includes(q)).sort(unreadFirst);
|
||||
if(!rows.length){ box.innerHTML='<p class="empty">Nothing matches.</p>'; return; }
|
||||
@@ -154,26 +154,30 @@ function renderGroup(f,kids){
|
||||
box.appendChild(el);
|
||||
}
|
||||
};
|
||||
$('#kidSearch').oninput=draw;
|
||||
$<HTMLInputElement>('#kidSearch').oninput=draw;
|
||||
draw();
|
||||
}
|
||||
|
||||
async function feedAction(a,f){
|
||||
if(a==='scan'){ await api('/api/fetch',{method:'POST',body:JSON.stringify({feed:f.id,force:true})}); }
|
||||
async function feedAction(a: string,f: Feed){
|
||||
if(a==='scan'){
|
||||
spinStart(f.id);
|
||||
try{ await api('/api/fetch',{method:'POST',body:JSON.stringify({feed:f.id,force:true})}); }
|
||||
catch(e){ spinEnd(); throw e; }
|
||||
}
|
||||
if(a==='read'){ const r=await api(`/api/feeds/${encodeURIComponent(f.id)}/read-all`,{method:'POST'}); toast(`Marked ${r.marked} read`); await loadFeeds(true); renderFeed(); loadEntries(); }
|
||||
if(a==='rm') removeFeed(f);
|
||||
if(a==='pin'){
|
||||
try{
|
||||
await api(`/api/feeds/${encodeURIComponent(f.id)}`,{method:'PATCH',body:JSON.stringify({pinned:!f.pinned})});
|
||||
await loadFeeds(true); renderFeed();
|
||||
}catch(e){ toast(e.message,true); }
|
||||
}catch(e){ toast(why(e),true); }
|
||||
}
|
||||
if(a==='settings') settingsModal(f);
|
||||
if(a==='share') share(f.title||f.id, f.url, $('#content .acts [data-a="share"]'));
|
||||
if(a==='dl') downloadLatestModal(f);
|
||||
}
|
||||
/// All Subscriptions' own buttons: a feed's, across every feed you read.
|
||||
async function allAction(a){
|
||||
async function allAction(a: string){
|
||||
if(a==='scanall') return scanAll();
|
||||
if(a==='readall'){
|
||||
const n=S.feeds.reduce((k,x)=>k+(x.unread||0),0);
|
||||
@@ -183,7 +187,7 @@ async function allAction(a){
|
||||
try{
|
||||
const r=await api('/api/read-all',{method:'POST'});
|
||||
toast(`Marked ${r.marked} read`); await loadFeeds(true); renderFeed(); loadEntries();
|
||||
}catch(e){ toast(e.message,true); }
|
||||
}catch(e){ toast(why(e),true); }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
/// One feed's row from the server, in place of the old one (or added, for a feed an OPML just
|
||||
/// listed). A scan sends dozens; the list is redrawn once a frame, not once each.
|
||||
let rowsQueued=0;
|
||||
function patchFeed(row){
|
||||
function patchFeed(row: Feed){
|
||||
const i=S.feeds.findIndex(f=>f.id===row.id);
|
||||
if(i<0) S.feeds.push(row); else S.feeds[i]=row;
|
||||
if(!rowsQueued) rowsQueued=requestAnimationFrame(()=>{ rowsQueued=0; renderFeeds(); });
|
||||
@@ -19,58 +19,75 @@ async function loadFeeds(keepSel?: boolean){
|
||||
// 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.feeds.some(f=>f.id===S.feed));
|
||||
selectFeed(known ? S.feed : ':all');
|
||||
selectFeed(known ? S.feed! : ':all');
|
||||
}
|
||||
}
|
||||
// An OPML can hold dozens of feeds; the ones with something new go first. sort is stable, so the
|
||||
// server's alphabetical order still holds within each half.
|
||||
const unreadFirst=(a,b)=>Number(b.unread>0)-Number(a.unread>0);
|
||||
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.
|
||||
const VIEWS={
|
||||
const VIEWS: Record<string,{title: string, icon: string, url?: string, blurb?: string}>={
|
||||
// The Directory holds the most subscribed feeds too, which had a place of their own, Popular (#124).
|
||||
':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.'},
|
||||
':all':{title:'All Subscriptions',icon:ICON.all},
|
||||
};
|
||||
/// Feeds being checked right now, from the event stream: their rows, and the row of a folder
|
||||
/// holding one, carry a spinner.
|
||||
const scanning=new Set<string>();
|
||||
/// Feeds being checked right now, from the event stream, and since when: their rows, and the row
|
||||
/// of a folder holding one, carry a spinner.
|
||||
const scanning=new Map<string, number>();
|
||||
/// A row's spinner takes the place of its unread count, so it waits this long: most feeds are
|
||||
/// checked in a few milliseconds, and each count blinked out and back as its feed went by.
|
||||
const SPIN_AFTER=300;
|
||||
function setScanning(id: string, on: boolean){
|
||||
if(on) scanning.add(id); else scanning.delete(id);
|
||||
if(on){ scanning.set(id,Date.now()); setTimeout(paintScanning,SPIN_AFTER); } else scanning.delete(id);
|
||||
paintScanning();
|
||||
}
|
||||
function paintScanning(){
|
||||
const slow=(id: string)=>scanning.has(id)&&Date.now()-scanning.get(id)!>=SPIN_AFTER;
|
||||
for(const row of $$('#feedlist .feed')){
|
||||
const id=row.dataset.id;
|
||||
const on=scanning.has(id)||S.feeds.some(c=>c.group===id&&scanning.has(c.id));
|
||||
const id=row.dataset.id!;
|
||||
const on=slow(id)||S.feeds.some(c=>c.group===id&&slow(c.id));
|
||||
row.classList.toggle('scanning',on);
|
||||
if(on) row.title='Checking for new items…'; else row.removeAttribute('title');
|
||||
}
|
||||
// The refresh buttons turn while what they check is being checked (#78). On <body>, because
|
||||
// a feed's page is redrawn as its items come in and would take a class on the button with it.
|
||||
const busy=id=>scanning.has(id)||S.feeds.some(c=>c.group===id&&scanning.has(c.id));
|
||||
document.body.classList.toggle('scan-this',busy(S.feed));
|
||||
document.body.classList.toggle('scan-any',S.feeds.some(f=>scanning.has(f.id)));
|
||||
// A feed's button turns on its own page only, wherever the person has gone since pressing it.
|
||||
document.body.classList.toggle('scan-this',spinFeed!==null&&spinFeed===S.feed);
|
||||
}
|
||||
/// The refresh buttons turn from the press until that scan's scan_done (#78, #233). On <body>,
|
||||
/// because a feed's page is redrawn as its items come in and would take a class on the button
|
||||
/// with it. Following the feeds being checked instead, the icon snapped back upright in the gap
|
||||
/// between one feed and the next, many times a second (#231).
|
||||
let spinFeed: string|null=null;
|
||||
function spinStart(feed: string|null){
|
||||
if(feed===null) document.body.classList.add('scan-any');
|
||||
else { spinFeed=feed; paintScanning(); }
|
||||
}
|
||||
/// `only` and `forced` from scan_done: a scheduled scan, or one limited to another feed, leaves
|
||||
/// a pressed button turning, since the scan it asked for is still queued behind it. Nothing
|
||||
/// (an error ended the job) stops them all.
|
||||
function spinEnd(done?: {only: string|null, forced: boolean}){
|
||||
if(!done||done.forced&&done.only==null) document.body.classList.remove('scan-any');
|
||||
if(!done||done.forced&&done.only===spinFeed){ spinFeed=null; paintScanning(); }
|
||||
}
|
||||
|
||||
function renderFeeds(){
|
||||
const q=$('#feedFilter').value.trim().toLowerCase();
|
||||
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.
|
||||
const a=document.activeElement, was=a&&a.closest&&a.closest<HTMLElement>('#feedlist [data-id]');
|
||||
const back=was&&([was.dataset.id,a.classList.contains('chev')] as [string, boolean]);
|
||||
const done=()=>{
|
||||
list.scrollTop=top;
|
||||
const row=back&&list.querySelector(`[data-id="${CSS.escape(back[0])}"]`);
|
||||
if(row) (back[1]&&$('.chev',row)||row).focus();
|
||||
const row=back&&list.querySelector<HTMLElement>(`[data-id="${CSS.escape(back[0])}"]`);
|
||||
if(row) (back[1]&&$('.chev',row)||row as HTMLElement).focus();
|
||||
};
|
||||
// The images already drawn, to go into the rows that replace theirs. Made anew, every icon in
|
||||
// the list went blank and loaded again, once a frame through a check of every feed, as each
|
||||
// feed's new row came in (#134). Matched by their markup, so a changed one is made anew.
|
||||
const drawn=new Map<string,HTMLImageElement[]>();
|
||||
for(const img of $$('img',list)){ const k=img.outerHTML; if(!drawn.has(k)) drawn.set(k,[]); drawn.get(k).push(img); }
|
||||
for(const img of $$<HTMLImageElement>('img',list)){ const k=img.outerHTML; if(!drawn.has(k)) drawn.set(k,[]); drawn.get(k)!.push(img); }
|
||||
list.innerHTML='';
|
||||
const unreadAll=S.feeds.reduce((n,f)=>n+(f.unread||0),0);
|
||||
const places=document.createElement('div');
|
||||
@@ -91,9 +108,9 @@ function renderFeeds(){
|
||||
// Feeds from a subscribed OPML sit under it, so the group reads as one thing. Pinned feeds
|
||||
// go first: a folder with its feeds under it, a feed from inside one lifted out of it.
|
||||
const byId=Object.fromEntries(shown.map(f=>[f.id,f]));
|
||||
const inside=f=>shown.filter(c=>c.group===f.id&&!c.pinned);
|
||||
const inside=(f: Feed)=>shown.filter(c=>c.group===f.id&&!c.pinned);
|
||||
const tops=shown.filter(f=>f.pinned||!(f.group&&byId[f.group]));
|
||||
const order=[];
|
||||
const order: [Feed, number][]=[];
|
||||
for(const f of [...tops.filter(f=>f.pinned),...tops.filter(f=>!f.pinned)]){
|
||||
order.push([f,0]);
|
||||
// A subscription can hold dozens of feeds, so a folder starts closed. Searching
|
||||
@@ -110,14 +127,14 @@ function renderFeeds(){
|
||||
// A subscription holds no entries itself, so its counts are the sum of what is inside --
|
||||
// taken from every feed it holds, not just the ones a filter left showing.
|
||||
const mine=S.feeds.filter(c=>c.group===f.id);
|
||||
const sum=k=>mine.reduce((n,c)=>n+(c[k]||0),0);
|
||||
const sum=(k: 'unread'|'entries'|'downloaded')=>mine.reduce((n,c)=>n+(c[k]||0),0);
|
||||
const [unread,eps,saved]=mine.length
|
||||
? [sum('unread'),sum('entries'),sum('downloaded')]
|
||||
: [f.unread,f.entries,f.downloaded];
|
||||
// A group's own row has no error of its own worth mentioning if the OPML itself
|
||||
// reads fine; it is failing when any feed inside it is. The feed's own page says what
|
||||
// went wrong (failBannerHTML); the list only has to make it findable.
|
||||
const bad=c=>c.failing?.reason||c.last_error;
|
||||
const bad=(c: Feed)=>c.failing?.reason||c.last_error;
|
||||
const err=mine.length ? mine.map(bad).find(Boolean) : bad(f);
|
||||
const nbad=mine.filter(bad).length;
|
||||
const el=document.createElement('div');
|
||||
@@ -143,15 +160,15 @@ function renderFeeds(){
|
||||
(f.orphaned?'<span class="tag" title="No longer listed, kept because it has downloads">Gone</span>':'')+
|
||||
`<span class="badge${unread?'':' zero'}" title="${unread} unread">${unread>999?'999+':unread}</span>`;
|
||||
el.onclick=()=>{ selectFeed(f.id); nav(false); };
|
||||
if(kids) $('.chev',el).onclick=ev=>{ ev.stopPropagation(); toggleGroup(f.id); };
|
||||
if(kids) $('.chev',el).onclick=(ev: Event)=>{ ev.stopPropagation(); toggleGroup(f.id); };
|
||||
for(const img of $$('img',el)){ const was=drawn.get(img.outerHTML)?.shift(); if(was) img.replaceWith(was); }
|
||||
list.appendChild(el);
|
||||
}
|
||||
paintScanning();
|
||||
done();
|
||||
}
|
||||
function selectFeed(id){
|
||||
S.feed=id; S.offset=0; S.sel=null; S.q=''; $('#epSearch').value='';
|
||||
function selectFeed(id: string){
|
||||
S.feed=id; S.offset=0; S.sel=null; S.q=''; $<HTMLInputElement>('#epSearch').value='';
|
||||
try{ localStorage.setItem('ipx.feed',id); }catch{}
|
||||
renderFeeds(); renderFeed(); loadEntries();
|
||||
}
|
||||
@@ -159,15 +176,15 @@ function selectFeed(id){
|
||||
/// A failing feed's error, in plain words with something to do about it, once `failing` is
|
||||
/// set (it has been failing for a day and is a kind worth naming -- see `explain_failure` in
|
||||
/// src/feed.rs). Anything else still shows the raw error, as before.
|
||||
function failBannerHTML(f){
|
||||
function failBannerHTML(f: Feed){
|
||||
if(f.failing) return `<div class="sub" style="color:var(--bad)">${esc(f.failing.reason)}
|
||||
<button type="button" class="btn tiny" data-ffail="unsub">Unsubscribe</button>${
|
||||
f.failing.new_url?` <button type="button" class="btn tiny" data-ffail="newurl">Use the new address</button>`:''}</div>`;
|
||||
if(f.last_error) return `<div class="sub" style="color:var(--bad)">${esc(f.last_error)}</div>`;
|
||||
return '';
|
||||
}
|
||||
function wireFailBanner(box,f){
|
||||
function wireFailBanner(box: ParentNode,f: Feed){
|
||||
const un=$('[data-ffail="unsub"]',box); if(un) un.onclick=()=>removeFeed(f);
|
||||
const nu=$('[data-ffail="newurl"]',box); if(nu) nu.onclick=()=>settingsModal(f,f.failing.new_url);
|
||||
const nu=$('[data-ffail="newurl"]',box); if(nu) nu.onclick=()=>settingsModal(f,f.failing?.new_url??undefined);
|
||||
}
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ document.addEventListener('touchstart', ev => {
|
||||
// back button is never swallowed with it.
|
||||
if(t.clientX < 14 && narrow() && ev.cancelable) ev.preventDefault();
|
||||
}
|
||||
else if(list && list.scrollTop <= 0 && !VIEWS[S.feed]?.url) touch = {x: t.clientX, y: t.clientY, t: Date.now(), pane: 'list', dx: 0, dy: 0};
|
||||
else if(list && list.scrollTop <= 0 && !VIEWS[S.feed ?? '']?.url) touch = {x: t.clientX, y: t.clientY, t: Date.now(), pane: 'list', dx: 0, dy: 0};
|
||||
}, {passive: false});
|
||||
|
||||
document.addEventListener('touchmove', ev => {
|
||||
|
||||
@@ -6,7 +6,7 @@ async function loadEntries(append?: boolean){
|
||||
const p=new URLSearchParams({offset:String(S.offset),limit:String(LIMIT),filter:S.filter,sort:S.sort.col,dir:S.sort.dir});
|
||||
if(S.q) p.set('q',S.q);
|
||||
const asked=performance.now(), seq=++loadSeq;
|
||||
const r=await api(S.feed===':all' ? `/api/entries?${p}`
|
||||
const r: {total: number, entries: Entry[]}=await api(S.feed===':all' ? `/api/entries?${p}`
|
||||
: `/api/feeds/${encodeURIComponent(S.feed)}/entries?${p}`);
|
||||
// Only the latest list counts: marking everything read reloads the All tab, and clicking
|
||||
// Unread straight after could have that answer land last and replace the Unread one.
|
||||
@@ -14,14 +14,14 @@ async function loadEntries(append?: boolean){
|
||||
S.total=r.total;
|
||||
for(const e of r.entries){
|
||||
const w=readWrites.get(readKey(e));
|
||||
if(w && !(w.done<asked)) e.read=w.read;
|
||||
if(w && !(w.done!==undefined&&w.done<asked)) e.read=w.read;
|
||||
}
|
||||
let entries = append ? S.entries.concat(r.entries) : r.entries;
|
||||
// A background scan finishing refreshes the list from the server, which -- on the Unread
|
||||
// tab -- would drop the item you have open the moment reading it took it off the filter.
|
||||
// Keep it until you pick a different one; the next refresh after that no longer protects it.
|
||||
// The items turned past on the way to it are kept too, so a swipe back still finds them.
|
||||
const kept=e=>e.guid===S.sel||turned.has(e.guid);
|
||||
const kept=(e: Entry)=>e.guid===S.sel||turned.has(e.guid);
|
||||
if(S.filter==='unread') entries=entries.filter(e=>!e.read||kept(e));
|
||||
if(!append && S.sel){
|
||||
const gone=S.entries.filter(e=>kept(e)&&!entries.some(n=>n.guid===e.guid));
|
||||
@@ -32,7 +32,7 @@ async function loadEntries(append?: boolean){
|
||||
}
|
||||
function renderEntries(){
|
||||
const box=$('#eps'); if(!box) return;
|
||||
const f=S.feeds.find(x=>x.id===S.feed), v=VIEWS[S.feed];
|
||||
const f=S.feeds.find(x=>x.id===S.feed), v=VIEWS[S.feed ?? ''];
|
||||
const unread=f?f.unread:S.feeds.reduce((n,x)=>n+(x.unread||0),0);
|
||||
$('#count').textContent=
|
||||
`${f?(f.title||f.id):v?v.title:''}: ${S.total} item${S.total===1?'':'s'}, ${unread} unread`;
|
||||
@@ -53,7 +53,7 @@ function renderEntries(){
|
||||
box.appendChild(b);
|
||||
}
|
||||
}
|
||||
function epEl(e){
|
||||
function epEl(e: Entry){
|
||||
// An item may carry several files. The row summarises the one you would act on --
|
||||
// the playable one, else anything already downloaded, else the first -- and says how
|
||||
// many others there are; the pane below lists them all.
|
||||
@@ -78,7 +78,7 @@ function epEl(e){
|
||||
num&&`<span>${num}</span>`,
|
||||
left&&`<span>${left}</span>`,
|
||||
others>0&&`<span>+${others} more file${others===1?'':'s'}</span>`,
|
||||
enc&&enc.deadair>0&&`<span title="DeadAir cut its dead air">${shorter(enc.deadair)}</span>`,
|
||||
enc&&enc.deadair&&enc.deadair>0&&`<span title="DeadAir cut its dead air">${shorter(enc.deadair)}</span>`,
|
||||
enc&&enc.deadair_pending&&DEAD_PENDING,
|
||||
enc&&enc.last_error&&enc.state==='error'&&`<span style="color:var(--bad)">${esc(enc.last_error)}</span>`,
|
||||
].filter(Boolean).join('<span class="dot"></span>')}</div>
|
||||
@@ -97,13 +97,13 @@ function epEl(e){
|
||||
${has?`<button class="iconbtn" data-a="del" title="Delete file" aria-label="Delete file">${ICON.trash}</button>`:''}
|
||||
</div>`;
|
||||
el.onclick=()=>selectEntry(e);
|
||||
$$('button[data-a]',el).forEach(b=>b.onclick=ev=>{ev.stopPropagation();epAction(b.dataset.a,e,el)});
|
||||
$$('button[data-a]',el).forEach(b=>b.onclick=(ev: Event)=>{ev.stopPropagation();epAction(b.dataset.a!,e,el)});
|
||||
return el;
|
||||
}
|
||||
/// Whether the browser can play it. Having a file is not the same as being playable:
|
||||
/// blog feeds put article images in enclosures, and an <audio> element pointed at a JPEG
|
||||
/// is just a broken player.
|
||||
function isPlayable(x){
|
||||
function isPlayable(x: Enclosure|undefined){
|
||||
if(!x || !x.path) return false;
|
||||
const m=(x.mime||'').toLowerCase();
|
||||
if(m.startsWith('audio/')||m.startsWith('video/')) return true;
|
||||
@@ -114,7 +114,7 @@ function isPlayable(x){
|
||||
}
|
||||
|
||||
/// What an enclosure is, for a row that is not media: "image", "pdf", "document".
|
||||
function kindOf(enc){
|
||||
function kindOf(enc: {mime?: string|null, url?: string}){
|
||||
const m=(enc.mime||'').toLowerCase();
|
||||
if(m.startsWith('image/')) return 'image';
|
||||
if(m.startsWith('video/')) return 'video';
|
||||
@@ -128,9 +128,9 @@ function kindOf(enc){
|
||||
/// What a file is, as one icon coloured by whether it is here: green once downloaded, red when
|
||||
/// the download failed, plain otherwise, so a file waiting and one deleted read alike. One icon
|
||||
/// either way keeps the column lined up; the words are in its tooltip.
|
||||
function kindIcon(enc){
|
||||
function kindIcon(enc: Enclosure){
|
||||
const k=kindOf(enc);
|
||||
const i={audio:ICON.audio,video:ICON.video,image:ICON.image,pdf:ICON.doc,torrent:ICON.torrent}[k]||ICON.file;
|
||||
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}, download failed${enc.last_error?': '+enc.last_error:''}`]
|
||||
: ['',k];
|
||||
@@ -138,7 +138,7 @@ function kindIcon(enc){
|
||||
}
|
||||
|
||||
function feedArt(id=S.feed){ const f=S.feeds.find(x=>x.id===id); return f&&f.image; }
|
||||
const feedName=id=>{ const f=S.feeds.find(x=>x.id===id); return f?(f.title||f.id):id; };
|
||||
const feedName=(id: string|null|undefined): string=>{ const f=S.feeds.find(x=>x.id===id); return f?(f.title||f.id):(id??''); };
|
||||
|
||||
/// 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
|
||||
@@ -147,24 +147,24 @@ const feedName=id=>{ const f=S.feeds.find(x=>x.id===id); return f?(f.title||f.id
|
||||
/// 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)=>html
|
||||
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() : '';
|
||||
function entryName(e): {text: string, derived: boolean}{
|
||||
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);
|
||||
if(words){
|
||||
const cut=words.length>120 ? words.slice(0,120).replace(/\s+\S*$/,'')+'…' : words;
|
||||
return {text:cut, derived:true};
|
||||
}
|
||||
const file=((e.enclosures||[])[0]?.url||'').split(/[?#]/)[0].split('/').pop().replace(/\.[a-z0-9]{1,5}$/i,'');
|
||||
const file=((e.enclosures||[])[0]?.url||'').split(/[?#]/)[0].split('/').pop()!.replace(/\.[a-z0-9]{1,5}$/i,'');
|
||||
if(file){ try{ return {text:decodeURIComponent(file), derived:true}; }catch{ return {text:file, derived:true}; } }
|
||||
return {text:[feedName(e.feed_id), dateOf(e.published)].filter(Boolean).join(', '), derived:true};
|
||||
return {text:[feedName(e.feed_id), dateOf(e.published??null)].filter(Boolean).join(', '), derived:true};
|
||||
}
|
||||
|
||||
/// Selecting an item shows it in the pane below, rather than expanding the row.
|
||||
/// Replaces one row with a fresh one, leaving the rest of the list and its scroll alone.
|
||||
function swapRow(e){
|
||||
function swapRow(e: Entry){
|
||||
const row=$(`#eps .ep[data-guid="${CSS.escape(e.guid)}"]`);
|
||||
if(row){ row.replaceWith(epEl(e)); syncPlayButtons(); }
|
||||
}
|
||||
@@ -172,9 +172,9 @@ function swapRow(e){
|
||||
/// Read and unread as this page last set them, and when the server had it. A list asked for
|
||||
/// before then answers with the old state: it put the dot back on an item just read, until
|
||||
/// the next refresh took it off again (loadEntries).
|
||||
const readWrites=new Map();
|
||||
const readKey=e=>e.feed_id+'\n'+e.guid;
|
||||
function setRead(e,read){
|
||||
const readWrites=new Map<string, {read: boolean, done?: number}>();
|
||||
const readKey=(e: Entry)=>e.feed_id+'\n'+e.guid;
|
||||
function setRead(e: Entry,read: boolean){
|
||||
e.read=read;
|
||||
const w: {read: boolean, done?: number}={read}; readWrites.set(readKey(e),w);
|
||||
return api(`/api/entries/${encodeURIComponent(e.feed_id)}/${encodeURIComponent(e.guid)}/flags`,
|
||||
@@ -184,7 +184,7 @@ function setRead(e,read){
|
||||
|
||||
/// Opening an item is reading it. The row is redrawn where it stands rather than the list
|
||||
/// reloaded, so an item does not vanish from under the pointer on the Unread tab.
|
||||
function markRead(e){
|
||||
function markRead(e: Entry){
|
||||
if(e.read) return;
|
||||
setRead(e,true).catch(err=>{ e.read=false; readWrites.delete(readKey(e)); toast(err.message,true); });
|
||||
}
|
||||
@@ -193,7 +193,7 @@ function markRead(e){
|
||||
/// in the list until the reader closes or another item is picked from the list. Dropped as each
|
||||
/// was left, a swipe back had nothing to go back to: the item just read was already gone.
|
||||
const turned=new Set<string>();
|
||||
function dropTurned(keep){
|
||||
function dropTurned(keep: string|null){
|
||||
const gone=S.entries.filter(x=>turned.has(x.guid)&&x.read&&x.guid!==keep);
|
||||
turned.clear();
|
||||
if(!gone.length) return;
|
||||
@@ -201,7 +201,7 @@ function dropTurned(keep){
|
||||
for(const x of gone) $(`#eps .ep[data-guid="${CSS.escape(x.guid)}"]`)?.remove();
|
||||
}
|
||||
|
||||
function selectEntry(e,turning=false){
|
||||
function selectEntry(e: Entry,turning=false){
|
||||
// On the Unread tab the item you were reading goes as you move on, not whenever a refresh
|
||||
// next happens to come along, which left a few read ones in the list for a while.
|
||||
if(S.filter==='unread' && S.sel && S.sel!==e.guid){
|
||||
@@ -217,10 +217,10 @@ function selectEntry(e,turning=false){
|
||||
}
|
||||
|
||||
/// Drag the divider between the item list and the item text.
|
||||
function dragSplit(pane){
|
||||
function dragSplit(pane: HTMLElement){
|
||||
const grab=$('#grab',pane);
|
||||
if(!grab) return;
|
||||
const move=ev=>{
|
||||
const move=(ev: MouseEvent)=>{
|
||||
const box=pane.getBoundingClientRect();
|
||||
const pct=Math.min(80,Math.max(12,((ev.clientY-box.top)/box.height)*100));
|
||||
pane.style.setProperty('--listh',pct.toFixed(1)+'%');
|
||||
@@ -231,7 +231,7 @@ function dragSplit(pane){
|
||||
document.body.style.userSelect='';
|
||||
try{ localStorage.setItem('ipx.listh', pane.style.getPropertyValue('--listh')); }catch{}
|
||||
};
|
||||
grab.onmousedown=ev=>{
|
||||
grab.onmousedown=(ev: MouseEvent)=>{
|
||||
ev.preventDefault();
|
||||
document.body.style.userSelect='none';
|
||||
document.addEventListener('mousemove',move);
|
||||
@@ -243,24 +243,24 @@ function dragSplit(pane){
|
||||
// ponytail: matched by guid alone; two feeds sharing a guid in All Subscriptions would pick
|
||||
// the first. Key rows by feed as well if that ever happens.
|
||||
const cur=()=>S.entries.find(x=>x.guid===S.sel);
|
||||
function syncTools(e){
|
||||
$('#tbPlay').disabled=!(e&&e.enclosures.some(isPlayable));
|
||||
$('#tbRead').disabled=$('#tbFlag').disabled=!e;
|
||||
function syncTools(e: Entry|null){
|
||||
$<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.
|
||||
$('#tbRead').innerHTML=e&&!e.read?ICON.unread:ICON.check;
|
||||
$('#tbRead').setAttribute('aria-pressed',String(!!(e&&e.read)));
|
||||
$('#tbFlag').setAttribute('aria-pressed',String(!!(e&&e.flagged)));
|
||||
$('#tbFlag').innerHTML=e&&e.flagged?ICON.pinOn:ICON.pin;
|
||||
$<HTMLButtonElement>('#tbRead').innerHTML=e&&!e.read?ICON.unread:ICON.check;
|
||||
$<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){
|
||||
$('#tbRead').title=`Mark ${e.read?'unread':'read'}`;
|
||||
$('#tbFlag').title=e.flagged?'Unpin':'Pin, so it is never deleted';
|
||||
$<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.
|
||||
function showDetail(e){
|
||||
function showDetail(e: Entry|null){
|
||||
const box=$('#detail'), files=$('#files'); if(!box) return;
|
||||
// A pane that can only say "No files" gives its width to the list instead.
|
||||
if(files) files.hidden=!(e&&e.enclosures.length);
|
||||
@@ -278,15 +278,15 @@ function showDetail(e){
|
||||
const narrow=!!window.matchMedia?.('(max-width:820px)')?.matches;
|
||||
box.innerHTML=detailHtml(e);
|
||||
if(files) files.innerHTML=narrow?'':`<div class="fhd">Files</div>${encs}`;
|
||||
$('#dback').onclick=()=>showDetail(null);
|
||||
$<HTMLButtonElement>('#dback').onclick=()=>showDetail(null);
|
||||
for(const root of [box,files]) if(root) $$('button[data-a]',root).forEach(b=>
|
||||
b.onclick=()=>epAction(b.dataset.a,e,null,b.dataset.enc?Number(b.dataset.enc):null));
|
||||
b.onclick=()=>epAction(b.dataset.a!,e,null,b.dataset.enc?Number(b.dataset.enc):undefined));
|
||||
syncPlayButtons();
|
||||
}
|
||||
|
||||
/// What the reader shows for an item. Its own function because a phone also draws the next or
|
||||
/// previous item beside the reader while it is swiped (gestures.ts).
|
||||
function detailHtml(e){
|
||||
function detailHtml(e: Entry){
|
||||
const encs=e.enclosures.map(encBox).join('');
|
||||
// A phone has no room for the files pane, so the files go above the text there instead.
|
||||
// Below it, a long set of show notes pushed play and delete screens down, and on an iPhone
|
||||
@@ -317,7 +317,7 @@ function detailHtml(e){
|
||||
}
|
||||
|
||||
/// One enclosure: a play button when the file is here, otherwise what it is and a way to get it.
|
||||
function encBox(x){
|
||||
function encBox(x: Enclosure){
|
||||
const size=x.length?mb(x.length):'';
|
||||
// One file serves everyone reading the feed, so deleting is not a private act.
|
||||
const f=S.feeds.find(y=>y.id===x.feed_id);
|
||||
@@ -328,8 +328,9 @@ function encBox(x){
|
||||
: 'Delete file';
|
||||
const delBtn=`<button class="btn ico danger" data-a="del" data-enc="${x.id}" title="${delLabel}" aria-label="${delLabel}">${ICON.trash}</button>`;
|
||||
// Played without its dead air, so saved without it too (#186).
|
||||
const saveLabel=x.deadair>0?'Save to this computer, without its dead air':'Save to this computer';
|
||||
const saveBtn=`<a class="btn ico" href="/media/${x.id}${x.deadair>0?'/deadair':''}" download title="${saveLabel}" aria-label="${saveLabel}">${ICON.save}</a>`;
|
||||
const dead=(x.deadair??0)>0;
|
||||
const saveLabel=dead?'Save to this computer, without its dead air':'Save to this computer';
|
||||
const saveBtn=`<a class="btn ico" href="/media/${x.id}${dead?'/deadair':''}" download title="${saveLabel}" aria-label="${saveLabel}">${ICON.save}</a>`;
|
||||
// The publisher's address, not this server's copy, which only someone signed in here can open.
|
||||
const shareBtn=`<button class="btn ico" data-a="share" data-enc="${x.id}" title="Share the file" aria-label="Share the file">${ICON.share}</button>`;
|
||||
if(x.path && !isPlayable(x)){
|
||||
@@ -369,14 +370,14 @@ function encBox(x){
|
||||
</div>`;
|
||||
}
|
||||
|
||||
async function epAction(a: string, e, el, encId?: number){
|
||||
async function epAction(a: string, e: Entry, el: HTMLElement|null, encId?: number){
|
||||
// Swap the row in place and refresh the text below when it is the one being read.
|
||||
const redraw=()=>{ swapRow(e); if(!el || S.sel===e.guid) showDetail(e); };
|
||||
const enc=(encId!=null && e.enclosures.find(x=>x.id===encId)) || e.enclosures[0];
|
||||
const path=`/api/entries/${encodeURIComponent(e.feed_id)}/${encodeURIComponent(e.guid)}`;
|
||||
try{
|
||||
if(a==='play') play(e, encId!=null ? enc : undefined);
|
||||
if(a==='share') await share(entryName(e).text, encId!=null ? enc.url : e.link, el);
|
||||
if(a==='share') await share(entryName(e).text, encId!=null ? enc.url : e.link!, el??undefined);
|
||||
if(a==='flag'){ e.flagged=!e.flagged; await api(path+'/flags',{method:'POST',body:JSON.stringify({flagged:e.flagged})}); redraw(); }
|
||||
if(a==='read'){ await setRead(e,!e.read); redraw(); }
|
||||
if(a==='get'){
|
||||
@@ -396,12 +397,12 @@ async function epAction(a: string, e, el, encId?: number){
|
||||
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(err.message)) throw err;
|
||||
if(!confirm(err.message+'\n\nDelete it anyway?')) return;
|
||||
if(!/one copy of this file/.test(why(err))) throw err;
|
||||
if(!confirm(why(err)+'\n\nDelete it anyway?')) return;
|
||||
await api(`/api/enclosures/${enc.id}?force=true`,{method:'DELETE'});
|
||||
}
|
||||
toast('Deleted'); loadEntries(); loadFeeds(true);
|
||||
}
|
||||
}catch(err){ toast(err.message,true); }
|
||||
}catch(err){ toast(why(err),true); }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
document.getElementById('f').onsubmit = async e => {
|
||||
document.getElementById('f')!.onsubmit = async e => {
|
||||
e.preventDefault();
|
||||
const msg = document.getElementById('msg');
|
||||
const msg = document.getElementById('msg')!;
|
||||
msg.textContent = '';
|
||||
const r = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/* ---------------- player ---------------- */
|
||||
const audio=$('#audio');
|
||||
const player: {guid: string|null, feed: string|null, entry: any, enc?: number, src?: string, moved?: boolean,
|
||||
const audio=$<HTMLAudioElement>('#audio');
|
||||
const player: {guid: string|null, feed: string|null, entry: Entry|null, enc?: number, src?: string, moved?: boolean,
|
||||
saveAt: number, marked: boolean}={guid:null,feed:null,entry:null,saveAt:0,marked:false};
|
||||
|
||||
/// Where a file plays from: DeadAir's playlist when the server says this person plays it
|
||||
/// shortened (#171, #181), whose times the entry is already given in, else the file itself.
|
||||
const mediaSrc=enc=>enc.deadair!=null?`/media/${enc.id}/deadair.m3u8`:`/media/${enc.id}`;
|
||||
const mediaSrc=(enc: {id: number, deadair?: number|null})=>enc.deadair!=null?`/media/${enc.id}/deadair.m3u8`:`/media/${enc.id}`;
|
||||
|
||||
/// hls.js, playing DeadAir's playlist where the browser cannot itself. Fetched the first time it
|
||||
/// is needed. Only Apple's browsers play it themselves: Chromium says it can ("maybe"), then fails
|
||||
@@ -31,7 +31,7 @@ function setSrc(url: string): Promise<void>|null{
|
||||
return ready.then(()=>{
|
||||
// Its playlist and audio requests join the trace of the tap that played them (#192).
|
||||
hls=new w.Hls({xhrSetup:(xhr: XMLHttpRequest)=>xhr.setRequestHeader('traceparent',traceparent())});
|
||||
hls.on(w.Hls.Events.ERROR,(_,d)=>{ if(d.fatal){ toast('Playback failed: '+d.details,true);
|
||||
hls.on(w.Hls.Events.ERROR,(_: string,d: {fatal: boolean, type: string, details: string})=>{ if(d.fatal){ toast('Playback failed: '+d.details,true);
|
||||
report('player_error',{msg:`hls.js: ${d.type} ${d.details}`,feed:player.feed,enclosure:player.enc}); } });
|
||||
hls.loadSource(url); hls.attachMedia(audio);
|
||||
});
|
||||
@@ -49,8 +49,8 @@ function markPlayed(){
|
||||
}
|
||||
|
||||
/// Plays one of the item's files in the player bar: the one asked for, or its first playable one.
|
||||
function play(e,enc=e.enclosures.find(isPlayable)){
|
||||
if(!isPlayable(enc)){
|
||||
function play(e: Entry,enc=e.enclosures.find(isPlayable)){
|
||||
if(!enc||!isPlayable(enc)){
|
||||
toast(e.enclosures.some(x=>x.path) ? 'That file is not audio or video' : 'Not downloaded yet', true);
|
||||
return;
|
||||
}
|
||||
@@ -76,17 +76,17 @@ function play(e,enc=e.enclosures.find(isPlayable)){
|
||||
player.marked=false;
|
||||
paintDead();
|
||||
}
|
||||
const go=()=>audio.play().catch(err=>toast('Playback failed: '+err.message,true));
|
||||
const go=()=>audio.play().catch((err: Error)=>toast('Playback failed: '+err.message,true));
|
||||
if(wait) wait.then(go,err=>toast('Playback failed: '+err.message,true)); else go();
|
||||
renderEntries();
|
||||
}
|
||||
function mediaSession(e,f){
|
||||
function mediaSession(e: Entry,f: Feed|undefined){
|
||||
if(!('mediaSession' in navigator)) return;
|
||||
navigator.mediaSession.metadata=new MediaMetadata({
|
||||
title:entryName(e).text, artist:f?(f.title||f.id):'', album:f?(f.title||''):'',
|
||||
artwork:(e.image||(f&&f.image))?[{src:artSrc(e.image||f.image),sizes:'512x512'}]:[],
|
||||
artwork:(e.image||(f&&f.image))?[{src:artSrc((e.image||f?.image)!),sizes:'512x512'}]:[],
|
||||
});
|
||||
const h={play:()=>audio.play(),pause:()=>audio.pause(),
|
||||
const h: Record<string,()=>void>={play:()=>audio.play(),pause:()=>audio.pause(),
|
||||
seekbackward:()=>audio.currentTime-=15,seekforward:()=>audio.currentTime+=30};
|
||||
for(const k in h){ try{navigator.mediaSession.setActionHandler(k as MediaSessionAction,h[k])}catch{} }
|
||||
}
|
||||
@@ -94,7 +94,7 @@ audio.addEventListener('timeupdate',()=>{
|
||||
const d=audio.duration||player.entry?.duration||0;
|
||||
$('#pcur').textContent=clock(audio.currentTime);
|
||||
$('#pdur').textContent=clock(d);
|
||||
if(d) $('#seek').value=String(Math.round(audio.currentTime/d*1000));
|
||||
if(d) $<HTMLInputElement>('#seek').value=String(Math.round(audio.currentTime/d*1000));
|
||||
// Only playing counts as moving: the seek to where you left off happens paused, and saving
|
||||
// that would write back whatever the list said, however old.
|
||||
if(!audio.paused) player.moved=true;
|
||||
@@ -117,29 +117,29 @@ function savePos(){
|
||||
const duration=isFinite(audio.duration)?Math.floor(audio.duration):null;
|
||||
navigator.sendBeacon?.(
|
||||
// A beacon sends no headers, so the trace goes in the address (#192).
|
||||
`/api/entries/${encodeURIComponent(player.feed)}/${encodeURIComponent(player.guid)}/position?traceparent=${traceparent()}`,
|
||||
`/api/entries/${encodeURIComponent(player.feed!)}/${encodeURIComponent(player.guid!)}/position?traceparent=${traceparent()}`,
|
||||
new Blob([JSON.stringify({secs:Math.floor(audio.currentTime),duration})],{type:'application/json'}));
|
||||
}
|
||||
audio.addEventListener('pause',savePos);
|
||||
audio.addEventListener('ended',()=>{savePos();markPlayed();$('#pplay').innerHTML=ICON.play});
|
||||
audio.addEventListener('ended',()=>{savePos();markPlayed();$<HTMLButtonElement>('#pplay').innerHTML=ICON.play});
|
||||
// body.playing is what sets the EQ bars moving.
|
||||
audio.addEventListener('play',()=>{ $('#pplay').innerHTML=ICON.pause; document.body.classList.add('playing'); });
|
||||
audio.addEventListener('pause',()=>{ $('#pplay').innerHTML=ICON.play; document.body.classList.remove('playing'); });
|
||||
audio.addEventListener('play',()=>{ $<HTMLButtonElement>('#pplay').innerHTML=ICON.pause; document.body.classList.add('playing'); });
|
||||
audio.addEventListener('pause',()=>{ $<HTMLButtonElement>('#pplay').innerHTML=ICON.play; document.body.classList.remove('playing'); });
|
||||
for(const ev of ['play','pause','ended']) audio.addEventListener(ev,syncPlayButtons);
|
||||
|
||||
/// Every play button for what is playing shows pause, like the player bar's: a row's, the files
|
||||
/// pane's, the toolbar's. Only the bar's used to change, so the others said play while it played.
|
||||
function syncPlayButtons(){
|
||||
const on=(guid,enc?)=>!audio.paused&&player.guid===guid&&(enc==null||player.enc===enc);
|
||||
const paint=(b,now,idle)=>{
|
||||
const on=(guid: string|null,enc?: number)=>!audio.paused&&player.guid===guid&&(enc==null||player.enc===enc);
|
||||
const paint=(b: HTMLElement,now: boolean,idle: string)=>{
|
||||
const label=now?'Pause':idle;
|
||||
if(b.title===label) return;
|
||||
b.title=label; b.setAttribute('aria-label',label); b.innerHTML=now?ICON.pause:ICON.play;
|
||||
};
|
||||
for(const b of $$('#eps .ep [data-a=play]')) paint(b,on(b.closest('.ep').dataset.guid),'Play');
|
||||
for(const b of $$('#eps .ep [data-a=play]')) paint(b,on(b.closest<HTMLElement>('.ep')!.dataset.guid!),'Play');
|
||||
for(const b of $$('#files [data-a=play][data-enc], #detail [data-a=play][data-enc]'))
|
||||
paint(b,on(S.sel,Number(b.dataset.enc)),'Play');
|
||||
const e=cur(); paint($('#tbPlay'),!!e&&on(e.guid),'Play the selected item');
|
||||
const e=cur(); paint($<HTMLButtonElement>('#tbPlay'),!!e&&on(e.guid),'Play the selected item');
|
||||
}
|
||||
for(const ev of ['play','pause','timeupdate']) audio.addEventListener(ev,syncListening);
|
||||
window.addEventListener('beforeunload',savePos);
|
||||
@@ -157,27 +157,27 @@ audio.addEventListener('playing',()=>{
|
||||
asked=0; waited=0;
|
||||
});
|
||||
audio.addEventListener('error',()=>{ if(audio.error) report('player_error',{msg:`media error ${audio.error.code}: ${audio.error.message}`,...playing()}); });
|
||||
$('#pplay').onclick=()=>audio.paused?audio.play():audio.pause();
|
||||
$('#pback').onclick=()=>audio.currentTime-=15;
|
||||
$('#pfwd').onclick=()=>audio.currentTime+=30;
|
||||
$('#seek').oninput=e=>{const d=audio.duration;if(d)audio.currentTime=d*e.target.value/1000};
|
||||
$('#rate').onchange=e=>{audio.playbackRate=+e.target.value;localStorage.setItem('ipx.rate',e.target.value)};
|
||||
$('#vol').oninput=e=>{audio.volume=e.target.value/100;localStorage.setItem('ipx.vol',e.target.value)};
|
||||
$<HTMLButtonElement>('#pplay').onclick=()=>audio.paused?audio.play():audio.pause();
|
||||
$<HTMLButtonElement>('#pback').onclick=()=>audio.currentTime-=15;
|
||||
$<HTMLButtonElement>('#pfwd').onclick=()=>audio.currentTime+=30;
|
||||
$<HTMLInputElement>('#seek').oninput=(e: Event)=>{const d=audio.duration;if(d)audio.currentTime=d*Number((e.target as HTMLInputElement).value)/1000};
|
||||
$<HTMLSelectElement>('#rate').onchange=(e: Event)=>{audio.playbackRate=+(e.target as HTMLSelectElement).value;localStorage.setItem('ipx.rate',(e.target as HTMLSelectElement).value)};
|
||||
$<HTMLInputElement>('#vol').oninput=(e: Event)=>{audio.volume=Number((e.target as HTMLInputElement).value)/100;localStorage.setItem('ipx.vol',(e.target as HTMLInputElement).value)};
|
||||
/// DeadAir's switch beside the speed: on or off for the show that is playing. The state is in the
|
||||
/// icon's shape and aria-pressed, never a colour.
|
||||
function paintDead(){
|
||||
const b=$('#pdead'), f=S.feeds.find(x=>x.id===player.feed);
|
||||
const b=$<HTMLButtonElement>('#pdead'), f=S.feeds.find(x=>x.id===player.feed);
|
||||
b.hidden=!f||document.body.classList.contains('has-video');
|
||||
if(b.hidden) return;
|
||||
if(!f||b.hidden) return;
|
||||
b.setAttribute('aria-pressed',String(!!f.deadair));
|
||||
b.innerHTML=f.deadair?ICON.deadairOn:ICON.deadair;
|
||||
b.title=f.deadair?'DeadAir is cutting the dead air from this show':'DeadAir: cut the dead air from this show';
|
||||
}
|
||||
$('#pdead').onclick=async()=>{
|
||||
$<HTMLButtonElement>('#pdead').onclick=async()=>{
|
||||
const f=S.feeds.find(x=>x.id===player.feed); if(!f) return;
|
||||
const on=!f.deadair;
|
||||
try{ await api(`/api/feeds/${encodeURIComponent(f.id)}`,{method:'PATCH',body:JSON.stringify({deadair:on})}); }
|
||||
catch(err){ toast(err.message,true); return; }
|
||||
catch(err){ toast(why(err),true); return; }
|
||||
f.deadair=on; paintDead();
|
||||
const switched=await switchVersion();
|
||||
toast(!on?'DeadAir is off for this show':switched?'DeadAir is cutting the dead air from this show'
|
||||
@@ -188,14 +188,14 @@ $('#pdead').onclick=async()=>{
|
||||
/// turned on or off for its show. True if it changed version: a copy not made yet plays next time.
|
||||
async function switchVersion(){
|
||||
if(!player.guid) return false;
|
||||
const [feed,guid]=[player.feed,player.guid].map(encodeURIComponent);
|
||||
const [feed,guid]=[player.feed!,player.guid!].map(s=>encodeURIComponent(s));
|
||||
// Saved and waited for, not beaconed, so the entry asked for next has this place in it.
|
||||
if(audio.readyState){
|
||||
await api(`/api/entries/${feed}/${guid}/position`,{method:'POST',body:JSON.stringify({
|
||||
secs:Math.floor(audio.currentTime),duration:isFinite(audio.duration)?Math.floor(audio.duration):null})}).catch(()=>{});
|
||||
player.moved=false;
|
||||
}
|
||||
const e=await api(`/api/entries/${feed}/${guid}`).catch(()=>null);
|
||||
const e: Entry|null=await api(`/api/entries/${feed}/${guid}`).catch((): null=>null);
|
||||
const enc=e&&e.enclosures.find(x=>x.id===player.enc);
|
||||
if(!enc||mediaSrc(enc)===player.src) return false;
|
||||
const was=!audio.paused;
|
||||
@@ -205,13 +205,13 @@ async function switchVersion(){
|
||||
if(was) (wait||Promise.resolve()).then(()=>audio.play()).catch(()=>{});
|
||||
return true;
|
||||
}
|
||||
$('#pclose').onclick=()=>{savePos();audio.pause();dropHls();audio.removeAttribute('src');player.guid=null;$('#player').classList.remove('on');document.body.classList.remove('has-video');renderEntries();
|
||||
$<HTMLButtonElement>('#pclose').onclick=()=>{savePos();audio.pause();dropHls();audio.removeAttribute('src');player.guid=null;$('#player').classList.remove('on');document.body.classList.remove('has-video');renderEntries();
|
||||
// Called here, not left to the pause event: closing a player already paused fires none.
|
||||
syncListening()};
|
||||
(function restore(){
|
||||
const r=localStorage.getItem('ipx.rate'), v=localStorage.getItem('ipx.vol');
|
||||
if(r){$('#rate').value=r;audio.playbackRate=+r}
|
||||
if(v){$('#vol').value=v;audio.volume=Number(v)/100}
|
||||
if(r){$<HTMLSelectElement>('#rate').value=r;audio.playbackRate=+r}
|
||||
if(v){$<HTMLInputElement>('#vol').value=v;audio.volume=Number(v)/100}
|
||||
})();
|
||||
|
||||
document.addEventListener('keydown',ev=>{
|
||||
@@ -223,34 +223,34 @@ document.addEventListener('keydown',ev=>{
|
||||
if(ev.key===' '&&player.guid){ev.preventDefault();audio.paused?audio.play():audio.pause()}
|
||||
else if(ev.key==='ArrowLeft'&&player.guid){audio.currentTime-=15}
|
||||
else if(ev.key==='ArrowRight'&&player.guid){audio.currentTime+=30}
|
||||
else if(ev.key==='/'){ev.preventDefault();$('#epSearch')?.focus()}
|
||||
else if(ev.key==='/'){ev.preventDefault();$<HTMLInputElement>('#epSearch')?.focus()}
|
||||
else if(!ev.ctrlKey&&!ev.metaKey&&!ev.altKey&&!$('#modal').classList.contains('on')) typed(ev);
|
||||
});
|
||||
|
||||
// Feedly's keys, vim's j and k among them: a letter to move through items or feeds, g and a
|
||||
// letter to go somewhere, ? to list them. None fire with Ctrl, Alt or Cmd held, so the browser's
|
||||
// own shortcuts still work, or while a dialog is open.
|
||||
const GO={a:':all',d:':directory',l:':listening'};
|
||||
const GO: Record<string,string>={a:':all',d:':directory',l:':listening'};
|
||||
let gAt=0;
|
||||
function stepEntry(by){
|
||||
if(VIEWS[S.feed]?.url||!S.entries.length) return;
|
||||
function stepEntry(by: number){
|
||||
if(VIEWS[S.feed ?? '']?.url||!S.entries.length) return;
|
||||
const i=S.entries.findIndex(x=>x.guid===S.sel);
|
||||
const e=S.entries[i<0?0:Math.min(S.entries.length-1,Math.max(0,i+by))];
|
||||
selectEntry(e,true);
|
||||
$(`#eps .ep[data-guid="${CSS.escape(e.guid)}"]`)?.scrollIntoView({block:'nearest'});
|
||||
}
|
||||
function stepFeed(by){
|
||||
function stepFeed(by: number){
|
||||
const rows=$$('#feedlist [data-id]'), i=rows.findIndex(r=>r.dataset.id===S.feed), id=rows[i+by]?.dataset.id;
|
||||
if(!id) return;
|
||||
selectFeed(id);
|
||||
$(`#feedlist [data-id="${CSS.escape(id)}"]`)?.scrollIntoView({block:'nearest'});
|
||||
}
|
||||
const KEYS={
|
||||
const KEYS: Record<string,()=>void>={
|
||||
j:()=>stepEntry(1), n:()=>stepEntry(1), k:()=>stepEntry(-1), p:()=>stepEntry(-1),
|
||||
J:()=>stepFeed(1), K:()=>stepFeed(-1),
|
||||
// The toolbar's own buttons, so a key does exactly what the click does, and nothing while
|
||||
// they are disabled.
|
||||
o:()=>$('#tbPlay').click(), m:()=>$('#tbRead').click(), s:()=>$('#tbFlag').click(),
|
||||
o:()=>$<HTMLButtonElement>('#tbPlay').click(), m:()=>$<HTMLButtonElement>('#tbRead').click(), s:()=>$<HTMLButtonElement>('#tbFlag').click(),
|
||||
v:()=>{ const e=cur(); if(e&&e.link) window.open(e.link,'_blank','noopener'); },
|
||||
A:()=>$('#content .fhead [data-a="read"], #content .fhead [data-a="readall"]')?.click(),
|
||||
r:async()=>{ await loadFeeds(true); if(S.feed){ renderFeed(); loadEntries(); } },
|
||||
@@ -259,7 +259,7 @@ const KEYS={
|
||||
'?':()=>keysModal(),
|
||||
g:()=>{ gAt=Date.now(); },
|
||||
};
|
||||
function typed(ev){
|
||||
function typed(ev: KeyboardEvent){
|
||||
// The second key of a g pair counts only if it follows within a second and a half.
|
||||
const pair=Date.now()-gAt<1500; gAt=0;
|
||||
const fn=pair ? (GO[ev.key]&&(()=>selectFeed(GO[ev.key])))||(ev.key==='s'&&prefsModal) : KEYS[ev.key];
|
||||
@@ -268,7 +268,7 @@ function typed(ev){
|
||||
}
|
||||
/// What ? shows: every key, grouped as Feedly's own list is.
|
||||
function keysModal(){
|
||||
const k=s=>`<kbd>${esc(s)}</kbd>`, g=c=>k('g')+' '+k(c);
|
||||
const k=(s: string)=>`<kbd>${esc(s)}</kbd>`, g=(c: string)=>k('g')+' '+k(c);
|
||||
const rows=[
|
||||
['Go to'],
|
||||
[g('a'),'All Subscriptions'],[g('d'),'Directory'],
|
||||
|
||||
@@ -37,13 +37,13 @@ function setTheme(name = theme.name, mode = theme.mode, save = false){
|
||||
root.dataset.mode = !both ? 'light'
|
||||
: theme.mode === 'auto' ? (systemDark && !systemDark.matches ? 'light' : 'dark') : theme.mode;
|
||||
// The tab's icon in the same variant as the logo on the page.
|
||||
const fav = $('#favicon'); if(fav) fav.href = fav.dataset[root.dataset.mode];
|
||||
const fav = $<HTMLLinkElement>('#favicon'); if(fav) fav.href = fav.dataset[root.dataset.mode!]!;
|
||||
// The top bar's colour for an iPhone before iOS 26 to paint behind the status bar, as Android's
|
||||
// toolbar does; the page's where the bar is see-through (Glass). iOS 26 reads the bar itself.
|
||||
const tc = $('meta[name=theme-color]'), bar = $('#topbar');
|
||||
const tc = $<HTMLMetaElement>('meta[name=theme-color]'), bar = $('#topbar');
|
||||
if(tc){ const c = bar ? getComputedStyle(bar).backgroundColor : ''; tc.content = /^rgb\(/.test(c) ? c : getComputedStyle(root).backgroundColor; }
|
||||
const sel = $('#stheme'); if(sel) sel.value = theme.name;
|
||||
const ms = $('#smode'); if(ms) ms.value = theme.mode;
|
||||
const sel = $<HTMLSelectElement>('#stheme'); if(sel) sel.value = theme.name;
|
||||
const ms = $<HTMLSelectElement>('#smode'); if(ms) ms.value = theme.mode;
|
||||
const mf = $('#smodefield'); if(mf) mf.hidden = !both;
|
||||
if(save) saveTheme();
|
||||
}
|
||||
@@ -62,6 +62,6 @@ systemDark?.addEventListener?.('change', () => { if(theme.mode === 'auto') setTh
|
||||
// becomes its cookie, once.
|
||||
let name: string | null = null, mode: string | null = null;
|
||||
try{ name = localStorage.getItem('ipx.theme'); mode = localStorage.getItem('ipx.mode'); }catch{}
|
||||
if(OLD_THEMES[name]) [name, mode] = OLD_THEMES[name];
|
||||
if(name&&OLD_THEMES[name]) [name, mode] = OLD_THEMES[name];
|
||||
setTheme(name ?? undefined, mode ?? undefined, !!name);
|
||||
})();
|
||||
|
||||
153
web/src/types.ts
Normal file
153
web/src/types.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
// What ipx's API sends the page, as types for the type-check (#235), each named after the Rust
|
||||
// struct it mirrors in crates/ipx/src. Types only: swc strips this file to nothing, so it is not
|
||||
// in web/build.mjs's list; tsconfig.json's glob reads it. A field added there goes here too.
|
||||
// An Option is `T | null`, as serde writes None.
|
||||
|
||||
/// A feed in your list, `/api/feeds` and the live `feed_row` (web.rs FeedRow).
|
||||
interface Feed {
|
||||
id: string;
|
||||
url: string;
|
||||
title: string | null;
|
||||
image: string | null;
|
||||
folder: string | null;
|
||||
category: string | null;
|
||||
feed_category: string | null;
|
||||
keywords: string[];
|
||||
blocked: string[];
|
||||
deadair: boolean;
|
||||
deadair_pause: number;
|
||||
allow_explicit: boolean;
|
||||
auto_download: boolean;
|
||||
max_new_per_check: number | null;
|
||||
/// The OPML subscription it came from.
|
||||
group: string | null;
|
||||
orphaned: boolean;
|
||||
managed: boolean;
|
||||
schedule: string | null;
|
||||
schedule_mins: number | null;
|
||||
every_mins: number;
|
||||
last_checked: number | null;
|
||||
next_check: number | null;
|
||||
last_error: string | null;
|
||||
failing: {reason: string, new_url: string | null} | null;
|
||||
entries: number;
|
||||
downloaded: number;
|
||||
unread: number;
|
||||
subscribers: number;
|
||||
pinned: boolean;
|
||||
private: boolean;
|
||||
private_by_address: boolean;
|
||||
}
|
||||
|
||||
/// An item, in a page of `/api/entries` (db.rs EntryRow).
|
||||
interface Entry {
|
||||
guid: string;
|
||||
feed_id: string;
|
||||
title: string | null;
|
||||
link: string | null;
|
||||
published: number | null;
|
||||
description: string | null;
|
||||
read: boolean;
|
||||
flagged: boolean;
|
||||
image: string | null;
|
||||
duration: number | null;
|
||||
episode: number | null;
|
||||
season: number | null;
|
||||
position: number;
|
||||
enclosures: Enclosure[];
|
||||
}
|
||||
|
||||
/// An item's file (db.rs EncRow).
|
||||
interface Enclosure {
|
||||
id: number;
|
||||
/// Seconds DeadAir's copy saves, when you play it from one.
|
||||
deadair?: number | null;
|
||||
deadair_pending?: boolean;
|
||||
feed_id: string;
|
||||
guid: string;
|
||||
url: string;
|
||||
mime: string | null;
|
||||
length: number | null;
|
||||
path: string | null;
|
||||
state: string;
|
||||
last_error: string | null;
|
||||
}
|
||||
|
||||
/// `/api/me`.
|
||||
interface Me {
|
||||
name: string;
|
||||
admin: boolean;
|
||||
sign_out: string;
|
||||
blocked: string[];
|
||||
deadair_saved: number;
|
||||
theme: {name: string, mode: string} | null;
|
||||
version: string;
|
||||
}
|
||||
|
||||
/// A feed as the Directory lists it (web.rs PopularRow): never its address.
|
||||
interface DirFeed {
|
||||
id: string;
|
||||
title: string | null;
|
||||
image: string | null;
|
||||
subscribers: number;
|
||||
subscribed: boolean;
|
||||
/// Its id in your list, when it is yours.
|
||||
feed: string | null;
|
||||
category: string | null;
|
||||
subcategory: string | null;
|
||||
podcast: boolean;
|
||||
}
|
||||
|
||||
/// The page's own state (util.ts `S`).
|
||||
interface State {
|
||||
feeds: Feed[];
|
||||
/// The feed or place open: a feed's id, or a view such as ':all'.
|
||||
feed: string | null;
|
||||
entries: Entry[];
|
||||
total: number;
|
||||
offset: number;
|
||||
filter: string;
|
||||
q: string;
|
||||
/// The selected item's guid.
|
||||
sel: string | null;
|
||||
me: Me | null;
|
||||
sort: {col: string, dir: 'asc' | 'desc'};
|
||||
}
|
||||
|
||||
/// An account, `/api/users` (web.rs list_users).
|
||||
interface Account {
|
||||
id: number;
|
||||
name: string;
|
||||
admin: boolean;
|
||||
/// Has a password; none signs in through the proxy.
|
||||
password: boolean;
|
||||
created: number | null;
|
||||
last_login: number | null;
|
||||
}
|
||||
|
||||
/// A line of the daemon's log, `/api/logs` (logbuf.rs LogLine).
|
||||
interface LogLine {
|
||||
seq: number;
|
||||
ts: number;
|
||||
level: string;
|
||||
target: string;
|
||||
msg: string;
|
||||
}
|
||||
|
||||
/// `/api/directory-admin`: the servers sharing with the directory and the feeds it blocks
|
||||
/// (directory lib.rs Instance, Blocked).
|
||||
interface DirAdmin {
|
||||
instances: {name: string, feeds: number, subscribers: number}[];
|
||||
blocked: {id: string, url: string | null, title: string | null, at: number}[];
|
||||
}
|
||||
|
||||
/// One of a listed feed's latest items, on its page in the Directory (web.rs ListedItem): never
|
||||
/// its files.
|
||||
interface ListedItem {
|
||||
guid: string;
|
||||
title: string | null;
|
||||
link: string | null;
|
||||
published: number | null;
|
||||
duration: number | null;
|
||||
description: string | null;
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
'use strict';
|
||||
// `any`: the page reads .value, .dataset and .onclick off whatever it looks up, and the
|
||||
// smoke test, not the type checker, is what makes sure a selector exists.
|
||||
const $ = (s: string, r: ParentNode = document): any => r.querySelector(s);
|
||||
const $$ = (s: string, r: ParentNode = document): any[] => [...r.querySelectorAll(s)];
|
||||
const esc = s => (s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const $ = <T extends HTMLElement = HTMLElement>(s: string, r: ParentNode = document): T => r.querySelector<T>(s)!;
|
||||
const $$ = <T extends HTMLElement = HTMLElement>(s: string, r: ParentNode = document): T[] => [...r.querySelectorAll<T>(s)];
|
||||
/// What went wrong, from whatever a catch caught: the page throws Errors, but a catch cannot know.
|
||||
const why = (e: unknown): string => e instanceof Error ? e.message : String(e);
|
||||
const ESCAPED: Record<string,string> = {'&':'&','<':'<','>':'>','"':'"',"'":'''};
|
||||
const esc = (s: string|null|undefined) => (s??'').replace(/[&<>"']/g,c=>ESCAPED[c]);
|
||||
// Icons: Font Awesome Free 7.3.1 by @fontawesome - https://fontawesome.com
|
||||
// License - https://fontawesome.com/license/free (Icons: CC BY 4.0). Embedded as SVG, only the
|
||||
// ones used, so there is no font to download and nothing is fetched from anyone else. Each takes
|
||||
// the button's own colour. To add one, copy the path from svgs/<style>/<name>.svg at the same tag.
|
||||
const fa=(box,body)=>`<svg class="i" viewBox="${box}" aria-hidden="true">${body}</svg>`;
|
||||
const ICON={
|
||||
const fa=(box: string,body: string)=>`<svg class="i" viewBox="${box}" aria-hidden="true">${body}</svg>`;
|
||||
const ICON: Record<string,string>={
|
||||
share:fa('0 0 512 512','<path fill="currentColor" d="M384 192c53 0 96-43 96-96s-43-96-96-96-96 43-96 96c0 5.4 .5 10.8 1.3 16L159.6 184.1c-16.9-15-39.2-24.1-63.6-24.1-53 0-96 43-96 96s43 96 96 96c24.4 0 46.6-9.1 63.6-24.1L289.3 400c-.9 5.2-1.3 10.5-1.3 16 0 53 43 96 96 96s96-43 96-96-43-96-96-96c-24.4 0-46.6 9.1-63.6 24.1L190.7 272c.9-5.2 1.3-10.5 1.3-16s-.5-10.8-1.3-16l129.7-72.1c16.9 15 39.2 24.1 63.6 24.1z"/>'), // solid/share-nodes
|
||||
plus:fa('0 0 448 512','<path fill="currentColor" d="M256 64c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 160-160 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l160 0 0 160c0 17.7 14.3 32 32 32s32-14.3 32-32l0-160 160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-160 0 0-160z"/>'), // solid/plus
|
||||
circleMinus:fa('0 0 512 512','<path fill="currentColor" d="M512 256A256 256 0 1 0 0 256a256 256 0 1 0 512 0zM184 232l144 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-144 0c-13.3 0-24-10.7-24-24s10.7-24 24-24z"/>'), // solid/circle-minus, for Unsubscribe
|
||||
@@ -58,25 +61,32 @@ const EQ='<span class="eq" aria-hidden="true"><i></i><i></i><i></i></span>';
|
||||
// One meaning per icon: minus unsubscribes, x closes or cancels, plus adds or subscribes, and a
|
||||
// dialog's confirm button carries the icon of what it does. Words go in the tooltip.
|
||||
// The page's own buttons name their icon; this draws it in, ahead of any label they carry.
|
||||
for(const b of $$('[data-icon]')) b.insertAdjacentHTML('afterbegin',ICON[b.dataset.icon]);
|
||||
for(const b of $$('[data-icon]')) b.insertAdjacentHTML('afterbegin',ICON[b.dataset.icon!]);
|
||||
|
||||
/// An episode whose DeadAir copy is still being made: it plays as it is until then, and the line
|
||||
/// becomes how much shorter it is once the copy is ready (the dead_air event).
|
||||
const DEAD_PENDING='<span class="dapend" title="DeadAir is still working on this episode. Until it is done, it plays at its full length.">Cutting dead air…</span>';
|
||||
/// What DeadAir took off an episode, as the list says it.
|
||||
function shorter(secs){ return secs<60?`${secs} s shorter`:`${Math.round(secs/60)} min shorter`; }
|
||||
function shorter(secs: number){ return secs<60?`${secs} s shorter`:`${Math.round(secs/60)} min shorter`; }
|
||||
/// A total of time saved: "3 h 12 min", "12 min", "40 s".
|
||||
function spanText(secs){
|
||||
function spanText(secs: number){
|
||||
const h=Math.floor(secs/3600), m=Math.floor(secs%3600/60);
|
||||
return h?`${h} h ${m} min`:m?`${m} min`:`${secs} s`;
|
||||
}
|
||||
/// One trace for each thing you do (#190): the requests a tap or a key sets off share a trace id,
|
||||
/// sent as traceparent, so Tempo shows them together. getRandomValues, not randomUUID, which a
|
||||
/// LAN address over plain HTTP does not have.
|
||||
let traceId='';
|
||||
/// LAN address over plain HTTP does not have. A trace ends after a minute with no request in it:
|
||||
/// the requests a live update or a woken laptop sets off hours later used to join the last tap's
|
||||
/// trace, which then lasted nine hours (#219). A play's position saves, every ten seconds, keep it.
|
||||
let traceId='', traceAt=0;
|
||||
const hex=(n: number)=>Array.from(crypto.getRandomValues(new Uint8Array(n)),b=>b.toString(16).padStart(2,'0')).join('');
|
||||
for(const t of ['pointerdown','keydown']) window.addEventListener(t,()=>{ traceId=hex(16); },{capture:true,passive:true});
|
||||
function traceparent(){ return `00-${traceId||=hex(16)}-${hex(8)}-01`; }
|
||||
for(const t of ['pointerdown','keydown']) window.addEventListener(t,()=>{ traceId=hex(16); traceAt=Date.now(); },{capture:true,passive:true});
|
||||
function traceparent(){
|
||||
const now=Date.now();
|
||||
if(!traceId||now-traceAt>60_000) traceId=hex(16);
|
||||
traceAt=now;
|
||||
return `00-${traceId}-${hex(8)}-01`;
|
||||
}
|
||||
|
||||
/// Something that went wrong, or how long something took, in the browser, for the server's log
|
||||
/// (#190). The same thing at most once a minute: a failure in a loop would otherwise send a line
|
||||
@@ -95,13 +105,15 @@ window.addEventListener('unhandledrejection',e=>report('rejection',{msg:String(e
|
||||
async function api(url: string, opts?: RequestInit): Promise<any>{
|
||||
const r = await fetch(url,{headers:{'Content-Type':'application/json',traceparent:traceparent()},...opts});
|
||||
if(r.status===401){ location.href='/login'; throw new Error('signed out'); }
|
||||
if(!r.ok) throw new Error(await r.text().catch(()=>'')||String(r.status));
|
||||
return r.status===204?null:r.json().catch(()=>null);
|
||||
// A page in place of ipx's words is Cloudflare or Caddy answering for it: the message became a
|
||||
// whole 502 page (#219).
|
||||
if(!r.ok) throw new Error((!/html/.test(r.headers.get('Content-Type')||'')&&await r.text().catch(()=>''))||`${r.status} ${r.statusText}`.trim());
|
||||
return r.status===204?null:r.json().catch((): null=>null);
|
||||
}
|
||||
// navigator.clipboard only exists in a secure context. Served over plain HTTP on a LAN
|
||||
// address it is undefined, so fall back to the old selection-based copy.
|
||||
async function copyText(text,btn){
|
||||
const flash=ok=>{
|
||||
async function copyText(text: string,btn?: HTMLElement){
|
||||
const flash=(ok: boolean)=>{
|
||||
if(!btn) return;
|
||||
// The button is an icon, so it is the markup that has to come back, not just its text.
|
||||
const was=btn.innerHTML;
|
||||
@@ -135,14 +147,14 @@ async function copyText(text,btn){
|
||||
///
|
||||
/// ponytail: a guess from the address. A private feed whose key has another name is shared
|
||||
/// without asking; add its pattern here when one turns up.
|
||||
async function share(title: string, url: string, btn?){
|
||||
async function share(title: string, url: string, btn?: HTMLElement){
|
||||
if(/patreon\.com\/|\/\/[^/]*@|[?&][^=]*(auth|token|key|secret|pass|sig)[^=]*=/i.test(url)
|
||||
&& !confirm('This address looks like it includes your own access to the feed, and anyone you '
|
||||
+'send it to could use it as you.\n\nShare it anyway?')) return;
|
||||
if(navigator.share){
|
||||
// Cancelling the sheet rejects too, and is not a failure worth a word.
|
||||
try{ await navigator.share({title, url}); }
|
||||
catch(e){ if(e.name!=='AbortError') toast(e.message,true); }
|
||||
catch(e){ if((e as Error)?.name!=='AbortError') toast(why(e),true); }
|
||||
return;
|
||||
}
|
||||
await copyText(url,btn);
|
||||
@@ -155,12 +167,12 @@ function toast(msg: string, bad?: boolean){
|
||||
$('#toasts').appendChild(t);
|
||||
setTimeout(()=>{t.style.opacity='0';t.style.transition='opacity .3s';setTimeout(()=>t.remove(),320)},bad?6000:3200);
|
||||
}
|
||||
const clock = s => {
|
||||
const clock = (s: number) => {
|
||||
s=Math.max(0,Math.floor(s||0));
|
||||
const h=Math.floor(s/3600),m=Math.floor(s%3600/60),x=s%60;
|
||||
return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`;
|
||||
};
|
||||
const ago = t => {
|
||||
const ago = (t: number|null) => {
|
||||
if(!t) return 'never';
|
||||
const d=(Date.now()/1000)-t;
|
||||
if(d<3600) return Math.max(1,Math.round(d/60))+'m ago';
|
||||
@@ -168,16 +180,16 @@ const ago = t => {
|
||||
if(d<2592000) return Math.round(d/86400)+'d ago';
|
||||
return new Date(t*1000).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'});
|
||||
};
|
||||
const dateOf = t => t?new Date(t*1000).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'}):'';
|
||||
const dateOf = (t: number|null) => t?new Date(t*1000).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'}):'';
|
||||
// A podcast episode is tens of MB, an article's image a few KB: whole MB made the small ones "0 MB".
|
||||
const mb = n => !n?'' : n<1048576?Math.max(1,Math.round(n/1024))+' KB'
|
||||
const mb = (n: number|null) => !n?'' : n<1048576?Math.max(1,Math.round(n/1024))+' KB'
|
||||
: n<1073741824?Math.round(n/1048576)+' MB' : (n/1073741824).toFixed(1)+' GB';
|
||||
const initials = s => (s||'?').replace(/[^A-Za-z0-9 ]/g,'').split(/\s+/).filter(Boolean).slice(0,2).map(w=>w[0]).join('').toUpperCase()||'?';
|
||||
const plural=(n,word)=>`${n} ${word}${n===1?'':'s'}`;
|
||||
const initials = (s: string|null) => (s||'?').replace(/[^A-Za-z0-9 ]/g,'').split(/\s+/).filter(Boolean).slice(0,2).map(w=>w[0]).join('').toUpperCase()||'?';
|
||||
const plural=(n: number,word: string)=>`${n} ${word}${n===1?'':'s'}`;
|
||||
// An initials tile takes one of these, by a hash of the name, so neighbours rarely match.
|
||||
const TINTS=['var(--accent)','var(--good)','var(--dim)','color-mix(in srgb,var(--accent),var(--good))'];
|
||||
const tint=name=>{ let h=0; for(const c of name||'?') h=(h*31+c.charCodeAt(0))>>>0; return TINTS[h%TINTS.length]; };
|
||||
function tileHTML(name,cls){
|
||||
const tint=(name: string)=>{ let h=0; for(const c of name||'?') h=(h*31+c.charCodeAt(0))>>>0; return TINTS[h%TINTS.length]; };
|
||||
function tileHTML(name: string,cls?: string){
|
||||
return `<div class="art ini ${cls||''}" style="--tint:${tint(name)}">${esc(initials(name))}</div>`;
|
||||
}
|
||||
/// Every image a feed names comes from iPX, which keeps a copy: fast after the first time, and
|
||||
@@ -186,25 +198,25 @@ function tileHTML(name,cls){
|
||||
function artSrc(url: string){
|
||||
return /^https?:\/\//i.test(url) ? '/api/art?u='+encodeURIComponent(url) : url;
|
||||
}
|
||||
function artHTML(url: string | null, name: string, cls?: string){
|
||||
function artHTML(url: string | null | undefined, name: string, cls?: string){
|
||||
return url
|
||||
? `<img class="art ${cls||''}" src="${esc(artSrc(url))}" alt="" loading="lazy" onerror="this.outerHTML=${esc(JSON.stringify(tileHTML(name,cls)))}">`
|
||||
: tileHTML(name,cls);
|
||||
}
|
||||
/// A folder's tile is its first four shows' art. With fewer than four to show, the folder's own.
|
||||
function folderArt(f,kids){
|
||||
function folderArt(f: Feed,kids: Feed[]){
|
||||
const art=kids.filter(c=>c.image).slice(0,4);
|
||||
if(art.length<4) return artHTML(f.image,f.title||f.id);
|
||||
// Tinted underneath, so art that fails to load leaves colour behind rather than a hole.
|
||||
return `<div class="art ini mosaic" style="--tint:${tint(f.title||f.id)}">${art.map(c=>
|
||||
`<img src="${esc(artSrc(c.image))}" alt="" loading="lazy" onerror="this.style.visibility='hidden'">`).join('')}</div>`;
|
||||
`<img src="${esc(artSrc(c.image!))}" alt="" loading="lazy" onerror="this.style.visibility='hidden'">`).join('')}</div>`;
|
||||
}
|
||||
|
||||
/// The sidebar slides over the page on a phone, so it needs a scrim to tap away.
|
||||
function nav(on){ $('#sidebar').classList.toggle('open',on); $('#scrim').hidden=!on; }
|
||||
function nav(on: boolean){ $('#sidebar').classList.toggle('open',on); $('#scrim').hidden=!on; }
|
||||
|
||||
/* ---------------- state ---------------- */
|
||||
const S = {
|
||||
const S: State = {
|
||||
feeds:[],
|
||||
// Which feed (or place) and which tab were open last time, so a refresh lands back where
|
||||
// you were instead of jumping to the first feed alphabetically.
|
||||
@@ -213,25 +225,25 @@ const S = {
|
||||
filter:(()=>{ try{ return localStorage.getItem('ipx.filter'); }catch{ return null; } })()||'all',
|
||||
q:'', sel:null, me:null,
|
||||
// The item table's order, kept across visits. The server sorts: a list arrives fifty at a time.
|
||||
sort:(()=>{ try{ return JSON.parse(localStorage.getItem('ipx.sort')); }catch{ return null; } })()
|
||||
sort:(()=>{ try{ return JSON.parse(localStorage.getItem('ipx.sort')??'null'); }catch{ return null; } })()
|
||||
||{col:'published',dir:'desc'},
|
||||
};
|
||||
const LIMIT = 50;
|
||||
|
||||
const UNITS = [['m','minutes'],['h','hours'],['d','days'],['w','weeks']];
|
||||
const UNIT_MINS = {m:1, h:60, d:1440, w:10080};
|
||||
const UNIT_MINS: Record<string,number> = {m:1, h:60, d:1440, w:10080};
|
||||
|
||||
/// Largest unit that divides evenly, so 120 reads "2 hours" not "120 minutes".
|
||||
function splitEvery(m){
|
||||
function splitEvery(m: number){
|
||||
if(!m) return {n:1, u:'h'};
|
||||
for(const u of ['w','d','h']) if(m % UNIT_MINS[u] === 0) return {n:m/UNIT_MINS[u], u};
|
||||
return {n:m, u:'m'};
|
||||
}
|
||||
function unitOptions(sel){
|
||||
function unitOptions(sel: string){
|
||||
return UNITS.map(([v,l]) =>
|
||||
`<option value="${v}"${sel===v?' selected':''}>${l}</option>`).join('');
|
||||
}
|
||||
function everyText(m){
|
||||
function everyText(m: number){
|
||||
if(!m) return '\u2014';
|
||||
const {n,u} = splitEvery(m);
|
||||
const name = {m:'min', h:'hour', d:'day', w:'week'}[u];
|
||||
|
||||
Reference in New Issue
Block a user