45 Commits

Author SHA1 Message Date
4421d1d083 A season's download sits on the picker's row (#482)
On a phone, on a row of its own under the picker, it cost a line above
the list for one button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 09:24:21 -05:00
c441215c62 A seasoned podcast runs in its own order, and a season downloads whole (#482)
Asked for on the issue: lowest to highest, by season and then episode,
and a way to download every episode of a season.

sort=episode orders by season, episode, then date, with the episodes in
none last either way round; a podcast told in seasons opens in it until a
heading is clicked, and its seasons are offered lowest first.
download-latest takes a season and queues every file of it not on iPX,
first episode first, up to 300; the page asks first, since a season can
be gigabytes. The picked season scrolls into view in the picker, and the
count under the list is the season's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 09:21:50 -05:00
4eb6fbb286 The app's wire code has the seasons' messages (#482)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 09:05:47 -05:00
a57820a078 A podcast told in seasons can be listed one season at a time (#482)
GET /api/feeds/{id}/seasons counts a podcast's episodes and unread by
season, from the same FROM as its list, so a count is what picking it
shows; season= on its entries narrows the list to one, or to the
episodes naming none. The page puts the seasons under the tabs, as the
tabs' own track, when a podcast is told in them: two or more, holding
most of its episodes. That leaves out Ken and Robin, whose "seasons" are
years on a quarter of 767 episodes, and The Vintage RPG Podcast's 2 of
366. Listed all together by date, a heading marks where each season
starts.

A fixture podcast in seasons is in the browser suite, which now
configures six feeds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 09:04:57 -05:00
9ece0ff17c Podcasts sort with a leading "A" or "An" set aside too (#481)
A Question of Science files under Q, as The Rest Is Science does under R.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 08:48:47 -05:00
8512851e4b Podcasts sort by name with a leading "The" set aside (#481)
The feed list, the Podcasts shelf and the playlist dialog took the
server's order, which is by id, a slug of the title, so The Rest Is
Science was under T; the Directory sorted by title the same way. One
helper, nameOrder, now orders names with a leading "The" aside, case and
accents aside and numbers by value. renderFeeds sorts S.feeds with it, so
a feed a live update adds or renames takes its place as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 08:41:24 -05:00
aba6bd52a7 A pinned item's pin keeps its accent disc in the reader's floating actions (#480)
On a phone the floating actions (#456) make every button transparent so
the frosted capsule shows through. That outranked the pinned button's
accent background but not its colour, --ink, so the pin was drawn white
on a light theme's capsule. Pinned keeps its accent there now.

The #456 browser test checks the pinned button's background, and names
the actions it expects instead of counting them: since Up Next an
episode has a fourth, and the count passed only when the tests before
it left an item without audio first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 08:36:32 -05:00
7a059f4460 The app's wire code has Up Next's, playlists' and the shelf's messages (#473, #474, #476)
ipx.proto gained FeedRow.podcast, the playlist messages and Up Next's
queue on the listening branch without ios/scripts/proto.sh being run,
since this machine had no generator. It has one now: protoc from apt and
protoc-gen-swift 1.41.0 built from source in Swift's image, both in
/src/install.sh. directory.pb.swift comes out byte for byte as the Mac
made it, so the Linux build of the generator writes the same code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 08:06:38 -05:00
279510c1f3 Merge branch 'listening' 2026-11-19 07:54:43 -05:00
4120bcd369 Subscriptions to a feed no longer in the catalogue are dropped at start (#478)
The ways a feed leaves the catalogue now take its subscriptions with
it, but any path missed now or added later would leave the same
leftover: items in All Subscriptions with no feed to name them. Each
start now unsubscribes everyone from a feed the catalogue does not
have, after retire_stranded, unless the catalogue is empty, which is
likelier a fault than a server with no feeds.

The 41 already in production (all from the Hacker News top feeds OPML,
which drops feeds daily) were deleted by hand on 2026-11-19.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 07:39:35 -05:00
349426cbf9 ipx rm takes a feed's subscriptions with it (#478)
Removing a feed from the catalogue left whoever subscribed to it
subscribed, the same leftover a list's dropped feed made: All
Subscriptions listed its items with no feed to name them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 07:39:35 -05:00
6939fd1dcc A feed an OPML drops takes its subscriptions and is not scanned again (#478)
On 2026-11-18 a scan's OPML sync dropped sciencedaily-latest-science-news.
drop_managed deleted the feed and its items but left its subscriptions,
and the scan, which had the feed in its list of feeds due, read it again
later in the same run and stored 60 items. The feed was then in no
catalogue but still subscribed to: All Subscriptions, which reads
subscriptions, listed its items, while the feed list, which reads the
catalogue, left it out, so the page had no name to put beside them and
sharing one answered 404.

drop_managed now deletes the feed's subscriptions too, and sync_group
returns the ids it dropped so the scan skips them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 07:39:35 -05:00
9c9c513419 The media handler's impossible error is matched as one (#479)
rustc 1.100 knows serving a file cannot fail (the error is Infallible)
and called e.to_string() an unreachable call, which -D warnings made
the pre-commit hook refuse for every commit touching ipx's Rust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 07:39:35 -05:00
d5037fb76d Subscriptions to a feed no longer in the catalogue are dropped at start (#478)
The ways a feed leaves the catalogue now take its subscriptions with
it, but any path missed now or added later would leave the same
leftover: items in All Subscriptions with no feed to name them. Each
start now unsubscribes everyone from a feed the catalogue does not
have, after retire_stranded, unless the catalogue is empty, which is
likelier a fault than a server with no feeds.

The 41 already in production (all from the Hacker News top feeds OPML,
which drops feeds daily) were deleted by hand on 2026-11-19.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 07:39:00 -05:00
c191357442 ipx rm takes a feed's subscriptions with it (#478)
Removing a feed from the catalogue left whoever subscribed to it
subscribed, the same leftover a list's dropped feed made: All
Subscriptions listed its items with no feed to name them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 07:33:53 -05:00
02d485cd10 A feed an OPML drops takes its subscriptions and is not scanned again (#478)
On 2026-11-18 a scan's OPML sync dropped sciencedaily-latest-science-news.
drop_managed deleted the feed and its items but left its subscriptions,
and the scan, which had the feed in its list of feeds due, read it again
later in the same run and stored 60 items. The feed was then in no
catalogue but still subscribed to: All Subscriptions, which reads
subscriptions, listed its items, while the feed list, which reads the
catalogue, left it out, so the page had no name to put beside them and
sharing one answered 404.

drop_managed now deletes the feed's subscriptions too, and sync_group
returns the ids it dropped so the scan skips them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 07:30:52 -05:00
7a3e3b4c63 The media handler's impossible error is matched as one (#479)
rustc 1.100 knows serving a file cannot fail (the error is Infallible)
and called e.to_string() an unreachable call, which -D warnings made
the pre-commit hook refuse for every commit touching ipx's Rust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 07:30:49 -05:00
bd7452db8f Now Playing covers the feeds and the list, not a row above them (#475)
As a grid item of #shell the sheet took a row of its own and pushed the
sidebar and the list into a second one; it is laid over the shell instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:57:38 +00:00
02ee6d74c1 Smart playlists (#476)
A playlist is the episodes of the podcasts chosen, those set to play first
ahead of the rest, newest or oldest first, unplayed only or all, kept up to
date by itself (table `playlists`, /api/playlists). It sits in a folder of its
own in the feed list, as Signals do. Played from one, an episode goes on to
the playlist's next once Up Next has nothing.

The priority ids are written into the ORDER BY, which the page query uses
twice, so they are quoted there rather than bound; they are also only ever
feed ids this person subscribes to.

The folder row first borrowed Signals' `sigs` class, which the tests use to
mean Signals' folder; four Signals tests failed until it had its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:54:19 +00:00
2faca684da Now Playing: a full view of what is playing (#475)
Tapping the player bar, or Enter on it, opens a sheet over the feeds and the
list: the episode's artwork large, its podcast, its show notes and Up Next.
The bar stays below it with the controls, so there is one set of them rather
than a second kept in step. Chapters are left for #477: nothing reads them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:40:02 +00:00
1fb1edd6b0 Podcasts shelf: your podcasts as their artwork (#474)
A place beside Up Next listing every feed with audio or video as a grid of
its artwork, with how many episodes are new, as Overcast's home screen
does. It is drawn from the feed list the page already holds; the feed list
gains `podcast`, an EXISTS per subscription over enclosures, which stops at
a podcast's first episode and is one index probe for a feed with no files.
Its cost on production's database is not measured: the EXPLAIN was not run.

The iOS app's generated messages (ios/Sources/Wire) are not regenerated:
there is no protoc here. Nothing in the app reads the new fields, and a
proto3 reader skips a field it does not know.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:37:53 +00:00
c65b80a06c Up Next: a queue that plays on by itself (#473)
Playing was one episode at a time: when one ended nothing followed. Up Next
is a per-account queue on the server (table `queue`, GET and PUT
/api/queue), so the phone and the browser share it. The page adds to it from
a row or the reader, reorders it by drag or arrow keys, and plays the next
when one ends; what is playing leaves it as it starts, as Overcast's does. An
episode 90% played leaves it on the server too, which covers the phone
playing on while the page is frozen.

The iOS app is told what follows (`{t:'next'}`, gated on the app saying it
can) and starts it at the end of an episode; the page takes it up through
nowPlaying as it does the car's pick. The Swift is not compiled here.

The page stub answered every unknown address with [], whose `.entries` is
Array.prototype.entries, so the queue read a function as its list; it now
answers /api/queue as an entry list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:31:40 +00:00
2ebe77b21e A search on Postgres starts from your feeds, not every feed's matches (#472)
After #459 a common word still took about 2 s: "apple" matched 61,674
items across every feed on the server, Postgres re-read each to confirm
the trigram match, and only then joined to the 1,151 in the searcher's
own feeds (EXPLAIN on production, 2026-11-17). The subquery
`e.feed_id IN (SELECT ... FROM subscriptions ...)` hid the feed list
from the planner, so the trigram index was always its way in.

Given as `e.feed_id = ANY(ARRAY(SELECT ...))`, the planner sees the
feeds and chooses per search: for "apple" this person's 20,152 items by
entries_seen, count 1.5 s to 0.38 s and the page of 50 1.1 s to 0.52 s;
for "kubernetes" still the trigram index, 21 ms; "the" 141 ms. Only for
a search, so ordinary lists keep their plans, and only on Postgres:
SQLite has no arrays and keeps the IN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:14:16 +00:00
54bfa5faf6 cargo deny passes: the SQLite advisory recorded as assessed (#467)
RUSTSEC-2026-0459 is SQLite before 3.54 returning stale page-cache memory
when it opens a database with a -wal file of another page size, which
needs a crafted pair of files someone else wrote. ipx opens only its own
state.db in its own data directory, and production runs on Postgres.
Its fix, libsqlite3-sys 0.39, is out of reach: sqlx-sqlite 0.9.0, the
latest, pins it below 0.38, and sea-orm 2.0.4 is on the same sqlx.

Ignored in deny.toml with that reason, as RUSTSEC-2026-0293 is, so a
new advisory fails the check again instead of hiding behind this one.
#467 stays open until sqlx can take the fix and the ignore comes out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:08:37 +00:00
9035306e22 A stuck scroll's report says where the drag began and who held it (#450)
Three scroll_stuck reports (2026-11-11, 11-12, 11-16) show a reader that
would not move with nothing wrong in what they record: no layer over it,
nothing inert, no transform, overflow auto. They started on the text (p,
a span in a pre, an image), not the left edge the swipe code cancels.

The report now also says where the finger began (x), how many touchmove
events the page saw during the drag (none would mean the browser kept
the gesture, as a scroller inside the text can), whether the touch was
cancelled, and how long since the reader was last slid across by a
swipe, which is the one thing a swipe changes on it and a suspect for
WebKit losing the scroller. The next report decides the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 01:39:34 +00:00
b046e66e54 Search reads items' plain text, trigram-indexed on Postgres (#459)
A search on All Subscriptions took 4.5-5 s: the page and its count each
matched lower(title) and lower(description) with LIKE '%q%' over every
entry, a parallel seq scan reading 554k buffers, about 4.3 GB, nearly all
of it descriptions' HTML in TOAST (EXPLAIN on production, 2026-11-14).

entries.search_text holds the title and the text with its markup taken
out (an image's alt and title kept, as Signals read them), lowercased
and cut at 4,000 characters; a pg_trgm GIN index on it keeps a part of a
word finding the word (#296's meaning). Chosen over a trigram index on
the HTML itself, several GB on the shared Postgres, and over full-text
search, which matches whole words only.

A new item gets its search text as it is stored. search.rs fills in the
rest behind the daemon, 500 at a time, and makes the index after,
CONCURRENTLY so scans go on, again if a build was cut off. A scan that
changes an item's title or text clears its search text for that pass to
make again; until then, and for every item stored before this, a search
matches it the old way, through a partial index on the ones without.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 01:34:01 +00:00
0cafe02599 Dependencies past eight of nine published advisories (#467)
ammonia 4.2.5 (mutation XSS through SVG and MathML, RUSTSEC-2026-0533),
pulldown-cmark 0.13.6 (wikilinks, 0414 and 0433), tokio 1.54.1
(AsyncFd, 0386), and async-compression 0.4.52, which let zstd go to
0.14.4 (0391), with zstd-safe 8.3.0 and zstd-sys (0398, 0403, 0410).

libsqlite3-sys (0459) stays at 0.37: sqlx-sqlite 0.9.0, the latest,
pins it below 0.38, so it waits on sqlx. Production runs on Postgres;
SQLite is the sample compose file's, the tests' and the load tests'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 01:04:41 +00:00
f652e6906b Swiping between items shows the next one's picture with its text (#471)
The preview a swipe draws beside the reader was built as the drag
began, so its pictures started loading then: its text showed first and
the picture popped in a moment later, flashing and pushing the text
down under the finger. Reported from the iOS app on an item with a
picture at its top.

The pictures of the items either side of the one open are now fetched
and decoded when it opens (a few each, parsed with DOMParser, which
loads nothing itself), so the preview draws them at once. And the end
of a swipe keeps the preview over the reader until the new item's
pictures are decoded, at most 300 ms, instead of swapping in the same
moment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:52:44 +00:00
Ray Slakinski
2b06db9d26 iOS: Sources/Wire regenerated from ipx.proto as of #470, comments only (#469)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:44:39 -05:00
Ray Slakinski
0fe2bf90ab iOS build 15 to TestFlight: protobuf to ipx (#469)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:44:26 -05:00
236bd02d88 Answers in protobuf from generated structs, and the page reads them (#470)
ipx-wire converted every protobuf answer at run time through
prost-reflect and serde_json::Value, so protobuf cost more than the JSON
it replaced: decoding 1,488 feeds took 1.50 ms that way against 0.37 ms
for serde_json and 0.09 ms for prost's own structs, and GET /api/feeds as
protobuf answered about 4 ms after JSON.

build.rs now generates those structs (prost-build from protox's
descriptors, still no protoc). An answer's JSON goes straight into its
struct with serde and out with prost, byte for byte what the runtime
path wrote (a test says so); bodies holding a google.protobuf.Value keep
the runtime path, as they are only ever read. ipx's calls to the
directory and ipx-play build and read the structs directly, through
From conversions beside the directory's own types.

The page asks for protobuf too, to see what it does in practice. It
reads it with web/src/wire.ts, about seventy lines and no library:
protobufjs alone was larger gzipped than all protobuf saves the page.
build.mts reads the .proto files into a table for it, and the answer
names its message in its Content-Type, so the page keeps no table of
routes. An answer of null stays JSON, since the empty message would be a
feed row of defaults. The offline worker decodes a kept answer to mark
what was read offline, and hands the page JSON.

The decoder's test caught `pos += varint()[0]`, which adds the length
to pos as it was before the varint was read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:21:41 +00:00
Ray Slakinski
baa6661622 iOS app asks ipx in protobuf, not JSON (#469)
The badge's and CarPlay's reads (/api/feeds, the entry lists) and the
player's writes (position, flags) now go as application/x-protobuf, the
messages generated from crates/wire/proto by ios/scripts/proto.sh into
Sources/Wire, committed so the build needs no protoc. SwiftProtobuf is
pinned to the generator's version, 1.41.0, whose code refuses another.

A read whose answer is not protobuf counts as no answer: a server from
before #465 answers JSON whatever it is asked, and JSON can decode as a
message of nothing, which would have set the badge to zero.

The outbox keeps its stored key, `json`, for the body, and marks the
new writes protobuf, so places saved offline by an older build are
still sent, as JSON.

Built for the simulator with Xcode 27.2; not run against a server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:00:10 -05:00
a96be2f14c build-image.sh refuses under 6 GB available, not 9: the cap alone
Tower sat at 8.6-9.1 GB available all evening and no build could start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:35:12 +00:00
c0998f1ac7 Protobuf beside JSON in ipx's, the directory's and ipx-play's APIs (#465); ipx's build touches crates/play (#466)
A client sending Accept: application/x-protobuf gets protobuf, and one
sending Content-Type: application/x-protobuf may send its body so; JSON
stays the default, so the page, the TUI and older iOS builds see nothing
new. ipx's own calls to the directory and ipx-play now go in protobuf.

The handlers are untouched. A new crate, ipx-wire, holds the .proto
files (compiled by protox in build.rs, so no protoc anywhere) and one
layer, negotiate, that converts JSON at the edge through prost-reflect,
by a table of each route's messages. Writing prost structs beside every
serde one would have doubled each type and every handler.

Protobuf cannot tell absent from empty or from null, and the PATCH
bodies depend on that: an Option<Vec> left out leaves the list, an empty
one clears it, and null clears a folder. So a list in a body is a
one-field message (absent or present), and null-to-clear is a
google.protobuf.Value. Numbers in a Value come back whole, or 3.0 would
not read as a usize.

Debug builds convert every JSON answer strictly and answer 500 for a
field missing from the .proto or a route missing from a table; the cargo
tests and the browser suite (125 tests) ran clean that way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:23:06 +00:00
2671d13489 Browser suite: ipxd list, a feed that moves for good, Atom with a bare ampersand (#463)
API coverage 78.0% to 80.0% (9174 of 11467 lines): follow_move and the catalogue's list,
and the parser's retry of an escaped Atom feed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:51:04 +00:00
b22016cbe5 Browser suite: feeds in every shape, a feed that starts failing, ipxd user (#463); coverage build's stylesheet named by its own hash (#464)
Atom, RSS with a bare ampersand and the iTunes and Media RSS fields, WordPress.com's posts,
and replies that are no feed are added through the API; a fixture feed turned 404, 403,
402, 500, a sentence, a web page linking its new address, garbled, a redirect loop and a
dropped connection says each, and after a day (error_since set back in the suite's SQLite)
in words, with the page's banner; ipxd user's commands and their refusals. API coverage
76.5% to 78.0%: failure.rs 12% to 91%, parse.rs 56% to 92%, cli.rs 44% to 86%.

#464: with IPX_COVERAGE=1 the page named app.css by the hash of it unminified while the
build wrote it minified. The worker's check from #449 reloaded the page for it, and its
throttle then swallowed the reload the #449 test waits for, which failed in every coverage
run. buildStyle now defaults to the page's choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:12:44 +00:00
eda77e87c7 Ask in the page's own dialog, not confirm(), which the iOS app answered Cancel (#462)
Deleting a downloaded file from the iOS app did nothing: no DELETE reached ipx-web or ipx.
WKWebView answers confirm() Cancel without showing it unless the app implements the panel,
which 614f270 does (#453), but only once the app is rebuilt. ask() is a <dialog> of the
page's own, in the top layer, so it opens over a dialog already up (the file menu, Settings)
and leaves it as it was, and Escape answers it alone. Every confirm() in the page and the
admin page goes through it; the tests answer it rather than the browser's dialog, and the
warning before sharing a feed with its key in the address, untested before, now is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 23:32:15 +00:00
d1ba83bb7a ipx-play's metrics on 9191: 9189 is hnopml's (#458)
5d0ff1a put ipx-play's /metrics on 9189, but hnopml, in the same
compose project, has published 192.168.1.130:9189 since 2026-11-12 and
Prometheus scrapes it there as job="hnopml". Deployed as written,
ipx-play's port would have clashed with it. 9187 to 9190 are ipx, the
directory, hnopml and ipx-web; 9191 is free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 04:11:51 +00:00
614f270a90 iOS app: the page's confirm() is asked, not answered Cancel (#453)
WebViewController is the web view's WKUIDelegate but had no confirm
panel, so WebKit answered every confirm() false at once and showed
nothing: the page's nine confirm() calls, deleting a file and sharing a
Patreon address among them, could never go ahead in the app. It now
shows an alert with Cancel and OK. With another alert already up it
answers Cancel, as before, since one cannot be presented over the other.
The page has no alert() or prompt(), so those panels are left out.

Not compiled here: the Swift builds only on a Mac with Xcode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 04:08:43 +00:00
0222c0b69a Artwork that cannot be shown is not fetched again every hour (#448)
/api/art remembered a failed image for an hour, whatever the failure, so
an image that could never pass was fetched again on the next view after
that. In 2026-11-09..13, five images over the 20 MB limit were fetched
146 times, each read 20 MB chunk by chunk before being refused, about
3 GB for nothing; a 400 from b2c-contenthub.com was asked for 34 times.

Now a Content-Length over the limit is refused before the body is read,
and a failure that will still hold tomorrow is remembered for a day: a
4xx other than 408 and 429, or ipx's own refusal (too large, not an
image). Timeouts, 5xx and dropped connections still retry in an hour.

JPEG XL, which shkspr.mobi sends as application/octet-stream, was
refused as not an image; its two signatures are sniffed now, and Safari
shows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 04:04:14 +00:00
f9f50fcf07 reap --dry-run says what would go, not that it went (#461)
A dry run printed "deleted <path> (N MB)" for every file and "deleted N
old file(s)" at the end, word for word a real reap, of files it kept:
Reaped and ReapDone carried no flag to say otherwise. Both now carry
dry_run (serde default false, so an older message still reads), and the
words are "would delete".

Found writing the browser suite's first test of retention, which ran on
the daemon's own clock and nowhere in the suite: over a tiny quota, a dry
reap lists the downloads and leaves them, and a reap with no limits
deletes nothing and only tidies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:59:02 +00:00
61c38bacc1 Browser suite: every service's /metrics, scraped as Prometheus does
Nothing in the browser suite asked ipx, the directory or ipx-play for
their metrics, though production's Prometheus scrapes all three every
15 s and the dashboard and alerts go blank if one stops answering. The
suite's servers get metrics ports (8799, 8797, 8790) and one test reads
each gzipped, checks every sample line is one Prometheus can parse, and
looks for the series that show it works: ipx's request histogram with
the route just asked for, the directory's snapshot from ipx, ipx-play's
build. ipx's metrics.rs went from 9% to 86% of lines run by the suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:58:55 +00:00
373f862588 A page older than its script is loaded again, not run with it (#449)
Safari on a Mac threw at load on 2026-11-10: the script wired #sleep,
which the page it ran in did not have. #sleep and its script came in
together on 11-08, so the page was older than the script. The service
worker answers a navigation it cannot fetch with the page it kept last,
here one from before 11-08, and that page asked for its script by the old
hash; by then the network answered, and Caddy, which ignores ?v=, sent
today's app.js. The worker even kept it under the old name.

Every ?v= is the first 12 hex digits of the file's SHA-256, so the worker
now checks what it fetched against the name. On a mismatch it does not
keep or give the file, and loads the page again from the network, at most
once in 30 seconds so a page still unreachable is not reloaded round and
round.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:46:49 +00:00
abee943bf5 One place to get an episode's file where you are (#457)
Getting an episode onto a phone took two buttons in two states: download
it to the server, wait, then keep it on the device, beside Save to this
computer, Share and Delete, five buttons that did not say where each
copy went. Now a file has one button that brings it to where you are.
On a phone or in the iOS app it ends on the device; when iPX has not got
the file yet, iPX fetches it and the device's copy follows once iPX says
it is done (remembered in localStorage, so a page closed meanwhile
catches up when a list next shows the file). On a computer it has iPX
fetch the file, and with iPX's copy there saves one. A line beside the
size says where the file is, and the rarer actions, two of them
destructive, are under a menu.

isPlayable is false for any file not on iPX, so the phone's button is
decided by playsKind, the same test without the path. download_done now
marks the file as on iPX in what the page holds, so the open file's box
changes at once rather than after the list is fetched again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVA8TdTxe556JB3sR1n
2026-11-14 03:42:16 +00:00
Ray Slakinski
5d0ff1ac57 ipx-play: metrics for Prometheus, a dashboard row and a down alert (#458)
ipx-play sent traces and logged JSON but served no /metrics, so nothing showed whether
shared links were opening or failing. It now serves them on metrics_bind (9189 in
production, off the tunnel's port), with the directory's histogram and /proc reading:
requests by method, route and status (by route, so each shared episode is not a row of its
own, and an unknown address is route=""), episodes shared, memory, open files, uptime and
version.

The iPX dashboard gets an ipx-play row, its warnings join the other containers' log panel,
and alerts.py fires when Prometheus cannot reach it. The prod-check skill and docs/play.md
name it, with the scrape job and the OTEL_RESOURCE_ATTRIBUTES tag the trace panels need.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:08:31 -05:00
94 changed files with 11309 additions and 425 deletions

View File

@@ -1,11 +1,11 @@
---
name: ipx-prod-check
description: Look for problems in production ipx (the ipx-web, iPX and ipx-directory containers on Tower, Tower itself and the monitoring that watches them) from their logs in Loki, their traces in Tempo and the metrics in Prometheus, and file what is found as Gitea issues. Use when asked to check on production, look for issues or errors in ipx, see why something is slow or failing in production, review the logs, or investigate a report about the live site.
description: Look for problems in production ipx (the ipx-web, iPX, ipx-directory and ipx-play containers on Tower, Tower itself and the monitoring that watches them) from their logs in Loki, their traces in Tempo and the metrics in Prometheus, and file what is found as Gitea issues. Use when asked to check on production, look for issues or errors in ipx, see why something is slow or failing in production, review the logs, or investigate a report about the live site.
---
# Checking production ipx
Production is three containers in the Arcane project `ipx` on Tower
Production is four containers in the Arcane project `ipx` on Tower
(`/mnt/fast/arcane/projects/ipx/compose.yaml`), one request passing through them in this order:
| container | what | logs, in Loki | traces, in Tempo | metrics, in Prometheus |
@@ -13,11 +13,12 @@ Production is three containers in the Arcane project `ipx` on Tower
| `ipx-web` | Caddy: serves the page, passes `/api` and `/media` to ipx (#203). Port 8099, the LAN and the tunnel | `{container="ipx-web"}`, JSON: a line a request (`http.log.access`), its own errors | service `ipx-web`: a span a request, passing `traceparent` on to ipx (#213) | `job="ipx-web"`: Caddy's own `caddy_http_*`, from `METRICS_BIND`, published as `192.168.1.130:9190` (#371) |
| `iPX` | the daemon: API, scans, downloads, DeadAir | `{container="iPX"}`, JSON (`IPX_LOG_FORMAT=json`) | service `ipx`; passes `traceparent` to the directory | `job="ipx"`, its `/metrics` |
| `ipx-directory` | the directory of public podcasts, `directory.ipxreader.app` (#204, #214) | `{container="ipx-directory"}`, JSON (`DIRECTORY_LOG_FORMAT=json`) | service `ipx-directory`: a span a request, joining ipx's trace when ipx called; a trace a refresher round (#213) | `job="ipx-directory"`, its `/metrics` |
| `ipx-play` | the page a shared episode opens, `play.ipxreader.app` (#447); ipx sends it the episodes shared | `{container="ipx-play"}`, JSON (`PLAY_LOG_FORMAT=json`): a line a request (`ipx_play::http`), one a share | service `ipx-play`: a span a request, joining ipx's trace on a share | `job="ipx-play"`, its `/metrics` on `metrics_bind` (production `192.168.1.130:9191`, LAN only, #458) |
Grafana's alert rules (`grafana/alerts.py`, #365) watch all of it between checks: start by asking
which are firing (the monitoring section). Under them, Tower itself: `job="node"` (the node exporter: load, CPU, memory, disks). The Grafana
dashboard `iPX` draws all of it in that order (`grafana/dashboard.py`). A trace without the
production tag (`resource.deployment.environment.name="production"`, on all three) is a daemon run
production tag (`resource.deployment.environment.name="production"`, on all four) is a daemon run
by hand, not production. Since #213 a request is one trace across the services it touched: a
Directory page is ipx-web, then ipx, then the directory, so start from the trace, not the logs. Alloy ships the logs; Loki, Tempo and
Prometheus publish no query port to this machine, so use the script beside this file:
@@ -38,7 +39,7 @@ $Q flame '<TraceQL>' [since] [out.svg] # where the matching spans' time went,
"Since the last deploy" is since that container started (each deploys on its own):
```sh
for c in iPX ipx-web ipx-directory; do S=$(docker inspect $c -f '{{.State.StartedAt}}'); echo "$c $(( ($(date +%s) - $(date -d "$S" +%s)) / 60 + 1 ))m"; done
for c in iPX ipx-web ipx-directory ipx-play; do S=$(docker inspect $c -f '{{.State.StartedAt}}'); echo "$c $(( ($(date +%s) - $(date -d "$S" +%s)) / 60 + 1 ))m"; done
```
Start every check by seeing that all three run, since Loki cannot see a container that is not:
@@ -422,12 +423,12 @@ container's lines are reaching Loki:
```sh
curl -s http://192.168.1.130:9090/api/v1/targets | python3 -c 'import json,sys
for t in json.load(sys.stdin)["data"]["activeTargets"]: print(t["health"], t["labels"]["job"], t["scrapeUrl"], t.get("lastError","")[:80])'
for c in iPX ipx-web ipx-directory; do echo "$c $($Q metric "sum(count_over_time({container=\"$c\"} [24h]))" 24h | tail -1)"; done
for c in iPX ipx-web ipx-directory ipx-play; do echo "$c $($Q metric "sum(count_over_time({container=\"$c\"} [24h]))" 24h | tail -1)"; done
docker ps -a --filter label=com.docker.compose.project=monitoring --format '{{.Names}} {{.Status}}'
docker logs --since 1h tempo 2>&1 | grep -E 'failed to poll|blocklist poll complete' | tail -2
```
`ipx`, `ipx-directory`, `ipx-web`, `node` and the monitoring's own, `prometheus`, `tempo`, `loki`
`ipx`, `ipx-directory`, `ipx-play`, `ipx-web`, `node` and the monitoring's own, `prometheus`, `tempo`, `loki`
and `alloy` (#366), should be `up`. Alloy is scraped at `alloy:12345` because its command sets
`--server.http.listen-addr`; it listens on 127.0.0.1 without it.

View File

@@ -2,15 +2,15 @@
# Refuses a commit whose Rust is not as rustfmt writes it, or that clippy warns about. Clippy only
# checks and never links, so it is light beside a test build (CLAUDE.md, Tests). It checks the
# crates the commit touches and those built on them, not the workspace: ipx uses ipx-play and
# ipx-directory, ipx-play uses ipx-directory, and all use ipx-feed. A commit to the page alone runs nothing here.
# ipx-directory, ipx-play uses ipx-directory, and all use ipx-feed and ipx-wire. A commit to the page alone runs nothing here.
staged=$(git diff --cached --name-only --diff-filter=ACMD)
echo "$staged" | grep -q -e '\.rs$' -e 'Cargo\.toml$' -e '^Cargo\.lock$' || exit 0
if ! cargo fmt --all --check >/dev/null 2>&1; then
echo "pre-commit: the Rust is not formatted; run cargo fmt --all" >&2
exit 1
fi
if echo "$staged" | grep -q -e '^Cargo\.toml$' -e '^Cargo\.lock$' -e '^crates/feed/'; then
pkgs="ipx-feed ipx-directory ipx-play ipx ipx-tui"
if echo "$staged" | grep -q -e '^Cargo\.toml$' -e '^Cargo\.lock$' -e '^crates/feed/' -e '^crates/wire/'; then
pkgs="ipx-feed ipx-wire ipx-directory ipx-play ipx ipx-tui"
elif echo "$staged" | grep -q '^crates/tui/'; then
pkgs="ipx-tui"
elif echo "$staged" | grep -q '^crates/directory/'; then

View File

@@ -20,7 +20,7 @@ service of the `content` project, beside audiobookshelf, immich and Plex (#208).
| Old database | `/mnt/user/ipx/state.db`, SQLite, used until the move to Postgres on 2026-09-18 and kept for rollback | `/data/state.db` |
| Downloads | `/mnt/user/ipx/downloads` | `/downloads` |
| Directory | `ipx-directory` in the same project, `192.168.1.130:8100`, public at `directory.ipxreader.app` through the tunnel with no Access in front: its pages are anyone's to browse, read only (#215), and its API (`/v1`) takes a token for everything. Until 2026-10-12 it was `ipx-dir.sdf1.net` (#214). Config `/mnt/fast/appdata/ipx-directory/directory.toml` (token hashes; Tower's own token in `tower.token` beside it, and entered in ipx's Admin, Directory, which keeps it in the database's `settings`, with the address ipx reaches it at: `http://ipx-directory:8100`, inside Docker, not the public address, which went out through Cloudflare and the tunnel, 170-340 ms a call where the directory answers in 16 ms), database `ipx_directory` on the same Postgres, URL in `directory.env` beside the compose file. See [docs/directory.md](docs/directory.md) | `/config/directory.toml` |
| Shared episodes | `ipx-play` in the same project, `192.168.1.130:8102`, public at `play.ipxreader.app` through the tunnel with no Access in front: the page a shared episode opens, anyone's to see (#447). `/v1` takes a token. Config `/mnt/fast/appdata/ipx-play/play.toml` (token hashes; Tower's token entered in ipx's Admin, Directory, Sharing episodes, with the address `http://ipx-play:8102`), database `ipx_play` on the same Postgres, URL in `play.env` beside the compose file. See [docs/play.md](docs/play.md) | `/config/play.toml` |
| Shared episodes | `ipx-play` in the same project, `192.168.1.130:8102`, public at `play.ipxreader.app` through the tunnel with no Access in front: the page a shared episode opens, anyone's to see (#447). `/v1` takes a token. Config `/mnt/fast/appdata/ipx-play/play.toml` (token hashes; Tower's token entered in ipx's Admin, Directory, Sharing episodes, with the address `http://ipx-play:8102`), database `ipx_play` on the same Postgres, URL in `play.env` beside the compose file. Metrics for Prometheus on `192.168.1.130:9191`, LAN only, as `job="ipx-play"` (#458). See [docs/play.md](docs/play.md) | `/config/play.toml` |
| Home page | `ipxreader.app` (and `www`): a static page from `site/`, on the Cloudflare Pages project `ipxreader`, not on Tower. See below | |
| Web UI | `ipx-web` (Caddy) in the same project, at `192.168.1.130:8099`, also `ipodderx.sdf1.net` via a Cloudflare tunnel. It serves the page and passes `/api` and `/media` to ipx, whose own port is published nowhere; its address on `ipx_default` is pinned to `192.168.64.10` (#203) | ipx `0.0.0.0:8099`, Caddy `:8080` |
| Sign-in via the tunnel | Cloudflare Access app `ipodderx`, with Authentik as its identity provider; see [docs/sso.md](docs/sso.md) | Caddy passes `Cf-Access-*` only from `192.168.64.1`, the `ipx_default` gateway cloudflared arrives from (`TUNNEL_PEER`; the subnet is pinned in the compose file); ipx trusts them only from Caddy, `192.168.64.10`, and only with a valid `Cf-Access-Jwt-Assertion` (`access_team`, `access_aud`) |
@@ -52,7 +52,7 @@ Deploying a change is: build and push the image, then pull it and recreate the c
**Build only with `scripts/build-image.sh`, never a bare `docker buildx build`.** On 2026-11-04
a plain build of ipx, its dependency layer invalidated by a `Cargo.toml` change, rebuilt
everything in release on all twelve threads with 5 GB free; Tower thrashed for three hours with
every core pegged and had to be rebooted. The script refuses to start under 9 GB available or
every core pegged and had to be rebooted. The script refuses to start under 6 GB available or
above load 12, and builds in the BuildKit container `ipx-capped` (made on first use), held to 6
GB of memory and six threads by its cgroup: a build that outgrows that is killed, and production
keeps running. If one is killed, say so and wait for the user to decide; do not raise the caps or go
@@ -148,7 +148,10 @@ running the command and kills the session (exit 144), which has happened more th
see [ios/README.md](ios/README.md). It builds only on a Mac with Xcode, from `ios/project.yml`
through XcodeGen: nothing here compiles or checks the Swift, so say so when handing over a change
to it. A change to the bridge's messages is a change to `native.ts`, `tests/native-bridge.ts` and
`ios/Sources/Bridge.swift` together, and the page deploys first.
`ios/Sources/Bridge.swift` together, and the page deploys first. The app's own calls to ipx (the
player, the badge, CarPlay) are protobuf, from `ios/Sources/Wire`, generated from
`crates/wire/proto` by `sh ios/scripts/proto.sh`: run it after changing a `.proto`, and deploy ipx
before shipping an app that needs a new field.
## Before you touch the page
@@ -250,7 +253,7 @@ session was stopped. So:
* Look at the load before and after each (`cat /proc/loadavg`). Above about 24, Tower's twelve
threads twice over, wait for it to come down before starting another.
* Test only what the change is in. ipx uses ipx-play and ipx-directory, ipx-play uses
ipx-directory, and all use ipx-feed, so:
ipx-directory, and all use ipx-feed and ipx-wire, so:
| changed | run |
|---|---|
@@ -260,7 +263,8 @@ session was stopped. So:
| `crates/play/` | `cargo test -p ipx-play`, then `-p ipx` |
| `crates/feed/` | `cargo test -p ipx-feed`, then `-p ipx-directory`, `-p ipx-play`, then `-p ipx` |
| `crates/tui/` | `cargo test -p ipx-tui`; it uses only the API, none of the other crates |
| `Cargo.toml`, `Cargo.lock` | all five, one at a time |
| `crates/wire/` | `cargo test -p ipx-wire`, then `-p ipx-play`, `-p ipx-directory`, then `-p ipx`; the browser suite, whose debug builds check every answer against the `.proto` |
| `Cargo.toml`, `Cargo.lock` | all six, one at a time |
The pre-commit hook's clippy follows the same table. The whole browser suite once, at the end
of a change to the page or the API; never `cargo test` for the workspace in one command.

335
Cargo.lock generated
View File

@@ -19,15 +19,15 @@ dependencies = [
[[package]]
name = "alloc-no-stdlib"
version = "2.0.4"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib",
]
@@ -40,9 +40,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "ammonia"
version = "4.2.4"
version = "4.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f45dfa685e1ec33b1bf1a3b93b8047cbdbef41b6040deebbe6bea7720a45574"
checksum = "b34ca49e407c06daac53f0c4debe8ff5df9cc2a4e9369d164a5d86ef8c219319"
dependencies = [
"cssparser",
"html5ever",
@@ -162,9 +162,9 @@ dependencies = [
[[package]]
name = "async-compression"
version = "0.4.46"
version = "0.4.52"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f10dafd0c8d2e51ae9a748805777613ed0bbe17bf586b76c8311f45c020a32f"
checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459"
dependencies = [
"compression-codecs",
"compression-core",
@@ -377,6 +377,12 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "beef"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
[[package]]
name = "bigdecimal"
version = "0.4.10"
@@ -471,9 +477,9 @@ dependencies = [
[[package]]
name = "brotli"
version = "8.0.4"
version = "9.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -482,9 +488,9 @@ dependencies = [
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -690,9 +696,9 @@ dependencies = [
[[package]]
name = "compression-codecs"
version = "0.4.41"
version = "0.4.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58a6d0db8759036a783bc7c3f7a07f8cef3bf9470eb1db3bc86e8bcd1c5d0fe8"
checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43"
dependencies = [
"brotli",
"compression-core",
@@ -704,9 +710,9 @@ dependencies = [
[[package]]
name = "compression-core"
version = "0.4.33"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414"
checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a"
[[package]]
name = "const_panic"
@@ -1264,6 +1270,12 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d"
[[package]]
name = "fixedbitset"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175"
[[package]]
name = "flate2"
version = "1.1.10"
@@ -1292,6 +1304,12 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foldhash"
version = "0.2.0"
@@ -1575,6 +1593,15 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash 0.1.5",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -1583,7 +1610,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -1594,7 +1621,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -1984,6 +2011,7 @@ dependencies = [
"ipx-directory",
"ipx-feed",
"ipx-play",
"ipx-wire",
"jsonwebtoken",
"librqbit",
"opentelemetry",
@@ -2016,6 +2044,7 @@ dependencies = [
"flate2",
"futures-util",
"ipx-feed",
"ipx-wire",
"mimalloc",
"opentelemetry",
"opentelemetry-otlp",
@@ -2068,6 +2097,7 @@ dependencies = [
"clap",
"ipx-directory",
"ipx-feed",
"ipx-wire",
"opentelemetry",
"percent-encoding",
"reqwest",
@@ -2097,6 +2127,23 @@ dependencies = [
"serde_json",
]
[[package]]
name = "ipx-wire"
version = "0.0.0"
dependencies = [
"axum",
"prost",
"prost-build",
"prost-reflect",
"prost-types",
"protox",
"serde",
"serde_json",
"tokio",
"tower",
"tracing",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@@ -2688,6 +2735,72 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "logos"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff472f899b4ec2d99161c51f60ff7075eeb3097069a36050d8037a6325eb8154"
dependencies = [
"logos-derive 0.15.1",
]
[[package]]
name = "logos"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f"
dependencies = [
"logos-derive 0.16.1",
]
[[package]]
name = "logos-codegen"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "192a3a2b90b0c05b27a0b2c43eecdb7c415e29243acc3f89cc8247a5b693045c"
dependencies = [
"beef",
"fnv",
"lazy_static",
"proc-macro2",
"quote",
"regex-syntax",
"rustc_version",
"syn 2.0.119",
]
[[package]]
name = "logos-codegen"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970"
dependencies = [
"fnv",
"proc-macro2",
"quote",
"regex-automata",
"regex-syntax",
"syn 2.0.119",
]
[[package]]
name = "logos-derive"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "605d9697bcd5ef3a42d38efc51541aa3d6a4a25f7ab6d1ed0da5ac632a26b470"
dependencies = [
"logos-codegen 0.15.1",
]
[[package]]
name = "logos-derive"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31"
dependencies = [
"logos-codegen 0.16.1",
]
[[package]]
name = "lru"
version = "0.18.5"
@@ -2790,6 +2903,28 @@ dependencies = [
"rapidhash",
]
[[package]]
name = "miette"
version = "7.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"
dependencies = [
"cfg-if",
"miette-derive",
"unicode-width 0.1.14",
]
[[package]]
name = "miette-derive"
version = "7.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "mimalloc"
version = "0.1.52"
@@ -2837,6 +2972,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multimap"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
[[package]]
name = "multiversion"
version = "0.9.0"
@@ -3115,6 +3256,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "ordered-float"
version = "2.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
dependencies = [
"num-traits",
]
[[package]]
name = "ordered-float"
version = "4.6.0"
@@ -3202,6 +3352,17 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "petgraph"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
dependencies = [
"fixedbitset",
"hashbrown 0.15.5",
"indexmap 2.14.2",
]
[[package]]
name = "pgvector"
version = "0.4.2"
@@ -3328,6 +3489,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.119",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
@@ -3356,6 +3527,25 @@ dependencies = [
"prost-derive",
]
[[package]]
name = "prost-build"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
dependencies = [
"heck 0.5.0",
"itertools 0.14.0",
"log",
"multimap",
"petgraph",
"prettyplease",
"prost",
"prost-types",
"regex",
"syn 2.0.119",
"tempfile",
]
[[package]]
name = "prost-derive"
version = "0.14.4"
@@ -3370,10 +3560,61 @@ dependencies = [
]
[[package]]
name = "pulldown-cmark"
version = "0.13.4"
name = "prost-reflect"
version = "0.16.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"
checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1"
dependencies = [
"base64 0.22.1",
"logos 0.16.1",
"miette",
"prost",
"prost-types",
"serde",
"serde-value",
]
[[package]]
name = "prost-types"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
dependencies = [
"prost",
]
[[package]]
name = "protox"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f25a07a73c6717f0b9bbbd685918f5df9815f7efba450b83d9c9dea41f0e3a1"
dependencies = [
"bytes",
"miette",
"prost",
"prost-reflect",
"prost-types",
"protox-parse",
"thiserror 2.0.20",
]
[[package]]
name = "protox-parse"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "072eee358134396a4643dff81cfff1c255c9fbd3fb296be14bdb6a26f9156366"
dependencies = [
"logos 0.15.1",
"miette",
"prost-types",
"thiserror 2.0.20",
]
[[package]]
name = "pulldown-cmark"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b"
dependencies = [
"bitflags 2.13.1",
"memchr",
@@ -3631,7 +3872,7 @@ dependencies = [
"thiserror 2.0.20",
"unicode-segmentation",
"unicode-truncate",
"unicode-width",
"unicode-width 0.2.3",
]
[[package]]
@@ -3663,7 +3904,7 @@ dependencies = [
"strum",
"time",
"unicode-segmentation",
"unicode-width",
"unicode-width 0.2.3",
]
[[package]]
@@ -4083,7 +4324,7 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "546040c653a705e60ec65ecd3191a809603734bebbc225775916dea9ae409b31"
dependencies = [
"ordered-float",
"ordered-float 4.6.0",
"sea-query-derive",
"serde_json",
]
@@ -4176,6 +4417,16 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde-value"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
dependencies = [
"ordered-float 2.10.1",
"serde",
]
[[package]]
name = "serde_core"
version = "1.0.229"
@@ -4788,6 +5039,18 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "tendril"
version = "0.5.1"
@@ -4905,9 +5168,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.53.1"
version = "1.54.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
dependencies = [
"bytes",
"libc",
@@ -5260,9 +5523,15 @@ checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5"
dependencies = [
"itertools 0.14.0",
"unicode-segmentation",
"unicode-width",
"unicode-width 0.2.3",
]
[[package]]
name = "unicode-width"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "unicode-width"
version = "0.2.3"
@@ -5908,27 +6177,27 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zstd"
version = "0.14.2"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "057cfd910cfac363a0ada849592624b4c9ff2e10bef504c3433810d78ed96f93"
checksum = "ad5020ab8f27bfc0024ad0a07aed6bf022a16208f479686fbed4fdd0c85eb0b3"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "8.1.0"
version = "8.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdd44c6a7284e91f3717755b24315a302edd9153a01f753c3cba3d765e8eafac"
checksum = "5a9ea9cc2576c2fcc104e9cec04f46e3ede564f4fbc206831e4ef7e859a4140d"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.1.1+zstd.1.5.7"
version = "2.1.3+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aeec9eaf2dffbbd09201e23bd0ffcbaa33bb8e9266a10734fd7ed90a85eca078"
checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d"
dependencies = [
"cc",
"pkg-config",

View File

@@ -1,5 +1,5 @@
[workspace]
members = ["crates/ipx", "crates/feed", "crates/directory", "crates/tui", "crates/play"]
members = ["crates/ipx", "crates/feed", "crates/directory", "crates/tui", "crates/play", "crates/wire"]
resolver = "3"
# Each service has its own version, in its own Cargo.toml (ipx, ipx-directory) or package.json
@@ -15,6 +15,7 @@ unsafe_code = "forbid"
ipx-feed = { path = "crates/feed" }
ipx-directory = { path = "crates/directory" }
ipx-play = { path = "crates/play" }
ipx-wire = { path = "crates/wire" }
ammonia = "4.1.4"
anyhow = "1.0.104"
argon2 = "0.6.0"
@@ -30,6 +31,11 @@ opentelemetry = { version = "0.33", default-features = false, features = ["trace
opentelemetry-otlp = { version = "0.33", default-features = false, features = ["trace", "http-proto", "reqwest-blocking-client", "gzip-http"] }
opentelemetry_sdk = { version = "0.33", default-features = false, features = ["trace"] }
opml = "1.1.6"
prost = "0.14.4"
prost-build = "0.14"
prost-reflect = { version = "0.16", features = ["serde"] }
protox = "0.9"
prost-types = "0.14"
pulldown-cmark = { version = "0.13.4", default-features = false, features = ["html"] }
mimalloc = "0.1.52"
http = "1.5.0"

View File

@@ -20,7 +20,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/
RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
--mount=type=cache,id=ipx-target,target=/src/target,sharing=locked \
touch crates/ipx/src/main.rs crates/ipx/src/lib.rs crates/feed/src/lib.rs \
crates/directory/src/lib.rs \
crates/directory/src/lib.rs crates/play/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \
&& cargo build --release --locked -p ipx \
&& cp target/release/ipxd /usr/local/bin/ipxd

View File

@@ -14,7 +14,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/
# of its own: built with ipx's, the two would rebuild shared crates for each other's features.
RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
--mount=type=cache,id=ipx-directory-target,target=/src/target,sharing=locked \
touch crates/directory/src/main.rs crates/directory/src/lib.rs crates/feed/src/lib.rs \
touch crates/directory/src/main.rs crates/directory/src/lib.rs crates/feed/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \
&& cargo build --release --locked -p ipx-directory \
&& cp target/release/ipx-directory /usr/local/bin/ipx-directory

View File

@@ -13,7 +13,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/
# Compiled crates kept in the builder between builds (#438), in a target of its own.
RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
--mount=type=cache,id=ipx-play-target,target=/src/target,sharing=locked \
touch crates/play/src/main.rs crates/play/src/lib.rs crates/directory/src/lib.rs crates/feed/src/lib.rs \
touch crates/play/src/main.rs crates/play/src/lib.rs crates/directory/src/lib.rs crates/feed/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \
&& cargo build --release --locked -p ipx-play \
&& cp target/release/ipx-play /usr/local/bin/ipx-play

View File

@@ -5,6 +5,8 @@ WORKDIR /src
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY web ./web
# The protobuf messages the page reads its answers in (#470).
COPY crates/wire/proto ./crates/wire/proto
RUN node web/build.mts /dist
FROM caddy:2

View File

@@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `/v1` answers in protobuf for a client that asks for it (`Accept: application/x-protobuf`) and takes a snapshot sent so; JSON stays the default. The messages are in `crates/wire/proto/directory.proto`, and answers go through structs generated from them (#465, #470).
- A `robots.txt` and a sitemap listing the home page, A to Z, every category and every feed, so search engines find the pages, not only the links between them (#380).
- `/metrics` counts its requests and their times by route and status, the feeds it checks and those that failed, and the snapshots it takes (#370).
- Its log lines inside a trace carry the trace's and span's ids, as ipx's do, so a failed feed check leads to its trace (#375).
@@ -25,6 +26,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A YouTube channel's check no longer fails on the 404 or 500 YouTube answers some feed requests with and does not mean: it is asked again, twice, a second apart (#382).
### Security
- Feeds and Markdown items are read with pulldown-cmark 0.13.6, and compressed answers with zstd 0.14.4 and zstd-safe 8.3, each closing published advisories (#467).
## [1.4.1] - 2026-10-24
### Fixed

View File

@@ -18,6 +18,7 @@ axum.workspace = true
clap.workspace = true
futures-util.workspace = true
ipx-feed.workspace = true
ipx-wire.workspace = true
opentelemetry.workspace = true
opentelemetry-otlp.workspace = true
opentelemetry_sdk.workspace = true

View File

@@ -17,6 +17,18 @@ use tower_http::compression::CompressionLayer;
use tower_http::decompression::RequestDecompressionLayer;
use tracing::Instrument;
/// Each route's protobuf messages (#465), beside its JSON.
const WIRE: ipx_wire::Routes = &[
("GET", "/v1/me", "", "directory.Me"),
("GET", "/v1/feeds", "", "directory.Listings"),
("GET", "/v1/popular", "", "directory.Listings"),
("GET", "/v1/feeds/{id}", "", "directory.FeedPage"),
("POST", "/v1/feeds/{id}/refresh", "", "directory.FeedPage"),
("POST", "/v1/snapshot", "directory.Snapshot", "directory.SnapshotResult"),
("GET", "/v1/blocked", "", "directory.BlockedList"),
("GET", "/v1/instances", "", "directory.Instances"),
];
/// Every route: the API under `/v1`, behind a token, and the public pages.
pub fn router(dir: Shared) -> Router {
let v1 = Router::new()
@@ -30,6 +42,7 @@ pub fn router(dir: Shared) -> Router {
.route("/v1/blocked/{id}", delete(unblock))
.route("/v1/instances", get(instances))
.route("/v1/instances/{name}", delete(drop_instance))
.route_layer(axum::middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
.layer(axum::middleware::from_fn_with_state(dir.clone(), authenticate));
Router::new()
.route("/healthz", get(healthz))

View File

@@ -97,3 +97,98 @@ pub struct Blocked {
/// The most a snapshot may list: far more than one server's subscriptions, few enough that one
/// request cannot hold the database for long.
pub const MAX_SNAPSHOT: usize = 20_000;
// The same in protobuf (#470): ipx reads and writes these through ipx-wire's structs, which
// mirror the ones above field for field.
use ipx_wire::pb::directory as pb;
impl From<pb::Listing> for Listing {
fn from(l: pb::Listing) -> Self {
Listing {
id: l.id,
url: l.url,
title: l.title,
image: l.image,
category: l.category,
subcategory: l.subcategory,
podcast: l.podcast,
subscribers: l.subscribers,
}
}
}
impl From<pb::Item> for Item {
fn from(i: pb::Item) -> Self {
Item {
guid: i.guid,
title: i.title,
link: i.link,
published: i.published,
duration: i.duration,
description: i.description,
}
}
}
impl From<pb::FeedPage> for FeedPage {
fn from(p: pb::FeedPage) -> Self {
FeedPage {
listing: Listing {
id: p.id,
url: p.url,
title: p.title,
image: p.image,
category: p.category,
subcategory: p.subcategory,
podcast: p.podcast,
subscribers: p.subscribers,
},
description: p.description,
failing: p.failing,
items: p.items.into_iter().map(Item::from).collect(),
}
}
}
impl TryFrom<pb::Me> for Me {
type Error = String;
fn try_from(m: pb::Me) -> Result<Self, String> {
let access = match m.access.as_str() {
"ro" => Access::Ro,
"rw" => Access::Rw,
"rwa" => Access::Rwa,
other => return Err(format!("an access level not known here: {other:?}")),
};
Ok(Me { name: m.name, access })
}
}
impl From<pb::Instance> for Instance {
fn from(i: pb::Instance) -> Self {
Instance { name: i.name, feeds: i.feeds, subscribers: i.subscribers }
}
}
impl From<pb::Blocked> for Blocked {
fn from(b: pb::Blocked) -> Self {
Blocked { id: b.id, url: b.url, title: b.title, at: b.at }
}
}
impl From<pb::SnapshotResult> for SnapshotResult {
fn from(r: pb::SnapshotResult) -> Self {
let n = |v: u64| usize::try_from(v).unwrap_or(usize::MAX);
SnapshotResult {
accepted: n(r.accepted),
refused_private: n(r.refused_private),
refused_blocked: n(r.refused_blocked),
refused_invalid: n(r.refused_invalid),
}
}
}
impl From<&SnapshotEntry> for pb::SnapshotEntry {
fn from(e: &SnapshotEntry) -> Self {
pb::SnapshotEntry { url: e.url.clone(), subscribers: e.subscribers, category: e.category.clone() }
}
}

View File

@@ -14,6 +14,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `GET /api/feeds/{id}/seasons` gives a podcast's seasons with how many episodes and unread each has, and a podcast's episodes can be asked for one season at a time, or for those naming none (`season=none`), and in its own order (`sort=episode`), season by season and episode by episode. `download-latest` takes a `season` to download all of it, first episode first (#482).
- Smart playlists: `GET` and `POST /api/playlists`, `PATCH` and `DELETE /api/playlists/{id}`, and `GET /api/playlists/{id}/entries`, the episodes of the podcasts chosen in the playlist's order, those set to play first ahead of the rest (#476).
- A feed in `/api/feeds` says whether it has audio or video (`podcast`), for the page's Podcasts shelf (#474).
- Up Next, a queue of episodes kept per account so every device shares it: `GET /api/queue` lists it in order, `PUT /api/queue` sets it, and an episode leaves it once it is 90% played (#473).
- The API answers in protobuf as well as JSON: a client that sends `Accept: application/x-protobuf` gets protobuf, and one that sends `Content-Type: application/x-protobuf` may send its body so; JSON stays the default for a client that does not ask, and an answer of null stays JSON. The messages are in `crates/wire/proto/ipx.proto`. ipx's own calls to the directory and ipx-play go in protobuf too, so both need their protobuf releases first. Answers and those calls go through structs generated from the `.proto` files, about four times quicker to read than the JSON (#465, #470).
- Sharing an episode gives a link to its page on ipx-play, which anyone can open and play, set up in Admin, Directory, Sharing episodes; private and paid feeds still share their own address (#447).
- The iOS app's icon count stays right with the app closed: with `[push]` set to an APNs key, ipx sends each registered phone (`POST /api/push/devices`, removed with `DELETE`) its All Subscriptions unread count through Apple's push service, within a minute of a change (#433). The push also wakes the app for a moment, for its widget to show the same count (#428).
- A place in an episode saved from DeadAir's shortened version names its file (`deadair` in `POST .../position`), so it is read in that version's clock even when ipx never handed out its playlist, as for a copy kept on the device or after a restart (#412).
@@ -31,6 +36,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- A feed an OPML stops listing leaves All Subscriptions with it, rather than its items staying there with no feed name beside them: the scan no longer reads it again after the list drops it, and its subscriptions go with it, as they do when a feed is removed with `ipx rm`. Any left from before are removed when ipx starts (#478).
- Searching All Subscriptions answers in a fraction of a second, not five: a search reads each item's title and text without its markup, indexed on Postgres, and still finds part of a word. It no longer matches words inside the HTML's tags, such as a link's address. Text past the first 4,000 characters of a very long post is not searched (#459, #472).
- Artwork that cannot be shown is asked for again a day later rather than every hour: one too large is refused on its stated size before it is read, and a refusal from the publisher or one ipx makes (too large, not an image) is remembered for a day; JPEG XL pictures sent without a type are shown (#448).
- `ipx reap --dry-run` says "would delete" of each file and of the total, rather than "deleted", word for word a real reap, of files it kept (#461).
- Subscribing to a feed someone here already reads puts its recent items to your Signals at once, rather than at the judge's next pass, up to five minutes later (#415).
- A download a restart stopped, a deploy's for one, is taken up again as the daemon starts, rather than waiting for its feed's next check, an hour or a day away (#410).
- A YouTube channel no longer misses most days' videos: YouTube answers some feed requests with a 404 or 500 it does not mean, and ipx now asks again, twice, a second apart, before calling the feed failing (#382), and then every hour for a day where it would have waited a day, since YouTube's failures run for hours; and its YouTube feeds are read one at a time, two seconds apart, since YouTube refuses many asked together (#386).
@@ -40,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
- Show notes are cleaned with ammonia 4.2.5, which no longer lets SVG or MathML in a feed's HTML carry script past it (RUSTSEC-2026-0533); Markdown items are read with pulldown-cmark 0.13.6, and compressed feeds and answers with zstd 0.14.4 and zstd-safe 8.3, each closing published advisories (#467).
- Ten wrong passwords from one address in a quarter hour hold that address off sign-in for the rest of it, answered `429` with how long to wait; before, a guesser could try as fast as the server checked. The address is the one a trusted proxy names last in `X-Forwarded-For`, or the peer's (#409).
## [1.5.1] - 2026-10-24

View File

@@ -17,6 +17,7 @@ workspace = true
ipx-feed.workspace = true
ipx-directory.workspace = true
ipx-play.workspace = true
ipx-wire.workspace = true
ammonia.workspace = true
anyhow.workspace = true
argon2.workspace = true

View File

@@ -92,6 +92,10 @@ pub fn write(file: &Path, kind: &str, body: &[u8]) -> std::io::Result<()> {
/// How long an address that could not be fetched is answered from memory before it is tried again.
const RETRY: Duration = Duration::from_secs(60 * 60);
/// The same for a failure the publisher will not change by morning: too large, not an image, a
/// 4xx. At an hour, five GIFs over the limit were read 20 MB at a time 37 times each in five days,
/// about 3 GB for nothing (#448).
const RETRY_LASTING: Duration = Duration::from_secs(24 * 60 * 60);
/// Addresses that could not be fetched lately, and why. Without it a page shown again fetched
/// them again: five covers too big to keep were downloaded from Patreon on every load (#169).
@@ -99,7 +103,7 @@ const RETRY: Duration = Duration::from_secs(60 * 60);
// one per artwork address a feed or item names; move it to disk or prune it on trim if that grows.
static FAILED: LazyLock<Mutex<HashMap<String, (Instant, String)>>> = LazyLock::new(Default::default);
/// Why `url` could not be fetched, if it failed less than an hour ago.
/// Why `url` could not be fetched, if it failed lately: an hour, or a day for a lasting failure.
pub fn failed(url: &str) -> Option<String> {
failed_as_of(url, Instant::now())
}
@@ -107,7 +111,7 @@ pub fn failed(url: &str) -> Option<String> {
fn failed_as_of(url: &str, now: Instant) -> Option<String> {
let mut map = FAILED.lock().unwrap_or_else(|e| e.into_inner());
match map.get(url) {
Some((at, why)) if now.duration_since(*at) < RETRY => Some(why.clone()),
Some((until, why)) if now < *until => Some(why.clone()),
Some(_) => {
map.remove(url);
None
@@ -116,8 +120,9 @@ fn failed_as_of(url: &str, now: Instant) -> Option<String> {
}
}
pub fn fail(url: &str, why: &str) {
FAILED.lock().unwrap_or_else(|e| e.into_inner()).insert(url.to_owned(), (Instant::now(), why.to_owned()));
pub fn fail(url: &str, why: &str, lasting: bool) {
let until = Instant::now() + if lasting { RETRY_LASTING } else { RETRY };
FAILED.lock().unwrap_or_else(|e| e.into_inner()).insert(url.to_owned(), (until, why.to_owned()));
}
/// Removes the least recently used images until what is kept fits in `limit` bytes; 0 empties it.
@@ -184,13 +189,16 @@ mod tests {
}
#[test]
fn a_failure_is_remembered_for_an_hour() {
fn a_failure_is_remembered_for_an_hour_and_a_lasting_one_for_a_day() {
let u = "https://example.com/a-failure-is-remembered.png";
assert_eq!(failed(u), None);
fail(u, "larger than 5 MB");
assert_eq!(failed(u).as_deref(), Some("larger than 5 MB"));
fail(u, "timed out", false);
assert_eq!(failed(u).as_deref(), Some("timed out"));
assert_eq!(failed_as_of(u, Instant::now() + RETRY), None);
// Asked for after the hour, it is forgotten, not just ignored.
assert_eq!(failed(u), None);
fail(u, "larger than 20 MB", true);
assert_eq!(failed_as_of(u, Instant::now() + RETRY).as_deref(), Some("larger than 20 MB"));
assert_eq!(failed_as_of(u, Instant::now() + RETRY_LASTING), None);
}
}

View File

@@ -136,6 +136,10 @@ pub(crate) async fn rm(ctx: &Ctx, feed: &str) -> Result<()> {
return Ok(());
};
ctx.store_cfg(cfg).await?;
// Left subscribed, All Subscriptions listed its items with no feed to name them (#478).
for (user, _) in ctx.db.subscribers_of(feed).await? {
ctx.db.unsubscribe(user, feed).await?;
}
// State and files stay: re-adding the feed should not re-download its back catalogue.
println!("removed {feed}; downloads and history kept");
retire_group(ctx, feed, Some(&parent)).await?;
@@ -477,6 +481,27 @@ pub(crate) async fn retire_stranded(ctx: &Ctx) -> Result<usize> {
Ok(before.len() - ctx.db.managed_feeds().await?.len())
}
/// Unsubscribes everyone from feeds the catalogue no longer has, and returns how many feeds that
/// was. Removing a feed once left its subscriptions behind, 41 of them by 2026-11-19, and All
/// Subscriptions listed their items with no feed to name them (#478).
pub(crate) async fn drop_stray_subscriptions(ctx: &Ctx) -> Result<usize> {
let known: std::collections::HashSet<String> = subscriptions(ctx).await?.into_iter().map(|s| s.id).collect();
// A catalogue that came back empty is more likely a fault than a server with no feeds, and
// taking it at its word would unsubscribe everyone from everything.
if known.is_empty() {
return Ok(0);
}
let mut dropped = 0;
for feed in ctx.db.subscriber_counts().await?.into_keys().filter(|f| !known.contains(f)) {
for (user, _) in ctx.db.subscribers_of(&feed).await? {
ctx.db.unsubscribe(user, &feed).await?;
}
tracing::info!(feed = %feed, "unsubscribed everyone from a feed no longer in the catalogue");
dropped += 1;
}
Ok(dropped)
}
/// Puts each feed no longer derived in the group its catalogue entry says, and returns how many
/// moved. Made a feed of its own before #358, a show kept its list's group in the database, and
/// hiding the list from All Subscriptions hid it too.
@@ -712,6 +737,21 @@ mod tests {
assert_eq!(regroup_unmanaged(&ctx).await.unwrap(), 0, "nothing left to move");
}
#[tokio::test]
async fn a_subscription_to_a_feed_not_in_the_catalogue_is_dropped() {
let mut cfg = config::Config::default();
cfg.feeds.insert("opml".into(), feed());
let ctx = test_ctx(cfg).await;
let me = ctx.db.create_user("me", None, false).await.unwrap();
ctx.db.upsert_managed("listed", "http://x/l.xml", "Listed", "opml").await.unwrap();
for id in ["opml", "listed", "gone"] {
ctx.db.subscribe(me, id).await.unwrap();
}
assert_eq!(drop_stray_subscriptions(&ctx).await.unwrap(), 1);
let mine: Vec<String> = ctx.db.subscriptions_for(me).await.unwrap().into_iter().map(|s| s.feed_id).collect();
assert!(mine.contains(&"opml".into()) && mine.contains(&"listed".into()) && !mine.contains(&"gone".into()));
}
#[tokio::test]
async fn a_stranded_group_is_retired_but_a_promoted_feed_keeps_its_entries() {
// davewiner: the OPML left config before retire_group existed, and 11 of its feeds

View File

@@ -97,6 +97,12 @@ pub(crate) async fn daemon(
Ok(n) => tracing::info!(feeds = n, "retired feeds whose OPML is no longer in config"),
Err(e) => tracing::warn!(error = %format!("{e:#}"), "could not retire feeds whose OPML is no longer in config"),
}
// After retire_stranded, which drops feeds whose subscriptions this then finds.
match catalogue::drop_stray_subscriptions(&ctx).instrument(db::step("drop_stray_subscriptions")).await {
Ok(0) => {}
Ok(n) => tracing::info!(feeds = n, "unsubscribed everyone from feeds no longer in the catalogue"),
Err(e) => tracing::warn!(error = %format!("{e:#}"), "could not drop subscriptions to feeds no longer in the catalogue"),
}
match catalogue::regroup_unmanaged(&ctx).instrument(db::step("regroup_unmanaged")).await {
Ok(0) => {}
Ok(n) => tracing::info!(feeds = n, "took feeds of their own out of their old list's group"),
@@ -162,6 +168,7 @@ pub(crate) async fn daemon(
tokio::spawn(signals::run(ctx.clone(), rx_stop.clone()));
tokio::spawn(directory::run(ctx.clone(), rx_stop.clone()));
tokio::spawn(crate::push::run(ctx.clone(), rx_stop.clone()));
tokio::spawn(crate::search::run(ctx.clone(), rx_stop.clone()));
// The library's counts for /metrics. The Docker healthcheck asked for them every 30 s until
// it was removed: Docker runs it with exec, which failed on Tower whenever root was logged
// out (#218).

View File

@@ -2,8 +2,8 @@
//! per-feed .ipxd plists, history.dat and qmcache.dat.
use crate::entity::{
api_tokens, blocklists, catalogue, deadair_prefs, enclosures, entries, feeds, hidden, push_devices, sessions,
settings, signal_verdicts, signals, subscriptions, users,
api_tokens, blocklists, catalogue, deadair_prefs, enclosures, entries, feeds, hidden, playlists, push_devices,
sessions, settings, signal_verdicts, signals, subscriptions, users,
};
use anyhow::{Context, Result};
use sea_orm::sea_query::{Expr, Func};
@@ -73,6 +73,8 @@ async fn create_missing(orm: &DatabaseConnection) -> Result<()> {
schema.create_table_from_entity(signals::Entity),
schema.create_table_from_entity(signal_verdicts::Entity),
schema.create_table_from_entity(push_devices::Entity),
schema.create_table_from_entity(queue::Entity),
schema.create_table_from_entity(playlists::Entity),
] {
orm.execute(table.if_not_exists()).await.context("creating the schema")?;
}
@@ -181,6 +183,15 @@ async fn create_missing(orm: &DatabaseConnection) -> Result<()> {
let sql = "ALTER TABLE deadair_prefs ADD COLUMN pause_ms BIGINT";
orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?;
}
if orm.execute_unprepared("SELECT search_text FROM entries LIMIT 0").await.is_err() {
// Every stored item starts without one: search.rs fills them in, behind the daemon (#459).
let sql = "ALTER TABLE entries ADD COLUMN search_text TEXT";
orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?;
}
// The items whose search text is still to be made: what search.rs looks for, and what a search
// reads the old way meanwhile. Empty once they are made, so finding none costs nothing.
let sql = "CREATE INDEX IF NOT EXISTS entries_unsearched ON entries (feed_id) WHERE search_text IS NULL";
orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?;
Ok(())
}
@@ -601,6 +612,16 @@ impl Db {
),
vec![user_id.into(), one()],
);
// Whether a feed has any audio or video, for the Podcasts shelf (#474). EXISTS, so a podcast
// stops at its first episode, and a feed with no files is one probe of enclosures_entry.
let media = counts(
"media",
"SELECT sub.feed_id, CAST(1 AS BIGINT) AS n FROM subscriptions sub
WHERE sub.user_id = $1 AND (CAST($2 AS TEXT) IS NULL OR sub.feed_id = $2)
AND EXISTS (SELECT 1 FROM enclosures x WHERE x.feed_id = sub.feed_id
AND (lower(x.mime) LIKE 'audio/%' OR lower(x.mime) LIKE 'video/%'))",
vec![user_id.into(), one()],
);
let blocked = Instrument::instrument(
blocklists::Entity::find().filter(blocklists::Column::UserId.eq(user_id)).all(&self.orm),
step("blocked"),
@@ -610,10 +631,11 @@ impl Db {
rows = rows.filter(feeds::Column::Id.eq(id));
}
let rows = Instrument::instrument(rows.all(&self.orm), step("feeds"));
let (entries, downloaded, unread, blocked, rows) = tokio::try_join!(
let (entries, downloaded, unread, media, blocked, rows) = tokio::try_join!(
entries,
downloaded,
unread,
media,
async { blocked.await.map_err(anyhow::Error::from) },
async { rows.await.map_err(anyhow::Error::from) },
)?;
@@ -639,6 +661,7 @@ impl Db {
ttl_mins: f.ttl_mins.map(|t| t.max(0) as u64),
blocked: blocked.remove(&id).unwrap_or_default(),
unread: unread.get(&id).copied().unwrap_or(0),
podcast: media.contains_key(&id),
};
(id, listing)
})
@@ -653,6 +676,8 @@ pub struct FeedListing {
pub ttl_mins: Option<u64>,
pub blocked: Vec<String>,
pub unread: i64,
/// It has an audio or video file, so it is on the Podcasts shelf (#474).
pub podcast: bool,
}
/// Everything `fetch` needs to decide whether to poll a feed, and how.
@@ -803,8 +828,8 @@ impl Db {
.exec(
"INSERT INTO entries
(feed_id, guid, title, link, published, description, first_seen,
image, duration, episode, season, markdown)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
image, duration, episode, season, markdown, search_text)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
ON CONFLICT DO NOTHING",
vec![
feed_id.into(),
@@ -819,6 +844,7 @@ impl Db {
e.episode.into(),
e.season.into(),
e.markdown.clone().into(),
crate::search::search_text(e.title.as_deref(), e.description.as_deref()).into(),
],
)
.await?;
@@ -831,7 +857,12 @@ impl Db {
duration = coalesce($6, duration),
episode = coalesce($7, episode),
season = coalesce($8, season),
markdown = coalesce($9, markdown)
markdown = coalesce($9, markdown),
-- Made again, by search.rs, when what it is made of has changed; the values
-- here are the row's as it was.
search_text = CASE WHEN title IS NOT DISTINCT FROM coalesce($3, title)
AND description IS NOT DISTINCT FROM coalesce($4, description)
THEN search_text END
WHERE feed_id = $1 AND guid = $2",
vec![
feed_id.into(),
@@ -1074,6 +1105,72 @@ impl Db {
Ok(())
}
/// Up to `limit` items whose search text is still to be made: feed, guid, title, description.
pub async fn unsearched(&self, limit: i64) -> Result<Vec<(String, String, Option<String>, Option<String>)>> {
self.rows(
"SELECT feed_id, guid, title, description FROM entries WHERE search_text IS NULL LIMIT $1",
vec![limit.into()],
)
.await?
.iter()
.map(|r| {
Ok((
r.try_get("", "feed_id")?,
r.try_get("", "guid")?,
r.try_get("", "title")?,
r.try_get("", "description")?,
))
})
.collect()
}
pub async fn set_search_text(&self, feed_id: &str, guid: &str, text: &str) -> Result<()> {
self.exec(
"UPDATE entries SET search_text = $3 WHERE feed_id = $1 AND guid = $2",
vec![feed_id.into(), guid.into(), text.into()],
)
.await?;
Ok(())
}
/// The trigram index a search uses on Postgres (#459), made once, beside the scans rather than
/// in their way (CONCURRENTLY), and made again if a build of it was cut off, which leaves it
/// there but unused. SQLite has no pg_trgm and reads the column whole, which is still a
/// fraction of the HTML. False when Postgres would not give pg_trgm, which a search survives.
pub async fn search_index(&self) -> Result<bool> {
if self.orm.get_database_backend() != sea_orm::DbBackend::Postgres {
return Ok(true);
}
let valid = self
.rows(
"SELECT i.indisvalid AS valid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
WHERE c.relname = 'entries_search' AND pg_table_is_visible(c.oid)",
vec![],
)
.await?
.first()
.map(|r| r.try_get::<bool>("", "valid"))
.transpose()?;
match valid {
Some(true) => return Ok(true),
Some(false) => {
self.orm.execute_unprepared("DROP INDEX CONCURRENTLY entries_search").await?;
}
None => {}
}
if let Err(e) = self.orm.execute_unprepared("CREATE EXTENSION IF NOT EXISTS pg_trgm").await {
tracing::warn!(error = %e, "search: pg_trgm could not be installed; searches read every item's text");
return Ok(false);
}
self.orm
.execute_unprepared(
"CREATE INDEX CONCURRENTLY entries_search ON entries USING gin (search_text gin_trgm_ops)",
)
.await
.context("indexing entries.search_text")?;
Ok(true)
}
/// A feed's stored artwork still on http, items' and its own: hosts a feed no longer names
/// keep their old items' artwork on http otherwise (IGN's 2009 items, #110).
pub async fn http_images(&self, feed_id: &str) -> Result<Vec<String>> {
@@ -1234,6 +1331,9 @@ impl Args {
/// The FROM and WHERE that `entries_in` and `count_in` share: whose read state, which feeds
/// (one, or every feed the person subscribes to), the filter, and a case-insensitive search of
/// title and description.
// Each is one of the list's own dimensions, as entries_where takes them; a struct of them would be
// built only to be taken apart here.
#[allow(clippy::too_many_arguments)]
fn entries_from(
a: &mut Args,
user_id: i64,
@@ -1242,8 +1342,18 @@ fn entries_from(
search: Option<&str>,
guid: Option<&str>,
signal: Option<i64>,
season: Season,
pg: bool,
) -> String {
let user = a.p(user_id);
// A search on Postgres is given this person's feeds as an array, not a subquery: with the
// subquery it matched the words in every feed on the server and joined to theirs after, 61,674
// items re-read for 1,151 of theirs, 1.5 s for "apple"; with the array it picks per search the
// feeds' index or the words', 0.4 s and 21 ms (#472). SQLite has no arrays and keeps the IN.
let searching = search.is_some_and(|q| !q.trim().is_empty());
let mine = |sub: String| {
if pg && searching { format!("e.feed_id = ANY(ARRAY({sub}))") } else { format!("e.feed_id IN ({sub})") }
};
let mut scope = match feeds {
// One feed as before, so its page keeps its plan: an OR with the shows' list, or an IN
// over a subquery, took clarkesworld's from 10 ms to 26 ms or a second (#283).
@@ -1253,19 +1363,15 @@ fn entries_from(
// A Signal and All Subscriptions leave out what this person hid from them (#288, #289).
// An episode under way still shows in Currently Listening, which is All Subscriptions'
// in-progress filter.
None if signal.is_some() => {
format!(
"e.feed_id IN (SELECT m.feed_id FROM subscriptions m WHERE m.user_id = {user} AND {})",
shown_in("hide_from_signals", "m")
)
}
None if filter != Filter::InProgress => {
format!(
"e.feed_id IN (SELECT m.feed_id FROM subscriptions m WHERE m.user_id = {user} AND {})",
shown_in("hide_from_all", "m")
)
}
None => format!("e.feed_id IN (SELECT feed_id FROM subscriptions WHERE user_id = {user})"),
None if signal.is_some() => mine(format!(
"SELECT m.feed_id FROM subscriptions m WHERE m.user_id = {user} AND {}",
shown_in("hide_from_signals", "m")
)),
None if filter != Filter::InProgress => mine(format!(
"SELECT m.feed_id FROM subscriptions m WHERE m.user_id = {user} AND {}",
shown_in("hide_from_all", "m")
)),
None => mine(format!("SELECT feed_id FROM subscriptions WHERE user_id = {user}")),
};
if let Some(id) = signal {
scope = format!(
@@ -1276,14 +1382,23 @@ fn entries_from(
if let Some(g) = guid {
scope = format!("{scope} AND e.guid = {}", a.p(g));
}
match season {
Season::Any => {}
Season::Of(n) => scope = format!("{scope} AND e.season = {}", a.p(n)),
Season::Unnumbered => scope = format!("{scope} AND e.season IS NULL"),
}
let search = match search.map(|q| q.trim().to_lowercase()).filter(|q| !q.is_empty()) {
Some(q) => {
// % and _ as typed, not as wildcards: "100%" matched anything starting 100 (#296).
let q = q.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_");
let like = a.p(format!("%{q}%"));
// The title and the text without its markup, lowercased (search.rs), which pg_trgm
// indexes: matching the HTML took 5 s for All Subscriptions, most of it reading 4 GB of
// descriptions (#459). An item not yet given one is matched the old way.
format!(
"(lower(coalesce(e.title, '')) LIKE {like} ESCAPE '\\' \
OR lower(coalesce(e.description, '')) LIKE {like} ESCAPE '\\')"
"(e.search_text LIKE {like} ESCAPE '\\' \
OR (e.search_text IS NULL AND (lower(coalesce(e.title, '')) LIKE {like} ESCAPE '\\' \
OR lower(coalesce(e.description, '')) LIKE {like} ESCAPE '\\')))"
)
}
None => "true".into(),
@@ -1335,6 +1450,14 @@ fn not_hidden(user: &str) -> String {
/// Pinned items are not lifted above the rest: sorting by the pin column, or the Pinned tab, does
/// that when it is wanted, and lifting them always was undone (issues #35 and #36).
pub fn order_sql(col: &str, dir: &str) -> String {
// A podcast told in seasons in its own order (#482): season by season, episode by episode, the
// episodes naming neither last whichever way round.
if col == "episode" {
let d = if dir == "desc" { "DESC" } else { "ASC" };
return format!(
"e.season {d} NULLS LAST, e.episode {d} NULLS LAST, coalesce(e.published, e.first_seen) {d}, e.guid {d}"
);
}
let expr = match col {
"kept" => "coalesce(s.flagged, false)",
"title" => "lower(coalesce(e.title, ''))",
@@ -1351,6 +1474,58 @@ pub fn order_sql(col: &str, dir: &str) -> String {
format!("{expr} {dir}, coalesce(e.published, e.first_seen) DESC, e.guid DESC")
}
/// A smart playlist as it is made and kept (#476): which podcasts, which of them come first, and
/// which of their episodes.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PlaylistSpec {
pub name: String,
pub feeds: Vec<String>,
#[serde(default)]
pub priority: Vec<String>,
#[serde(default)]
pub only_unplayed: bool,
#[serde(default)]
pub oldest_first: bool,
}
/// A playlist in the list, with how many episodes it holds now.
#[derive(Debug, serde::Serialize)]
pub struct PlaylistRow {
pub id: i64,
#[serde(flatten)]
pub spec: PlaylistSpec,
pub items: i64,
}
/// A playlist's order: its priority podcasts' episodes first, then by date, newest or oldest
/// first. The ids are written into the SQL, so each is quoted; they are feed ids this person
/// subscribes to, slugs, but the quoting does not rely on that.
pub fn playlist_order(spec: &PlaylistSpec) -> String {
let by_date = order_sql("published", if spec.oldest_first { "asc" } else { "desc" });
if spec.priority.is_empty() {
return by_date;
}
let ids = spec.priority.iter().map(|f| format!("'{}'", f.replace('\'', "''"))).collect::<Vec<_>>().join(", ");
format!("CASE WHEN e.feed_id IN ({ids}) THEN 0 ELSE 1 END, {by_date}")
}
/// Which of a podcast's seasons a list is of (#482): every one, one by its number, or the episodes
/// that name none.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Season {
Any,
Of(i64),
Unnumbered,
}
/// A season of a podcast, as its page offers it: None for the episodes that name none.
#[derive(Debug, PartialEq, Eq, serde::Serialize)]
pub struct SeasonCount {
pub season: Option<i64>,
pub episodes: i64,
pub unread: i64,
}
/// Which slice of a feed the UI is asking for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Filter {
@@ -1442,7 +1617,7 @@ impl Db {
order: &str,
) -> Result<Vec<EntryRow>> {
let feeds = feed_id.as_ref().map(std::slice::from_ref);
self.entries_where(user_id, feeds, filter, search, None, None, offset, limit, order).await
self.entries_where(user_id, feeds, filter, search, None, None, Season::Any, offset, limit, order).await
}
/// As `entries_in`, for several feeds together (an OPML's shows, #283), or every subscribed
@@ -1458,7 +1633,63 @@ impl Db {
limit: i64,
order: &str,
) -> Result<Vec<EntryRow>> {
self.entries_where(user_id, feeds, filter, search, None, None, offset, limit, order).await
self.entries_where(user_id, feeds, filter, search, None, None, Season::Any, offset, limit, order).await
}
/// As `entries_of`, for one season of the feeds (#482).
#[allow(clippy::too_many_arguments)]
pub async fn season_entries(
&self,
user_id: i64,
feeds: &[&str],
season: Season,
filter: Filter,
search: Option<&str>,
offset: i64,
limit: i64,
order: &str,
) -> Result<Vec<EntryRow>> {
self.entries_where(user_id, Some(feeds), filter, search, None, None, season, offset, limit, order).await
}
/// As `count_of`, for one season of the feeds (#482).
pub async fn season_count(
&self,
user_id: i64,
feeds: &[&str],
season: Season,
filter: Filter,
search: Option<&str>,
) -> Result<i64> {
self.count_where(user_id, Some(feeds), season, filter, search).await
}
/// The seasons of the feeds, newest first and the episodes naming none last, each with how
/// many of its episodes the list holds and how many are unread: what the season picker offers
/// (#482). The same FROM as the lists, so a count is what picking it shows.
pub async fn seasons(&self, user_id: i64, feeds: &[&str]) -> Result<Vec<SeasonCount>> {
let count = |filter| {
let mut a = Args::default();
let from = entries_from(&mut a, user_id, Some(feeds), filter, None, None, None, Season::Any, self.pg());
(format!("SELECT e.season, count(*) AS n {from} GROUP BY e.season"), a.0)
};
let read = |rows: Vec<sea_orm::QueryResult>| -> Result<std::collections::HashMap<Option<i64>, i64>> {
rows.iter().map(|r| Ok((r.try_get("", "season")?, r.try_get("", "n")?))).collect()
};
let (all, unread) = (count(Filter::All), count(Filter::Unread));
let all = read(self.rows(&all.0, all.1).await?)?;
let unread = read(self.rows(&unread.0, unread.1).await?)?;
let mut out: Vec<SeasonCount> = all
.into_iter()
.map(|(season, episodes)| SeasonCount {
season,
episodes,
unread: unread.get(&season).copied().unwrap_or(0),
})
.collect();
// Lowest season first, as the podcast runs; the episodes naming none last.
out.sort_by_key(|s| (s.season.is_none(), s.season));
Ok(out)
}
/// The shows of an OPML (or a Patreon creator) this person subscribes to (#283).
@@ -1487,13 +1718,15 @@ impl Db {
limit: i64,
order: &str,
) -> Result<Vec<EntryRow>> {
self.entries_where(user_id, None, filter, search, None, Some(signal), offset, limit, order).await
self.entries_where(user_id, None, filter, search, None, Some(signal), Season::Any, offset, limit, order).await
}
pub async fn signal_count(&self, user_id: i64, signal: i64, filter: Filter, search: Option<&str>) -> Result<i64> {
let mut a = Args::default();
let sql =
format!("SELECT count(*) AS n {}", entries_from(&mut a, user_id, None, filter, search, None, Some(signal)));
let sql = format!(
"SELECT count(*) AS n {}",
entries_from(&mut a, user_id, None, filter, search, None, Some(signal), Season::Any, self.pg())
);
let r = self.rows(&sql, a.0).await?;
Ok(r.first().context("count(*) always returns a row")?.try_get("", "n")?)
}
@@ -1503,7 +1736,7 @@ impl Db {
pub async fn entry(&self, user_id: i64, feed_id: &str, guid: &str) -> Result<Option<EntryRow>> {
let order = order_sql("published", "desc");
Ok(self
.entries_where(user_id, Some(&[feed_id]), Filter::All, None, Some(guid), None, 0, 1, &order)
.entries_where(user_id, Some(&[feed_id]), Filter::All, None, Some(guid), None, Season::Any, 0, 1, &order)
.await?
.pop())
}
@@ -1517,12 +1750,13 @@ impl Db {
search: Option<&str>,
guid: Option<&str>,
signal: Option<i64>,
season: Season,
offset: i64,
limit: i64,
order: &str,
) -> Result<Vec<EntryRow>> {
let mut a = Args::default();
let from = entries_from(&mut a, user_id, feeds, filter, search, guid, signal);
let from = entries_from(&mut a, user_id, feeds, filter, search, guid, signal, season, self.pg());
// The page's keys first, then its rows: the sort then needs only `entries_by_time`, not
// every item's row, and the show notes are read for the page alone (#188).
let (limit, offset) = (a.p(limit), a.p(offset));
@@ -1606,9 +1840,21 @@ impl Db {
feeds: Option<&[&str]>,
filter: Filter,
search: Option<&str>,
) -> Result<i64> {
self.count_where(user_id, feeds, Season::Any, filter, search).await
}
async fn count_where(
&self,
user_id: i64,
feeds: Option<&[&str]>,
season: Season,
filter: Filter,
search: Option<&str>,
) -> Result<i64> {
let mut a = Args::default();
let sql = if filter == Filter::Unread && search.is_none() {
// The feed list's own count, feed by feed, knows nothing of seasons.
let sql = if filter == Filter::Unread && search.is_none() && season == Season::Any {
// Feed by feed, as the feed list counts (#352); the same feeds as `entries_from`.
let user = a.p(user_id);
let scope = match feeds {
@@ -1623,7 +1869,10 @@ impl Db {
unread_in_sub!()
)
} else {
format!("SELECT count(*) AS n {}", entries_from(&mut a, user_id, feeds, filter, search, None, None))
format!(
"SELECT count(*) AS n {}",
entries_from(&mut a, user_id, feeds, filter, search, None, None, season, self.pg())
)
};
let r = self.rows(&sql, a.0).await?;
Ok(r.first().context("count(*) always returns a row")?.try_get("", "n")?)
@@ -1652,6 +1901,64 @@ impl Db {
vec![user_id.into(), feed_id.into(), guid.into(), secs.max(0).into(), duration.filter(|d| *d > 0).into()],
)
.await?;
// A finished episode leaves Up Next (#473), at the 90% where the page calls it played, so
// every device agrees on what is next without each having to say so.
self.exec(
"DELETE FROM queue WHERE user_id = $1 AND feed_id = $2 AND guid = $3 AND EXISTS (
SELECT 1 FROM entry_state s JOIN entries e ON e.feed_id = s.feed_id AND e.guid = s.guid
WHERE s.user_id = $1 AND s.feed_id = $2 AND s.guid = $3
AND coalesce(s.duration, e.duration) > 0
AND s.position * 10 >= coalesce(s.duration, e.duration) * 9)",
vec![user_id.into(), feed_id.into(), guid.into()],
)
.await?;
Ok(())
}
/// Up Next (#473), in order, each episode as `entry` gives it. Only feeds still subscribed to,
/// and only episodes still there: retention may have taken one since it was queued.
// shortcut: one query per queued episode, fine for the tens a queue holds; join the queue into
// entries_where if queues ever run to hundreds.
pub async fn queue_of(&self, user_id: i64) -> Result<Vec<EntryRow>> {
let keys = self
.rows(
"SELECT q.feed_id, q.guid FROM queue q
JOIN subscriptions s ON s.user_id = q.user_id AND s.feed_id = q.feed_id
WHERE q.user_id = $1 ORDER BY q.pos",
vec![user_id.into()],
)
.await?;
let mut out = Vec::with_capacity(keys.len());
for k in keys {
let (feed, guid): (String, String) = (k.try_get("", "feed_id")?, k.try_get("", "guid")?);
out.extend(self.entry(user_id, &feed, &guid).await?);
}
Ok(out)
}
/// Puts Up Next in the order given, in one transaction. An episode that does not exist, or is
/// in a feed this person does not subscribe to, is left out; one given twice keeps its first
/// place.
// shortcut: the whole list replaced, so the last device to write wins; per-item adds and moves
// if two devices editing at once ever lose one's change.
pub async fn set_queue(&self, user_id: i64, items: &[(String, String)]) -> Result<()> {
use sea_orm::TransactionTrait;
let backend = self.orm.get_database_backend();
let tx = self.orm.begin().await?;
let run = |sql: &str, v: Vec<sea_orm::Value>| Statement::from_sql_and_values(backend, sql, v);
tx.execute_raw(run("DELETE FROM queue WHERE user_id = $1", vec![user_id.into()])).await?;
for (pos, (feed, guid)) in items.iter().enumerate() {
tx.execute_raw(run(
"INSERT INTO queue (user_id, feed_id, guid, pos)
SELECT s.user_id, e.feed_id, e.guid, $4 FROM entries e
JOIN subscriptions s ON s.user_id = $1 AND s.feed_id = e.feed_id
WHERE e.feed_id = $2 AND e.guid = $3
ON CONFLICT DO NOTHING",
vec![user_id.into(), feed.clone().into(), guid.clone().into(), (pos as i64).into()],
))
.await?;
}
tx.commit().await?;
Ok(())
}
@@ -1740,6 +2047,10 @@ impl Db {
Ok(n)
}
fn pg(&self) -> bool {
self.orm.get_database_backend() == sea_orm::DbBackend::Postgres
}
async fn rows(&self, sql: &str, values: Vec<sea_orm::Value>) -> Result<Vec<sea_orm::QueryResult>> {
let (stmt, started) = (self.stmt(sql, values), std::time::Instant::now());
let rows = self.orm.query_all_raw(stmt).await?;
@@ -2361,14 +2672,25 @@ impl Db {
/// The next N enclosures with no file, newest entry first -- what "download latest"
/// queues up.
pub async fn undownloaded(&self, feed_id: &str, limit: i64) -> Result<Vec<i64>> {
/// A feed's files not downloaded, newest first, or one season's in its own order (#482): what
/// Download latest, or Download this season, queues.
pub async fn undownloaded(&self, feed_id: &str, season: Season, limit: i64) -> Result<Vec<i64>> {
let mut a = Args::default();
let (feed, limit) = (a.p(feed_id), a.p(limit));
let (which, order) = match season {
Season::Any => (String::new(), order_sql("published", "desc")),
Season::Of(n) => (format!("AND e.season = {}", a.p(n)), order_sql("episode", "asc")),
Season::Unnumbered => ("AND e.season IS NULL".into(), order_sql("published", "asc")),
};
self.rows(
"SELECT x.id FROM enclosures x
JOIN entries e ON e.feed_id = x.feed_id AND e.guid = x.guid
WHERE x.feed_id = $1 AND x.path IS NULL AND x.state <> 'reaped'
ORDER BY coalesce(e.published, e.first_seen) DESC
LIMIT $2",
vec![feed_id.into(), limit.into()],
&format!(
"SELECT x.id FROM enclosures x
JOIN entries e ON e.feed_id = x.feed_id AND e.guid = x.guid
WHERE x.feed_id = {feed} AND x.path IS NULL AND x.state <> 'reaped' {which}
ORDER BY {order}
LIMIT {limit}"
),
a.0,
)
.await?
.iter()
@@ -2497,6 +2819,8 @@ impl Db {
self.exec("DELETE FROM feeds WHERE id = $1 AND managed", vec![id.into()]).await?;
self.exec("DELETE FROM entries WHERE feed_id = $1", vec![id.into()]).await?;
self.exec("DELETE FROM enclosures WHERE feed_id = $1 AND path IS NULL", vec![id.into()]).await?;
// Left behind, All Subscriptions listed the items of a feed no list had a name for (#478).
self.exec("DELETE FROM subscriptions WHERE feed_id = $1", vec![id.into()]).await?;
Ok(())
}
@@ -3073,6 +3397,74 @@ impl Db {
Ok(true)
}
/// This person's smart playlists (#476), by name, each with its count. A podcast unsubscribed
/// from since is left out of it, here and in its episodes.
pub async fn playlists(&self, user_id: i64) -> Result<Vec<PlaylistRow>> {
let mine: std::collections::HashSet<String> =
self.subscriptions_for(user_id).await?.into_iter().map(|s| s.feed_id).collect();
let rows = playlists::Entity::find()
.filter(playlists::Column::UserId.eq(user_id))
.order_by_asc(playlists::Column::Name)
.all(&self.orm)
.await?;
let mut out = Vec::with_capacity(rows.len());
for p in rows {
let mut spec = PlaylistSpec {
name: p.name,
feeds: serde_json::from_str(&p.feeds)?,
priority: serde_json::from_str(&p.priority)?,
only_unplayed: p.only_unplayed,
oldest_first: p.oldest_first,
};
spec.feeds.retain(|f| mine.contains(f));
spec.priority.retain(|f| spec.feeds.contains(f));
let feeds: Vec<&str> = spec.feeds.iter().map(String::as_str).collect();
let filter = if spec.only_unplayed { Filter::Unread } else { Filter::All };
let items = self.count_of(user_id, Some(&feeds), filter, None).await?;
out.push(PlaylistRow { id: p.id, spec, items });
}
Ok(out)
}
pub async fn playlist(&self, user_id: i64, id: i64) -> Result<Option<PlaylistRow>> {
Ok(self.playlists(user_id).await?.into_iter().find(|p| p.id == id))
}
/// Makes a playlist, or with `id` changes one of this person's: its id, or None when that one
/// is not theirs.
pub async fn save_playlist(&self, user_id: i64, id: Option<i64>, spec: &PlaylistSpec) -> Result<Option<i64>> {
let mut m = playlists::ActiveModel {
user_id: Set(user_id),
name: Set(spec.name.clone()),
feeds: Set(serde_json::to_string(&spec.feeds)?),
priority: Set(serde_json::to_string(&spec.priority)?),
only_unplayed: Set(spec.only_unplayed),
oldest_first: Set(spec.oldest_first),
..Default::default()
};
let Some(id) = id else {
m.created = Set(now());
return Ok(Some(m.insert(&self.orm).await?.id));
};
let theirs = playlists::Entity::find_by_id(id).one(&self.orm).await?.is_some_and(|p| p.user_id == user_id);
if !theirs {
return Ok(None);
}
m.id = Set(id);
m.update(&self.orm).await?;
Ok(Some(id))
}
pub async fn remove_playlist(&self, user_id: i64, id: i64) -> Result<bool> {
let n = playlists::Entity::delete_many()
.filter(playlists::Column::Id.eq(id))
.filter(playlists::Column::UserId.eq(user_id))
.exec(&self.orm)
.await?
.rows_affected;
Ok(n > 0)
}
pub async fn typesafe_key_set(&self, user_id: i64) -> Result<bool> {
Ok(users::Entity::find_by_id(user_id).one(&self.orm).await?.is_some_and(|u| u.typesafe_key.is_some()))
}
@@ -3478,12 +3870,15 @@ mod tests {
INSERT INTO entries (feed_id, guid, first_seen) VALUES ('f','a',0),('f','b',0),('f','c',0),('g','d',0),('h','e',0);
INSERT INTO entry_state (user_id, feed_id, guid, read) VALUES (1,'f','a',true),(2,'f','b',true);
INSERT INTO hidden (user_id, feed_id, guid) VALUES (1,'f','c');
INSERT INTO enclosures (id, feed_id, guid, url, path, state) VALUES
(1,'f','a','u1','/tmp/a','done'),(2,'f','b','u2',null,'pending');
INSERT INTO enclosures (id, feed_id, guid, url, path, state, mime) VALUES
(1,'f','a','u1','/tmp/a','done','Audio/MPEG'),(2,'f','b','u2',null,'pending',null),
(3,'g','d','u3',null,'skipped','image/jpeg');
INSERT INTO blocklists (user_id, feed_id, words) VALUES (1,'g','[\"spoiler\"]');",
).await
.unwrap();
let list = db.feed_list(1, None).await.unwrap();
// On the Podcasts shelf by having sound, whatever the case of its type; a picture is not (#474).
assert!(list["f"].podcast && !list["g"].podcast);
let g = db.feed_list(1, Some("g")).await.unwrap();
assert_eq!(g.keys().collect::<Vec<_>>(), ["g"]);
assert_eq!(
@@ -3655,6 +4050,53 @@ mod tests {
assert_eq!(files, ["u1"].map(String::from).into()); // u2 is g's: left to the insert to find
}
#[tokio::test]
async fn a_search_reads_the_words_and_an_item_without_search_text_the_old_way() {
let db = Db::memory().await.unwrap();
let me = db.create_user("me", None, false).await.unwrap();
db.exec_for_test(
"INSERT INTO feeds (id, url) VALUES ('f', 'http://x/f.xml');
INSERT INTO entries (feed_id, guid, title, description, first_seen) VALUES ('f','old','Old','<p>Banana</p>',1);",
)
.await
.unwrap();
db.subscribe(me, "f").await.unwrap();
let item = |text: &str| crate::feed::Entry {
guid: "a".into(),
title: Some("Apple news".into()),
description: Some(text.into()),
..Default::default()
};
db.record_entry("f", &item(r#"<p>Read <a href="https://shop.example">more</a></p>"#)).await.unwrap();
let order = order_sql("published", "desc");
let found = async |q: &str| -> Vec<String> {
let rows = db.entries_of(me, None, Filter::All, Some(q), 0, 50, &order).await.unwrap();
assert_eq!(db.count_of(me, None, Filter::All, Some(q)).await.unwrap(), rows.len() as i64, "{q}");
rows.into_iter().map(|r| r.guid).collect()
};
assert_eq!(found("APP").await, ["a"], "a part of a word, in any case");
assert_eq!(found("more").await, ["a"]);
assert!(found("shop.example").await.is_empty(), "an address in the markup is not a word of the post");
assert_eq!(found("banana").await, ["old"], "stored before search text, matched the old way");
for (f, g, t, d) in db.unsearched(100).await.unwrap() {
db.set_search_text(&f, &g, &crate::search::search_text(t.as_deref(), d.as_deref())).await.unwrap();
}
assert!(db.unsearched(100).await.unwrap().is_empty());
assert_eq!(found("banana").await, ["old"], "and by its search text once made");
// Told differently, it is made again; until then the old way finds the new words.
db.record_entry("f", &item("<p>Cherry</p>")).await.unwrap();
assert_eq!(db.unsearched(100).await.unwrap().len(), 1);
assert_eq!(found("cherry").await, ["a"]);
// Told the same, it keeps what it has.
for (f, g, t, d) in db.unsearched(100).await.unwrap() {
db.set_search_text(&f, &g, &crate::search::search_text(t.as_deref(), d.as_deref())).await.unwrap();
}
db.record_entry("f", &item("<p>Cherry</p>")).await.unwrap();
assert!(db.unsearched(100).await.unwrap().is_empty());
}
#[tokio::test]
async fn a_scan_finds_the_stored_items_the_feed_now_tells_differently() {
let db = Db::memory().await.unwrap();
@@ -3732,6 +4174,119 @@ mod tests {
assert_eq!(db.others_wanting(1, 3).await.unwrap(), (0, 0));
}
#[tokio::test]
async fn up_next_keeps_its_order_is_private_and_lets_go_of_what_is_finished() {
let db = Db::memory().await.unwrap();
db.exec_for_test(
"INSERT INTO users (id, name, is_admin) VALUES (1,'ray',true),(2,'sam',false);
INSERT INTO entries (feed_id, guid, title, first_seen, duration) VALUES
('f','a','One',100,600),('f','b','Two',200,600),('g','c','Three',300,600);",
)
.await
.unwrap();
db.subscribe(1, "f").await.unwrap();
db.subscribe(2, "f").await.unwrap();
let key = |f: &str, g: &str| (f.to_owned(), g.to_owned());
let guids = async |u| db.queue_of(u).await.unwrap().into_iter().map(|e| e.guid).collect::<Vec<_>>();
// Not subscribed to g, an episode that is not there, and one given twice: left out.
let asked = [key("f", "b"), key("g", "c"), key("f", "zz"), key("f", "a"), key("f", "b")];
db.set_queue(1, &asked).await.unwrap();
assert_eq!(guids(1).await, ["b", "a"], "in the order given");
assert!(guids(2).await.is_empty(), "sam's is their own");
db.set_position(1, "f", "b", 300, None).await.unwrap();
assert_eq!(guids(1).await, ["b", "a"], "half way is not finished");
db.set_position(1, "f", "b", 550, None).await.unwrap();
assert_eq!(guids(1).await, ["a"], "past 90% it leaves");
db.set_queue(1, &[]).await.unwrap();
assert!(guids(1).await.is_empty());
}
#[tokio::test]
async fn a_podcast_s_seasons_are_counted_and_listed_one_at_a_time() {
let db = Db::memory().await.unwrap();
db.exec_for_test(
"INSERT INTO users (id, name, is_admin) VALUES (1,'ray',true);
INSERT INTO entries (feed_id, guid, title, published, first_seen, season, episode) VALUES
('f','a','S1E1',200,200,1,1),('f','b','S1E2',100,100,1,2),('f','c','S2E1',300,300,2,1),
('f','d','Trailer',50,50,NULL,NULL),('g','e','Elsewhere',400,400,2,1);",
)
.await
.unwrap();
db.subscribe(1, "f").await.unwrap();
db.set_entry_flag(1, "f", "a", EntryFlag::Read, true).await.unwrap();
// Lowest first, the unnumbered last, each with its unread; another feed's season 2 is not in it.
let got = db.seasons(1, &["f"]).await.unwrap();
let want = [(Some(1), 2, 1), (Some(2), 1, 1), (None, 1, 1)];
assert_eq!(got.iter().map(|s| (s.season, s.episodes, s.unread)).collect::<Vec<_>>(), want);
let order = order_sql("published", "desc");
let titles = async |season| {
let rows = db.season_entries(1, &["f"], season, Filter::All, None, 0, 50, &order).await.unwrap();
assert_eq!(db.season_count(1, &["f"], season, Filter::All, None).await.unwrap(), rows.len() as i64);
rows.into_iter().map(|r| r.title.unwrap()).collect::<Vec<_>>()
};
// By date, newest first: S1E2 came out first, as a season's episodes sometimes do.
assert_eq!(titles(Season::Of(1)).await, ["S1E1", "S1E2"]);
assert_eq!(titles(Season::Unnumbered).await, ["Trailer"]);
assert_eq!(titles(Season::Any).await.len(), 4);
assert_eq!(db.season_count(1, &["f"], Season::Of(1), Filter::Unread, None).await.unwrap(), 1);
// In the podcast's own order, season by season, the episodes in none last either way round.
let (up, down) = (order_sql("episode", "asc"), order_sql("episode", "desc"));
let all = db.season_entries(1, &["f"], Season::Any, Filter::All, None, 0, 50, &up).await.unwrap();
assert_eq!(all.into_iter().map(|r| r.title.unwrap()).collect::<Vec<_>>(), ["S1E1", "S1E2", "S2E1", "Trailer"]);
let back = db.season_entries(1, &["f"], Season::Any, Filter::All, None, 0, 50, &down).await.unwrap();
assert_eq!(back.last().unwrap().title.as_deref(), Some("Trailer"));
}
#[tokio::test]
async fn a_playlist_puts_its_priority_podcasts_first_and_is_its_owners_alone() {
let db = Db::memory().await.unwrap();
db.exec_for_test(
"INSERT INTO users (id, name, is_admin) VALUES (1,'ray',true),(2,'sam',false);
INSERT INTO entries (feed_id, guid, title, published, first_seen) VALUES
('f','f1','F old',100,100),('f','f2','F new',300,300),('g','g1','G mid',200,200),('h','h1','H',400,400);",
)
.await
.unwrap();
for f in ["f", "g", "h"] {
db.subscribe(1, f).await.unwrap();
}
let spec = |priority: &[&str], oldest_first| PlaylistSpec {
name: "Commute".into(),
feeds: vec!["f".into(), "g".into()],
priority: priority.iter().map(|p| p.to_string()).collect(),
only_unplayed: false,
oldest_first,
};
let id = db.save_playlist(1, None, &spec(&[], false)).await.unwrap().unwrap();
let guids = async |s: &PlaylistSpec| {
let feeds: Vec<&str> = s.feeds.iter().map(String::as_str).collect();
let rows = db.entries_of(1, Some(&feeds), Filter::All, None, 0, 50, &playlist_order(s)).await.unwrap();
rows.into_iter().map(|e| e.guid).collect::<Vec<_>>()
};
assert_eq!(guids(&spec(&[], false)).await, ["f2", "g1", "f1"], "newest first, h not in it");
assert_eq!(guids(&spec(&[], true)).await, ["f1", "g1", "f2"], "oldest first");
assert_eq!(guids(&spec(&["g"], false)).await, ["g1", "f2", "f1"], "g first");
assert_eq!(guids(&spec(&["it's"], false)).await, ["f2", "g1", "f1"], "a quote is quoted");
let mine = db.playlists(1).await.unwrap();
assert_eq!((mine.len(), mine[0].items), (1, 3));
assert!(db.playlists(2).await.unwrap().is_empty(), "sam has none");
assert_eq!(db.save_playlist(2, Some(id), &spec(&[], true)).await.unwrap(), None, "not sam's to change");
assert!(!db.remove_playlist(2, id).await.unwrap(), "nor to remove");
db.exec_for_test("DELETE FROM subscriptions WHERE user_id = 1 AND feed_id = 'g'").await.unwrap();
let p = db.playlist(1, id).await.unwrap().unwrap();
assert_eq!((p.spec.feeds.as_slice(), p.items), (&["f".to_string()][..], 2), "g unsubscribed from");
assert!(db.remove_playlist(1, id).await.unwrap());
assert!(db.playlists(1).await.unwrap().is_empty());
}
#[tokio::test]
async fn read_state_belongs_to_one_person() {
let db = Db::memory().await.unwrap();

View File

@@ -5,6 +5,8 @@
use std::collections::{HashMap, HashSet};
use ipx_directory::{FeedPage, Listing, Me, SnapshotEntry, SnapshotResult};
use ipx_wire::Message as _;
use ipx_wire::pb::directory as pb;
use serde::de::DeserializeOwned;
use crate::catalogue::Sub;
@@ -65,6 +67,13 @@ pub fn configured(cfg: &config::Config) -> bool {
target(cfg).is_some()
}
/// How an answer in protobuf becomes what the caller wants (#470).
type Decode<T> = fn(&[u8]) -> Result<T, String>;
fn listings(b: &[u8]) -> Result<Vec<Listing>, String> {
Ok(pb::Listings::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Listing::from).collect())
}
/// A span the whole call, its answer read and parsed included: the directory's own span ends when it
/// has answered, so a slow read of a large answer showed under no span (#250).
#[tracing::instrument(name = "directory_call", skip_all, fields(http.request.method = %method, url.path = %path.split('?').next().unwrap_or(path), http.response.body.size))]
@@ -73,6 +82,7 @@ async fn call<T: DeserializeOwned>(
method: reqwest::Method,
path: &str,
body: Option<&[SnapshotEntry]>,
answer: Option<Decode<T>>,
) -> Result<T, DirError> {
let (base, token) = target(&ctx.cfg()).ok_or(DirError::NotConfigured)?;
let mut req =
@@ -81,15 +91,19 @@ async fn call<T: DeserializeOwned>(
if let Some(tp) = ipx_directory::otel::traceparent() {
req = req.header("traceparent", tp);
}
// A snapshot is about 100 KB of JSON, sent gzipped; the directory unpacks it (#253).
// Protobuf both ways (#465), where the answer has a message: a smaller body to read.
if answer.is_some() {
req = req.header(reqwest::header::ACCEPT, ipx_wire::PROTOBUF);
}
// A snapshot is about 100 KB, sent gzipped; the directory unpacks it (#253).
if let Some(b) = body {
use std::io::Write as _;
let json = serde_json::to_vec(b).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
let pb = pb::Snapshot { items: b.iter().map(pb::SnapshotEntry::from).collect() }.encode_to_vec();
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&json).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
gz.write_all(&pb).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
let packed = gz.finish().map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
req = req
.header(reqwest::header::CONTENT_TYPE, "application/json")
.header(reqwest::header::CONTENT_TYPE, ipx_wire::PROTOBUF)
.header(reqwest::header::CONTENT_ENCODING, "gzip")
.body(packed);
}
@@ -104,9 +118,16 @@ async fn call<T: DeserializeOwned>(
.unwrap_or_default();
return Err(DirError::Refused(status.as_u16(), msg));
}
let protobuf = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.is_some_and(|v| v.as_bytes().starts_with(ipx_wire::PROTOBUF.as_bytes()));
// A removal or an unblock answers 204, with nothing to read: that reads as null, which is ().
let body = resp.bytes().await.map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
tracing::Span::current().record("http.response.body.size", body.len());
if let Some(decode) = answer.filter(|_| protobuf) {
return decode(&body).map_err(|e| DirError::Unreachable(format!("its answer did not read: {e}")));
}
serde_json::from_slice(if body.is_empty() { b"null" } else { &body })
.map_err(|e| DirError::Unreachable(format!("its answer did not read: {e:#}")))
}
@@ -116,23 +137,31 @@ fn seg(s: &str) -> percent_encoding::PercentEncode<'_> {
}
pub async fn me(ctx: &Ctx) -> Result<Me, DirError> {
call(ctx, reqwest::Method::GET, "/v1/me", None).await
call(ctx, reqwest::Method::GET, "/v1/me", None, Some(|b| pb::Me::decode(b).map_err(|e| e.to_string())?.try_into()))
.await
}
pub async fn feeds(ctx: &Ctx) -> Result<Vec<Listing>, DirError> {
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/feeds", None).await?;
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/feeds", None, Some(listings)).await?;
note_art(got.iter());
Ok(got)
}
pub async fn popular(ctx: &Ctx) -> Result<Vec<Listing>, DirError> {
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/popular?limit=10", None).await?;
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/popular?limit=10", None, Some(listings)).await?;
note_art(got.iter());
Ok(got)
}
pub async fn page(ctx: &Ctx, id: &str) -> Result<FeedPage, DirError> {
let got: FeedPage = call(ctx, reqwest::Method::GET, &format!("/v1/feeds/{}", seg(id)), None).await?;
let got: FeedPage = call(
ctx,
reqwest::Method::GET,
&format!("/v1/feeds/{}", seg(id)),
None,
Some(|b| pb::FeedPage::decode(b).map(FeedPage::from).map_err(|e| e.to_string())),
)
.await?;
note_art(std::iter::once(&got.listing));
Ok(got)
}
@@ -157,29 +186,45 @@ pub fn listed_art(url: &str) -> bool {
/// Removes a feed and blocks it, so no snapshot brings it back.
pub async fn remove(ctx: &Ctx, id: &str) -> Result<(), DirError> {
call(ctx, reqwest::Method::DELETE, &format!("/v1/feeds/{}", seg(id)), None).await
call(ctx, reqwest::Method::DELETE, &format!("/v1/feeds/{}", seg(id)), None, None).await
}
pub async fn refresh(ctx: &Ctx, id: &str) -> Result<serde::de::IgnoredAny, DirError> {
call(ctx, reqwest::Method::POST, &format!("/v1/feeds/{}/refresh", seg(id)), None).await
call(ctx, reqwest::Method::POST, &format!("/v1/feeds/{}/refresh", seg(id)), None, None).await
}
pub async fn blocked(ctx: &Ctx) -> Result<Vec<ipx_directory::Blocked>, DirError> {
call(ctx, reqwest::Method::GET, "/v1/blocked", None).await
call(
ctx,
reqwest::Method::GET,
"/v1/blocked",
None,
Some(|b| {
Ok(pb::BlockedList::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Into::into).collect())
}),
)
.await
}
pub async fn unblock(ctx: &Ctx, id: &str) -> Result<(), DirError> {
call(ctx, reqwest::Method::DELETE, &format!("/v1/blocked/{}", seg(id)), None).await
call(ctx, reqwest::Method::DELETE, &format!("/v1/blocked/{}", seg(id)), None, None).await
}
pub async fn instances(ctx: &Ctx) -> Result<Vec<ipx_directory::Instance>, DirError> {
call(ctx, reqwest::Method::GET, "/v1/instances", None).await
call(
ctx,
reqwest::Method::GET,
"/v1/instances",
None,
Some(|b| Ok(pb::Instances::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Into::into).collect())),
)
.await
}
/// Drops one server's snapshot, and its counts with it. It comes back with that server's next
/// one: to keep a server out, revoke its token.
pub async fn drop_instance(ctx: &Ctx, name: &str) -> Result<(), DirError> {
call(ctx, reqwest::Method::DELETE, &format!("/v1/instances/{}", seg(name)), None).await
call(ctx, reqwest::Method::DELETE, &format!("/v1/instances/{}", seg(name)), None, None).await
}
/// Has the snapshot sent again now, changed or not.
@@ -234,7 +279,14 @@ async fn snapshot(ctx: &Ctx) -> Result<Vec<SnapshotEntry>, DirError> {
}
pub async fn share(ctx: &Ctx, entries: &[SnapshotEntry]) -> Result<SnapshotResult, DirError> {
let r: SnapshotResult = call(ctx, reqwest::Method::POST, "/v1/snapshot", Some(entries)).await?;
let r: SnapshotResult = call(
ctx,
reqwest::Method::POST,
"/v1/snapshot",
Some(entries),
Some(|b| pb::SnapshotResult::decode(b).map(Into::into).map_err(|e| e.to_string())),
)
.await?;
if r.refused_private > 0 {
// The directory caught what this side should have: worth knowing which check differs.
tracing::warn!(refused = r.refused_private, "the directory refused feeds as private that ipx sent");

View File

@@ -86,6 +86,10 @@ pub mod entries {
pub duration: Option<i64>,
pub episode: Option<i64>,
pub season: Option<i64>,
/// The title and the text without markup, lowercased and cut short, which search reads
/// (#459); none until search.rs makes it.
#[sea_orm(column_type = "Text", nullable)]
pub search_text: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
@@ -266,6 +270,53 @@ pub mod entry_state {
owned_by_user!();
}
/// Up Next (#473): the episodes someone has lined up to play, in order. Per person, and on the
/// server so the phone and the browser play through the same one.
pub mod queue {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "queue")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: i64,
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub feed_id: String,
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub guid: String,
pub pos: i64,
}
owned_by_user!();
}
/// Smart playlists (#476): episodes of the podcasts chosen, kept up to date by themselves. The
/// priority podcasts' episodes come first.
pub mod playlists {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "playlists")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub user_id: i64,
#[sea_orm(column_type = "Text")]
pub name: String,
/// JSON array of feed ids.
#[sea_orm(column_type = "Text")]
pub feeds: String,
/// JSON array of feed ids, of those in `feeds`.
#[sea_orm(column_type = "Text")]
pub priority: String,
pub only_unplayed: bool,
pub oldest_first: bool,
pub created: i64,
}
owned_by_user!();
}
/// Words someone never wants to see: an item whose title or text has one is hidden from them and
/// not downloaded on their account (issue #47). `feed_id` is empty for the list that applies to
/// every feed they read.

View File

@@ -83,6 +83,9 @@ pub enum Event {
Reaped {
path: String,
bytes: u64,
/// Only what would go: `reap --dry-run` said "deleted" of files it kept (#461).
#[serde(default)]
dry_run: bool,
},
/// Terminal: a client that asked for work stops reading here.
ScanDone {
@@ -97,6 +100,8 @@ pub enum Event {
ReapDone {
files: usize,
bytes: u64,
#[serde(default)]
dry_run: bool,
},
Status {
feeds: usize,
@@ -165,11 +170,11 @@ impl Event {
},
Event::DownloadDone { path, .. } => format!(" saved {path}"),
Event::DownloadError { url, msg, .. } => format!(" failed {url}: {msg}"),
Event::Reaped { path, bytes } => {
format!("deleted {path} ({:.1} MB)", *bytes as f64 / 1_048_576.0)
Event::Reaped { path, bytes, dry_run } => {
format!("{} {path} ({:.1} MB)", deleted(*dry_run), *bytes as f64 / 1_048_576.0)
}
Event::ReapDone { files, bytes } => {
format!("deleted {files} old file(s), {:.1} MB", *bytes as f64 / 1_048_576.0)
Event::ReapDone { files, bytes, dry_run } => {
format!("{} {files} old file(s), {:.1} MB", deleted(*dry_run), *bytes as f64 / 1_048_576.0)
}
Event::Status { feeds, pending, downloaded } => {
format!("{feeds} feeds, {pending} queued to download, {downloaded} downloaded")
@@ -288,6 +293,10 @@ impl Event {
}
}
const fn deleted(dry_run: bool) -> &'static str {
if dry_run { "would delete" } else { "deleted" }
}
/// An event, logged once (#91): its words as the message, and `ev`, `feed`, `new` and the rest as
/// fields, so Loki reads them without parsing the message. A failure also gets `error.type` and,
/// from an HTTP error, `http.response.status_code`, so failures group by kind without a regex.
@@ -516,7 +525,9 @@ mod tests {
assert!(Event::ScanDone { feeds: 3, only: None, forced: false }.is_for(&me, &mine));
assert!(Event::SignalHits { user: 1, hits: 2 }.is_for(&me, &mine));
assert!(!Event::SignalHits { user: 3, hits: 2 }.is_for(&me, &mine));
assert!(!Event::Reaped { path: "/downloads/Theirs/ep.mp3".into(), bytes: 1 }.is_for(&me, &mine));
assert!(
!Event::Reaped { path: "/downloads/Theirs/ep.mp3".into(), bytes: 1, dry_run: false }.is_for(&me, &mine)
);
}
#[test]
@@ -627,7 +638,7 @@ mod tests {
#[test]
fn only_completion_events_end_a_client_session() {
assert!(Event::ScanDone { feeds: 1, only: None, forced: false }.is_terminal());
assert!(Event::ReapDone { files: 0, bytes: 0 }.is_terminal());
assert!(Event::ReapDone { files: 0, bytes: 0, dry_run: false }.is_terminal());
assert!(!Event::FeedDone { feed: "a".into(), new: 0, downloaded: 0, failed: 0, torrents: 0 }.is_terminal());
}

View File

@@ -27,6 +27,7 @@ mod play;
mod push;
mod retention;
mod scan;
mod search;
mod signals;
#[cfg(test)]
mod test_util;

View File

@@ -182,7 +182,7 @@ pub(crate) async fn sync_group(ctx: &Arc<Ctx>, parent_id: &str, listed: &[(Strin
.await?;
// Anything in this group the OPML no longer lists.
let mut removed = 0;
let mut removed = vec![];
let mut kept = 0;
let parent = ctx.cfg().feeds.get(parent_id).cloned();
async {
@@ -203,7 +203,7 @@ pub(crate) async fn sync_group(ctx: &Arc<Ctx>, parent_id: &str, listed: &[(Strin
tracing::info!(feed = %m.id, "dropped from the OPML but has downloads; keeping it");
} else {
ctx.db.drop_managed(&m.id).await?;
removed += 1;
removed.push(m.id.clone());
tracing::info!(feed = %m.id, "dropped from the OPML with nothing downloaded; removed");
}
}
@@ -291,4 +291,21 @@ mod tests {
assert!(ctx.db.subscription(me, "b").await.unwrap().is_some());
assert!(ctx.db.subscription(you, "b").await.unwrap().is_none());
}
#[tokio::test]
async fn a_feed_the_list_drops_takes_its_subscriptions_with_it() {
let mut cfg = config::Config::default();
cfg.feeds.insert("opml".into(), feed());
let ctx = Arc::new(test_ctx(cfg).await);
let me = ctx.db.create_user("me", None, false).await.unwrap();
ctx.db.upsert_managed("a", "http://x/a.xml", "a", "opml").await.unwrap();
ctx.db.subscribe(me, "opml").await.unwrap();
ctx.db.subscribe(me, "a").await.unwrap();
// Left subscribed, All Subscriptions listed a's items with no feed to name them (#478).
let Outcome::Opml { removed, .. } = sync_group(&ctx, "opml", &[]).await.unwrap() else { panic!("a list") };
assert_eq!(removed, ["a"], "the scan is told, so it does not read a again");
assert!(ctx.db.subscription(me, "a").await.unwrap().is_none());
assert!(ctx.db.subscription(me, "opml").await.unwrap().is_some());
}
}

View File

@@ -4,6 +4,7 @@
//! file address, which carries someone's access, never leaves this server.
use crate::ctx::Ctx;
use ipx_wire::Message as _;
use std::collections::HashMap;
use std::time::Duration;
@@ -76,7 +77,25 @@ pub async fn share(
.post(format!("{base}/v1/shares"))
.bearer_auth(token)
.timeout(Duration::from_secs(15))
.json(&episode);
// Protobuf both ways (#465).
.header(reqwest::header::CONTENT_TYPE, ipx_wire::PROTOBUF)
.header(reqwest::header::ACCEPT, ipx_wire::PROTOBUF)
.body(
ipx_wire::pb::play::Episode {
feed_url: episode.feed_url,
guid: episode.guid,
feed_title: episode.feed_title,
feed_image: episode.feed_image,
title: episode.title,
description: episode.description,
link: episode.link,
published: episode.published,
duration: episode.duration,
audio_url: episode.audio_url,
mime: episode.mime,
}
.encode_to_vec(),
);
// Its spans join this request's trace.
if let Some(tp) = ipx_directory::otel::traceparent() {
req = req.header("traceparent", tp);
@@ -87,7 +106,10 @@ pub async fn share(
let msg = resp.json::<serde_json::Value>().await.ok().and_then(|v| v["error"].as_str().map(str::to_owned));
return Err(NoLink::Failed(format!("ipx-play answered {status}: {}", msg.unwrap_or_default())));
}
resp.json().await.map_err(|e| NoLink::Failed(format!("ipx-play's answer did not read: {e:#}")))
let body = resp.bytes().await.map_err(|e| NoLink::Failed(format!("reading ipx-play's answer: {e:#}")))?;
let shared = ipx_wire::pb::play::Shared::decode(body)
.map_err(|e| NoLink::Failed(format!("ipx-play's answer did not read: {e}")))?;
Ok(ipx_play::Shared { id: shared.id, url: shared.url })
}
#[cfg(test)]

View File

@@ -142,10 +142,10 @@ pub(crate) async fn reap(ctx: &Ctx, dry_run: bool, standalone: bool) -> Result<(
}
let removed = r.aged_out.iter().chain(r.over_quota.iter());
for c in removed {
ctx.out.emit(Event::Reaped { path: c.path.clone(), bytes: c.bytes.max(0) as u64 });
ctx.out.emit(Event::Reaped { path: c.path.clone(), bytes: c.bytes.max(0) as u64, dry_run });
}
if standalone {
ctx.out.emit(Event::ReapDone { files: r.aged_out.len() + r.over_quota.len(), bytes: r.bytes_freed });
ctx.out.emit(Event::ReapDone { files: r.aged_out.len() + r.over_quota.len(), bytes: r.bytes_freed, dry_run });
}
Ok(())
}

View File

@@ -5,6 +5,7 @@ use crate::ctx::Ctx;
use crate::ipc::Event;
use crate::{catalogue, cli, config, db, download, feed, lists, metrics, signals, torrent};
use anyhow::Result;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
@@ -23,6 +24,8 @@ pub(crate) async fn fetch(ctx: &Arc<Ctx>, only: Option<&str>, force: bool, scope
let subscribed = ctx.db.subscriber_counts().await?;
let mut scanned = 0;
let mut fresh: Vec<String> = vec![];
// Feeds a list read earlier in this run dropped: still in `due`, scanned they came back (#478).
let mut dropped: HashSet<String> = HashSet::new();
let in_scope =
|s: &Sub| scope.is_empty() || scope.contains(&s.id) || s.cfg.group.as_ref().is_some_and(|g| scope.contains(g));
let mut states = ctx.db.http_states().await?;
@@ -95,6 +98,9 @@ pub(crate) async fn fetch(ctx: &Arc<Ctx>, only: Option<&str>, force: bool, scope
let (id, feed_cfg) = (&sub.id, &sub.cfg);
// A task that panicked has no body; scan_one then fetches it itself.
let fetched = futures_util::StreamExt::next(&mut bodies).await.and_then(|j| j.ok()).flatten();
if dropped.contains(id) {
continue;
}
scanned += 1;
ctx.out.emit(Event::FeedStart { feed: id.clone() });
match scan_one(ctx, id, feed_cfg, state, force, fetched).await {
@@ -113,10 +119,12 @@ pub(crate) async fn fetch(ctx: &Arc<Ctx>, only: Option<&str>, force: bool, scope
ctx.out.emit(Event::FeedSkip {
feed: id.clone(),
reason: format!(
"{total} feed(s) listed, {} added, {removed} unsubscribed, {kept} kept without a listing",
added.len()
"{total} feed(s) listed, {} added, {} unsubscribed, {kept} kept without a listing",
added.len(),
removed.len()
),
});
dropped.extend(removed);
// Read them in the same pass, as the original did, rather than making
// the user wait a whole interval for a newly listed show.
fresh.extend(added);
@@ -247,7 +255,7 @@ pub(crate) enum Outcome {
/// The URL is a list of feeds rather than a feed: an OPML, or a Patreon creator's shows.
Opml {
added: Vec<String>,
removed: usize,
removed: Vec<String>,
kept: usize,
total: usize,
},

88
crates/ipx/src/search.rs Normal file
View File

@@ -0,0 +1,88 @@
//! What a search reads (#459): each item's title and text, the markup taken out, lowercased and cut
//! short, kept in `entries.search_text` beside the HTML. Matching the HTML itself took 5 s on All
//! Subscriptions, most of it reading 4 GB of descriptions; the plain text is a fraction of that,
//! and Postgres indexes it with pg_trgm, so a part of a word still finds the word, as before.
use std::sync::Arc;
use std::time::Duration;
use tracing::Instrument;
use crate::ctx::Ctx;
/// Enough of a post for its subject to be in it; a word only past this in a very long post is not
/// found. It keeps the index a size the shared Postgres carries.
pub const MAX_CHARS: usize = 4000;
/// Items made at a time, and how long between looks for more once none are left.
const BATCH: i64 = 500;
const EVERY: Duration = Duration::from_secs(5 * 60);
/// The title, then the text with its markup taken out (an image's alt and title kept, as Signals
/// read them), lowercased, its spaces made single, and at most `MAX_CHARS` long.
pub fn search_text(title: Option<&str>, description: Option<&str>) -> String {
let text = crate::signals::text_of(description.unwrap_or(""));
let all = format!("{} {}", title.unwrap_or(""), text).to_lowercase();
all.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(MAX_CHARS).collect()
}
/// Makes every item's search text that is missing, then the index, then looks again now and then:
/// a scan that changes an item's title or text leaves its search text to be made again here, and
/// a search reads that item the old way until it is.
pub async fn run(ctx: Arc<Ctx>, mut stop: tokio::sync::watch::Receiver<bool>) {
let mut indexed = false;
loop {
let pass = async {
let made = fill(&ctx).await?;
if !indexed {
indexed = ctx.db.search_index().instrument(crate::db::step("search_index")).await?;
}
anyhow::Ok(made)
};
tokio::select! {
_ = stop.changed() => return,
done = pass.instrument(tracing::info_span!("search_text")) => match done {
Ok(n) if n > 0 => tracing::info!(items = n, "search: made items' search text"),
Ok(_) => {}
Err(e) => tracing::warn!(error = %format!("{e:#}"), "search: items' search text could not be made"),
},
}
tokio::select! {
_ = stop.changed() => return,
_ = tokio::time::sleep(EVERY) => {}
}
}
}
/// Every item without search text, given one, a batch at a time: how many.
async fn fill(ctx: &Ctx) -> anyhow::Result<usize> {
let mut made = 0;
loop {
let batch = ctx.db.unsearched(BATCH).await?;
if batch.is_empty() {
return Ok(made);
}
for (feed, guid, title, description) in &batch {
ctx.db.set_search_text(feed, guid, &search_text(title.as_deref(), description.as_deref())).await?;
}
made += batch.len();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_text_is_the_words_not_the_markup() {
let t = search_text(
Some("Apple's NEW Thing"),
Some(r#"<p>Read <a href="https://x.example/app">more</a></p><img alt="A Chart" src="c.png">"#),
);
assert_eq!(t, "apple's new thing read more a chart");
assert!(!t.contains("href") && !t.contains("x.example"), "an address in a tag is not a word of the post");
assert_eq!(search_text(None, None), "");
let long = "word ".repeat(2000);
assert_eq!(search_text(Some("Title"), Some(&long)).chars().count(), MAX_CHARS);
assert!(search_text(Some("Title"), Some(&long)).starts_with("title word"), "the title is always in it");
}
}

View File

@@ -497,7 +497,7 @@ fn chosen(answer: &serde_json::Value, candidates: &[(String, String)]) -> Option
/// Show notes are HTML: Jev is given their words, and an image's alt and title text, which is all
/// the words some posts have. xkcd's is a comic and its hover text; dropping the tag whole sent Jev
/// "Ground Effect" alone, an F1 aerodynamics term, and the comic went into Formula 1 (#267).
fn text_of(html: &str) -> String {
pub(crate) fn text_of(html: &str) -> String {
let mut out = String::with_capacity(html.len());
let mut tag: Option<String> = None;
for c in html.chars() {

View File

@@ -48,6 +48,56 @@ pub struct WebState {
pub wrong: Wrong,
}
/// Each route's protobuf messages (#465), beside its JSON: what its body is and what it answers.
const WIRE: ipx_wire::Routes = &[
("POST", "/api/login", "ipx.Credentials", "ipx.SignedIn"),
("GET", "/api/me", "", "ipx.Me"),
("PATCH", "/api/me", "ipx.MePatch", ""),
("GET", "/api/tokens", "", "ipx.ApiTokens"),
("POST", "/api/tokens", "ipx.NewToken", "ipx.MadeToken"),
("POST", "/api/push/devices", "ipx.PushDevice", ""),
("GET", "/api/feeds", "", "ipx.FeedRows"),
("POST", "/api/feeds", "ipx.NewFeed", "ipx.AddedFeed"),
("PATCH", "/api/feeds/{id}", "ipx.FeedPatch", ""),
("GET", "/api/feeds/{id}/entries", "", "ipx.EntryPage"),
("GET", "/api/feeds/{id}/seasons", "", "ipx.SeasonRows"),
("GET", "/api/entries", "", "ipx.EntryPage"),
("GET", "/api/queue", "", "ipx.EntryPage"),
("PUT", "/api/queue", "ipx.QueueItems", "ipx.EntryPage"),
("GET", "/api/playlists", "", "ipx.PlaylistRows"),
("POST", "/api/playlists", "ipx.PlaylistSpec", "ipx.PlaylistId"),
("PATCH", "/api/playlists/{id}", "ipx.PlaylistSpec", ""),
("GET", "/api/playlists/{id}/entries", "", "ipx.EntryPage"),
("GET", "/api/signals", "", "ipx.SignalRows"),
("POST", "/api/signals", "ipx.SignalBody", "ipx.SignalId"),
("POST", "/api/signals/icon", "ipx.IconAsk", "ipx.Icon"),
("PATCH", "/api/signals/{id}", "ipx.SignalBody", ""),
("GET", "/api/signals/{id}/entries", "", "ipx.EntryPage"),
("GET", "/api/entries/{feed_id}/{guid}", "", "ipx.EntryRow"),
("POST", "/api/entries/{feed_id}/{guid}/flags", "ipx.Flags", "ipx.FeedRow"),
("POST", "/api/entries/{feed_id}/{guid}/position", "ipx.Position", ""),
("POST", "/api/entries/{feed_id}/{guid}/share", "ipx.ShareBody", "ipx.ShareLink"),
("POST", "/api/feeds/{id}/read-all", "", "ipx.Marked"),
("POST", "/api/read-all", "", "ipx.Marked"),
("POST", "/api/feeds/{id}/download-latest", "ipx.HowMany", "ipx.Queued"),
("POST", "/api/fetch", "ipx.FetchBody", ""),
("POST", "/api/opml", "ipx.OpmlBody", "ipx.OpmlImported"),
("GET", "/api/settings", "", "ipx.Settings"),
("PATCH", "/api/settings", "ipx.SettingsPatch", ""),
("GET", "/api/directory-status", "", "ipx.DirStatus"),
("GET", "/api/status", "", "ipx.Status"),
("GET", "/api/popular", "", "ipx.PopularRows"),
("GET", "/api/directory", "", "ipx.PopularRows"),
("GET", "/api/directory/{id}", "", "ipx.Listed"),
("GET", "/api/directory-admin", "", "ipx.DirAdmin"),
("POST", "/api/popular/{id}", "", "ipx.FeedId"),
("GET", "/api/users", "", "ipx.Accounts"),
("POST", "/api/users", "ipx.NewUser", ""),
("PATCH", "/api/users/{id}", "ipx.UserPatch", ""),
("GET", "/api/logs", "", "ipx.LogPage"),
("POST", "/api/client", "ipx.ClientEvent", ""),
];
pub fn router(state: WebState) -> Router {
Router::new()
.route("/api/me", get(me).patch(patch_me))
@@ -59,7 +109,12 @@ pub fn router(state: WebState) -> Router {
.route("/api/feeds", get(feeds).post(add_feed))
.route("/api/feeds/{id}", patch(patch_feed).delete(remove_feed))
.route("/api/feeds/{id}/entries", get(entries))
.route("/api/feeds/{id}/seasons", get(seasons))
.route("/api/entries", get(all_entries))
.route("/api/queue", get(queue).put(set_queue))
.route("/api/playlists", get(list_playlists).post(add_playlist))
.route("/api/playlists/{id}", patch(patch_playlist).delete(remove_playlist))
.route("/api/playlists/{id}/entries", get(playlist_entries))
.route("/api/signals", get(list_signals).post(add_signal))
.route("/api/signals/icon", post(pick_signal_icon))
.route("/api/signals/{id}", patch(patch_signal).delete(remove_signal))
@@ -102,6 +157,7 @@ pub fn router(state: WebState) -> Router {
// Signing in cannot require being signed in, so these sit outside the auth layer.
.route("/api/login", post(login))
.route("/api/login-check", get(login_check))
.route_layer(middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
.route_layer(middleware::from_fn(name_span))
.layer(middleware::from_fn(cross_site_refused))
.layer(middleware::from_fn(access_log))
@@ -957,6 +1013,8 @@ struct FeedRow {
private: bool,
/// Private whatever it is marked, for a login or an address with a key in it.
private_by_address: bool,
/// Has an audio or video file: on the Podcasts shelf (#474).
podcast: bool,
}
#[derive(Serialize)]
@@ -1005,7 +1063,8 @@ async fn feed_rows(state: &WebState, user: &crate::db::User, only: Option<&str>)
let up = feed.group.as_deref().and_then(|g| mine.get(g));
let Some(mine) = mine.get(id) else { continue };
// A feed not scanned yet has no row: blank, as feed_summary gave it.
let crate::db::FeedListing { summary: s, ttl_mins, blocked, unread } = listed.remove(id).unwrap_or_default();
let crate::db::FeedListing { summary: s, ttl_mins, blocked, unread, podcast } =
listed.remove(id).unwrap_or_default();
out.push(FeedRow {
private: feed.private,
private_by_address: crate::directory::looks_private(&crate::config::Feed {
@@ -1068,6 +1127,7 @@ async fn feed_rows(state: &WebState, user: &crate::db::User, only: Option<&str>)
kept: kept.contains(id),
hide_from_all: hidden.contains(id),
hide_from_signals: quiet.contains(id),
podcast,
});
}
Ok(out)
@@ -1777,12 +1837,36 @@ mod tests {
assert_eq!(image_kind("application/octet-stream", &jpeg).as_deref(), Some("image/jpeg"));
assert_eq!(image_kind("", b"\x89PNG\r\n").as_deref(), Some("image/png"));
assert_eq!(image_kind("", b"RIFF\0\0\0\0WEBPVP8").as_deref(), Some("image/webp"));
assert_eq!(image_kind("application/octet-stream", b"\xff\x0a\xfa").as_deref(), Some("image/jxl"));
assert_eq!(image_kind("", b"\0\0\0\x0cJXL \r\n\x87\n\0").as_deref(), Some("image/jxl"));
assert_eq!(image_kind("image/avif", b"").as_deref(), Some("image/avif"));
// A page, or an untyped SVG, stays refused.
assert_eq!(image_kind("text/html", &jpeg), None);
assert_eq!(image_kind("", b"<svg onload=alert(1)>"), None);
}
#[tokio::test]
async fn an_artwork_failure_lasts_when_the_publisher_or_ipx_refuses_it() {
// Answers each request with the status its path names.
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let at = l.local_addr().unwrap();
tokio::spawn(async move {
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
while let Ok((mut s, _)) = l.accept().await {
let mut buf = [0; 1024];
let n = s.read(&mut buf).await.unwrap_or(0);
let code = String::from_utf8_lossy(&buf[..n]).split('/').nth(1).unwrap_or("500")[..3].to_owned();
let _ = s.write_all(format!("HTTP/1.1 {code} X\r\ncontent-length: 0\r\n\r\n").as_bytes()).await;
}
});
let c = reqwest::Client::new();
for (code, want) in [(404, true), (410, true), (408, false), (429, false), (503, false)] {
let e = c.get(format!("http://{at}/{code}")).send().await.unwrap().error_for_status().unwrap_err();
assert_eq!(lasting(&e.into()), want, "{code}");
}
assert!(lasting(&anyhow::anyhow!("larger than 20971520 bytes")));
}
#[test]
fn a_signal_icon_is_a_style_and_a_plain_name() {
assert_eq!(signal_icon(Some("solid/robot".into())).ok().flatten().as_deref(), Some("solid/robot"));
@@ -1960,6 +2044,9 @@ struct Page {
sort: Option<String>,
#[serde(default)]
dir: Option<String>,
/// One season of a podcast's (#482): its number, or `none` for the episodes naming none.
#[serde(default)]
season: Option<String>,
}
fn fifty() -> i64 {
@@ -1987,6 +2074,30 @@ async fn entries(
entry_page(&state, user.id, Some(&ids[..]), None, &page).await
}
/// A season as the page sends it (#482): its number, `none` for the episodes naming none, or
/// nothing for every season.
fn season_of(s: Option<&str>) -> Result<db::Season, ApiError> {
Ok(match s.map(str::trim) {
None | Some("") => db::Season::Any,
Some("none") => db::Season::Unnumbered,
Some(n) => db::Season::Of(n.parse().map_err(|_| ApiError::bad_request(format!("no season {n:?}")))?),
})
}
/// A podcast's seasons, for its page to offer one at a time (#482). An OPML's are its shows'
/// together, as its items are.
async fn seasons(
State(state): State<WebState>,
Path(id): Path<String>,
user: crate::db::User,
) -> Result<Json<Vec<crate::db::SeasonCount>>, ApiError> {
subscribed(&state, &user, &id).await?;
let mut ids = state.ctx.db.group_members(user.id, &id).await?;
ids.push(id);
let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
Ok(Json(state.ctx.db.seasons(user.id, &ids).await?))
}
/// A feed's items and files are for the people who subscribe to it (#129). Anyone signed in
/// could read any feed's by its id, a paid one's included, with its enclosure addresses, which
/// can carry the subscriber's key, and fetch, queue or delete its files by theirs. A feed in
@@ -2022,6 +2133,7 @@ async fn entry_page(
let order =
crate::db::order_sql(page.sort.as_deref().unwrap_or("published"), page.dir.as_deref().unwrap_or("desc"));
let limit = page.limit.clamp(1, 200);
let season = season_of(page.season.as_deref())?;
// Which list, so a slow one's trace says what was asked of it (#287). The search's words stay
// out: they are the reader's own.
let in_list = tracing::info_span!(
@@ -2033,19 +2145,32 @@ async fn entry_page(
offset = page.offset,
limit,
search = search.is_some(),
season = ?season,
);
// A season is of a podcast's own page; All Subscriptions and a Signal have none to pick.
let in_season = feeds.filter(|_| season != db::Season::Any);
let list = async {
match signal {
Some(id) => {
match (signal, in_season) {
(Some(id), _) => {
db.signal_entries(user_id, id, filter, search, page.offset, limit, &order).instrument(in_list).await
}
None => db.entries_of(user_id, feeds, filter, search, page.offset, limit, &order).instrument(in_list).await,
(None, Some(fs)) => {
db.season_entries(user_id, fs, season, filter, search, page.offset, limit, &order)
.instrument(in_list)
.await
}
(None, None) => {
db.entries_of(user_id, feeds, filter, search, page.offset, limit, &order).instrument(in_list).await
}
}
};
let count = async {
match signal {
Some(id) => db.signal_count(user_id, id, filter, search).instrument(db::step("count_in")).await,
None => db.count_of(user_id, feeds, filter, search).instrument(db::step("count_in")).await,
match (signal, in_season) {
(Some(id), _) => db.signal_count(user_id, id, filter, search).instrument(db::step("count_in")).await,
(None, Some(fs)) => {
db.season_count(user_id, fs, season, filter, search).instrument(db::step("count_in")).await
}
(None, None) => db.count_of(user_id, feeds, filter, search).instrument(db::step("count_in")).await,
}
};
// The count beside the list, not after it: each waited on the other, about 40 and 24 ms on the
@@ -2061,6 +2186,132 @@ async fn entry_page(
Ok(Json(EntryPage { total, entries: rows }))
}
/// One of Up Next's episodes, as the page names it.
#[derive(Deserialize)]
struct QueueItem {
feed_id: String,
guid: String,
}
/// Up Next (#473): the episodes lined up to play, in order, as a page of entries.
async fn queue(State(state): State<WebState>, user: crate::db::User) -> Result<Json<EntryPage>, ApiError> {
queue_page(&state, user.id).await
}
/// Puts Up Next in the order sent, and answers with it as it now is: what was not yours to queue
/// is left out rather than refused, so a list one device held while another unsubscribed still
/// saves.
async fn set_queue(
State(state): State<WebState>,
user: crate::db::User,
Json(items): Json<Vec<QueueItem>>,
) -> Result<Json<EntryPage>, ApiError> {
if items.len() > 500 {
return Err(ApiError::bad_request("Up Next holds at most 500 episodes"));
}
let items: Vec<(String, String)> = items.into_iter().map(|i| (i.feed_id, i.guid)).collect();
state.ctx.db.set_queue(user.id, &items).await?;
queue_page(&state, user.id).await
}
async fn queue_page(state: &WebState, user_id: i64) -> Result<Json<EntryPage>, ApiError> {
let mut rows = state.ctx.db.queue_of(user_id).await?;
let mut sanitizer = feed_sanitizer();
for row in &mut rows {
clean_row(&mut sanitizer, row);
}
crate::deadair::for_reader(&state.ctx, user_id, &mut rows).await?;
Ok(Json(EntryPage { total: rows.len() as i64, entries: rows }))
}
/// A playlist as sent, made fit to keep: a name, the podcasts this person subscribes to, the
/// priority ones among them.
async fn playlist_spec(
state: &WebState,
user: &crate::db::User,
mut spec: crate::db::PlaylistSpec,
) -> Result<crate::db::PlaylistSpec, ApiError> {
spec.name = spec.name.trim().to_owned();
if spec.name.is_empty() || spec.name.chars().count() > 100 {
return Err(ApiError::bad_request("a playlist needs a name of up to 100 characters"));
}
let mine: std::collections::HashSet<String> =
state.ctx.db.subscriptions_for(user.id).await?.into_iter().map(|s| s.feed_id).collect();
let mut seen = std::collections::HashSet::new();
spec.feeds.retain(|f| mine.contains(f) && seen.insert(f.clone()));
if spec.feeds.is_empty() {
return Err(ApiError::bad_request("a playlist needs at least one podcast you subscribe to"));
}
spec.priority.retain(|f| spec.feeds.contains(f));
spec.priority.dedup();
Ok(spec)
}
/// Smart playlists (#476).
async fn list_playlists(
State(state): State<WebState>,
user: crate::db::User,
) -> Result<Json<Vec<crate::db::PlaylistRow>>, ApiError> {
Ok(Json(state.ctx.db.playlists(user.id).await?))
}
async fn add_playlist(
State(state): State<WebState>,
user: crate::db::User,
Json(spec): Json<crate::db::PlaylistSpec>,
) -> Result<Json<serde_json::Value>, ApiError> {
let spec = playlist_spec(&state, &user, spec).await?;
let id = state.ctx.db.save_playlist(user.id, None, &spec).await?;
Ok(Json(serde_json::json!({ "id": id })))
}
async fn patch_playlist(
State(state): State<WebState>,
Path(id): Path<i64>,
user: crate::db::User,
Json(spec): Json<crate::db::PlaylistSpec>,
) -> Result<StatusCode, ApiError> {
let spec = playlist_spec(&state, &user, spec).await?;
match state.ctx.db.save_playlist(user.id, Some(id), &spec).await? {
Some(_) => Ok(StatusCode::NO_CONTENT),
None => Err(ApiError::not_found("no such playlist")),
}
}
async fn remove_playlist(
State(state): State<WebState>,
Path(id): Path<i64>,
user: crate::db::User,
) -> Result<StatusCode, ApiError> {
if !state.ctx.db.remove_playlist(user.id, id).await? {
return Err(ApiError::not_found("no such playlist"));
}
Ok(StatusCode::NO_CONTENT)
}
/// A playlist's episodes, in its own order: the page's sort does not apply.
async fn playlist_entries(
State(state): State<WebState>,
Path(id): Path<i64>,
user: crate::db::User,
Query(page): Query<Page>,
) -> Result<Json<EntryPage>, ApiError> {
let Some(p) = state.ctx.db.playlist(user.id, id).await? else {
return Err(ApiError::not_found("no such playlist"));
};
let feeds: Vec<&str> = p.spec.feeds.iter().map(String::as_str).collect();
let filter = if p.spec.only_unplayed { crate::db::Filter::Unread } else { crate::db::Filter::All };
let order = crate::db::playlist_order(&p.spec);
let limit = page.limit.clamp(1, 200);
let mut rows = state.ctx.db.entries_of(user.id, Some(&feeds), filter, None, page.offset, limit, &order).await?;
let mut sanitizer = feed_sanitizer();
for row in &mut rows {
clean_row(&mut sanitizer, row);
}
crate::deadair::for_reader(&state.ctx, user.id, &mut rows).await?;
Ok(Json(EntryPage { total: p.items, entries: rows }))
}
/// One entry, in the clock of the file this person will play (`deadair::for_reader`).
async fn one_entry(
State(state): State<WebState>,
@@ -2518,7 +2769,11 @@ async fn delete_file(
state.ctx.db.mark_reaped(id).await?;
state
.events
.send(Event::Reaped { path: enc.path.unwrap_or_default(), bytes: enc.length.unwrap_or(0).max(0) as u64 })
.send(Event::Reaped {
path: enc.path.unwrap_or_default(),
bytes: enc.length.unwrap_or(0).max(0) as u64,
dry_run: false,
})
.ok();
Ok(StatusCode::NO_CONTENT)
}
@@ -2733,7 +2988,7 @@ async fn serve_media(state: WebState, id: i64, user: crate::db::User, req: Reque
}
r.into_response()
}
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
Err(e) => match e {},
}
}
@@ -2800,6 +3055,8 @@ async fn art(State(state): State<WebState>, Query(q): Query<ArtQuery>) -> Respon
let mut r = state.ctx.client.get(&q.u).timeout(crate::feed::FEED_TIMEOUT).send().await?.error_for_status()?;
let said = r.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_owned();
anyhow::ensure!(said.starts_with("image/") || untyped(&said), "not an image: {said}");
// Said up front, refused up front: read chunk by chunk, each was 20 MB fetched to be thrown away (#448).
anyhow::ensure!(r.content_length().is_none_or(|n| n <= MAX as u64), "larger than {MAX} bytes");
let mut body = Vec::new();
while let Some(c) = r.chunk().await? {
body.extend_from_slice(&c);
@@ -2826,12 +3083,25 @@ async fn art(State(state): State<WebState>, Query(q): Query<ArtQuery>) -> Respon
let why = format!("{e:#}");
// The access line says only that it failed, not which image or why (#169).
tracing::warn!(url = %crate::feed::redact(&q.u), error = %crate::feed::redact_text(&why), "could not fetch artwork");
crate::art::fail(&q.u, &why);
crate::art::fail(&q.u, &why, lasting(&e));
(StatusCode::BAD_GATEWAY, why).into_response()
}
}
}
/// Whether an artwork fetch failed for a reason that will still hold tomorrow: refused by the
/// publisher (a 4xx but a timeout or too many requests), or what ipx refuses (too large, not an
/// image), which are its own errors and not reqwest's. A timeout, a 5xx or a dropped connection
/// may be gone in an hour.
fn lasting(e: &anyhow::Error) -> bool {
match e.downcast_ref::<reqwest::Error>() {
Some(re) => re.status().is_some_and(|s| {
s.is_client_error() && s != StatusCode::REQUEST_TIMEOUT && s != StatusCode::TOO_MANY_REQUESTS
}),
None => true,
}
}
/// The fetches of artwork under way, by address, each a lock the requests for it take in turn.
static ART_FETCHES: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
@@ -2880,6 +3150,8 @@ fn image_kind(said: &str, body: &[u8]) -> Option<String> {
[0x89, b'P', b'N', b'G', ..] => "image/png",
[b'G', b'I', b'F', b'8', ..] => "image/gif",
[b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => "image/webp",
// JPEG XL, bare or in its box, which shkspr.mobi sends as octet-stream (#448); Safari shows it.
[0xFF, 0x0A, ..] | [0, 0, 0, 0x0C, b'J', b'X', b'L', b' ', 0x0D, 0x0A, 0x87, 0x0A, ..] => "image/jxl",
_ => return None,
};
Some(kind.to_owned())
@@ -2967,6 +3239,9 @@ async fn read_all_mine(
struct HowMany {
#[serde(default = "five")]
count: i64,
/// One season, all of it, in place of the newest `count` (#482).
#[serde(default)]
season: Option<String>,
}
fn five() -> i64 {
@@ -2982,7 +3257,10 @@ async fn download_latest(
Json(body): Json<HowMany>,
) -> Result<Json<serde_json::Value>, ApiError> {
subscribed(&state, &user, &id).await?;
let ids = state.ctx.db.undownloaded(&id, body.count.clamp(1, 100)).await?;
let season = season_of(body.season.as_deref())?;
// A whole season, Oxide and Friends' longest 47 episodes; past 300 it is no season.
let most = if season == db::Season::Any { body.count.clamp(1, 100) } else { 300 };
let ids = state.ctx.db.undownloaded(&id, season, most).await?;
for enc in &ids {
state.ctx.db.requeue(*enc).await?;
state

View File

@@ -12,7 +12,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `POST /v1/shares` takes and answers protobuf (`application/x-protobuf`) as well as JSON, chosen by `Content-Type` and `Accept`. The messages are in `crates/wire/proto/play.proto`, and answers go through structs generated from them (#465, #470).
- A page for each shared episode, at `/e/<id>`: its show, title, date, length and notes, a player that plays the publisher's own file from the time it was shared at (`?t=754` or `?t=12:34`), buttons to subscribe in Apple Podcasts, Overcast, Pocket Casts or Castro, the feed's address, and a preview where the link is pasted (#447).
- `POST /v1/shares`, for an ipx server with a token from `ipx-play token <name>`: an episode in, its short link out, the same link however often and from whichever server it is shared. An address that looks like a private or paid feed's is refused (#447).
- Metrics for Prometheus on a port of its own, `metrics_bind`: requests by route and status and their time, episodes shared, memory (#458).
[unreleased]: https://git.sdf1.net/rays/ipx/commits/main/crates/play
### Security
- An episode's notes are cleaned with ammonia 4.2.5, which no longer lets SVG or MathML in a feed's HTML carry script past it (RUSTSEC-2026-0533) (#467).

View File

@@ -21,6 +21,7 @@ clap.workspace = true
# log lines as ipx and the directory.
ipx-directory.workspace = true
ipx-feed.workspace = true
ipx-wire.workspace = true
opentelemetry.workspace = true
percent-encoding.workspace = true
reqwest.workspace = true

View File

@@ -15,6 +15,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 (#458), apart from `bind`, which the tunnel
/// publishes: `0.0.0.0:9191`. Empty serves none.
#[serde(default)]
pub metrics_bind: String,
/// The address people open, which the links ipx is handed begin with.
#[serde(default = "default_public_url")]
pub public_url: String,

View File

@@ -9,10 +9,11 @@
//! its file is, nothing more.
pub mod config;
pub mod metrics;
mod page;
pub mod store;
use axum::extract::{Path, Query, Request, State};
use axum::extract::{MatchedPath, Path, Query, Request, State};
use axum::http::{StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
@@ -107,10 +108,14 @@ pub struct Play {
type St = Arc<Play>;
/// Each route's protobuf messages (#465), beside its JSON.
const WIRE: ipx_wire::Routes = &[("POST", "/v1/shares", "play.Episode", "play.Shared")];
pub fn router(play: Play) -> Router {
let st = Arc::new(play);
let api = Router::new()
.route("/v1/shares", post(share))
.route_layer(axum::middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
.layer(axum::middleware::from_fn_with_state(st.clone(), authenticate));
Router::new()
.route("/healthz", get(healthz))
@@ -160,6 +165,7 @@ async fn share(State(st): State<St>, Extension(who): Extension<Who>, Json(mut e)
}
match st.store.put(&who.0, &e).await {
Ok(id) => {
metrics::SHARES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tracing::info!(server = %who.0, id = %id, "an episode was shared");
Json(Shared { url: format!("{}/e/{id}", st.base), id }).into_response()
}
@@ -198,6 +204,9 @@ async fn healthz(State(st): State<St>) -> Response {
/// calls here; and a line, with the server's name and never its token.
async fn access_log(req: Request, next: Next) -> Response {
let (method, path) = (req.method().clone(), req.uri().path().to_owned());
// By route, not path: by path each shared episode would be a row of its own. A path no route
// has is "", which someone trying addresses cannot multiply.
let route = req.extensions().get::<MatchedPath>().map_or("", |r| r.as_str()).to_owned();
let start = Instant::now();
let span = if path == "/healthz" {
tracing::Span::none()
@@ -218,6 +227,14 @@ async fn access_log(req: Request, next: Next) -> Response {
let status = resp.status().as_u16();
span.record("http.response.status_code", status);
if path != "/healthz" {
metrics::REQUESTS.observe(
&format!(
"method=\"{}\",route=\"{}\",status=\"{status}\"",
ipx_directory::metrics::method(method.as_str()),
ipx_directory::metrics::label(&route)
),
start.elapsed().as_secs_f64(),
);
let _in = span.enter();
let who = resp.extensions().get::<Who>().map_or("", |w| w.0.as_str()).to_owned();
tracing::info!(
@@ -301,6 +318,18 @@ mod tests {
assert!(!html.contains("javascript:"), "a link that is not a web address is dropped");
assert_eq!(get(&app, "/e/nothere").await.0, StatusCode::NOT_FOUND);
get(&app, "/no/such/page").await;
let mut out = String::new();
metrics::REQUESTS.render(&mut out, "r", "");
for row in [
r#"r_count{method="GET",route="/e/{id}",status="200"}"#,
r#"r_count{method="POST",route="/v1/shares",status="200"}"#,
r#"r_count{method="GET",route="",status="404"}"#,
] {
assert!(out.contains(row), "requests are counted by route, not path: {row} in {out}");
}
assert!(!out.contains("nothere") && !out.contains("/no/such"), "{out}");
}
#[tokio::test]

View File

@@ -98,6 +98,13 @@ async fn serve(path: &Path) -> Result<()> {
.with_context(|| format!("{} is not set: ipx-play needs a database URL", cfg.database_url_env))?;
let store = Store::open(&url, true).await.context("opening the database")?;
let listener = TcpListener::bind(&cfg.bind).await.with_context(|| format!("listening on {}", cfg.bind))?;
if !cfg.metrics_bind.is_empty() {
let metrics = TcpListener::bind(&cfg.metrics_bind)
.await
.with_context(|| format!("listening for metrics on {}", cfg.metrics_bind))?;
tracing::info!(bind = %cfg.metrics_bind, "serving metrics for Prometheus at /metrics");
tokio::spawn(ipx_play::metrics::serve(metrics));
}
tracing::info!(version = env!("CARGO_PKG_VERSION"), bind = %cfg.bind, tokens = tokens.len(), "ipx-play started");
let app = ipx_play::router(Play { store, tokens, base: cfg.base().to_owned() });
axum::serve(listener, app)

View File

@@ -0,0 +1,99 @@
//! ipx-play's /metrics (#458), in Prometheus's text format: memory, open files, the requests it
//! answered and the episodes it was given to share. The histogram and /proc reading are the
//! directory's, so the two read alike on the dashboard.
use axum::Router;
use ipx_directory::metrics::{Histograms, SECONDS, process};
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering::Relaxed;
use std::time::Instant;
use tokio::net::TcpListener;
/// Requests answered, by method, route and status: a page opened is `route="/e/{id}"`.
pub static REQUESTS: Histograms = Histograms::new(SECONDS);
/// Episodes an ipx server sent to be shared, the same one again included.
pub static SHARES: AtomicU64 = AtomicU64::new(0);
/// Nothing from the database, so a scrape costs nothing and answers while it is down.
fn render(started: Instant) -> String {
let mut out = String::new();
let mut gauge = |name: &str, kind: &str, help: &str, labels: &str, v: f64| {
out.push_str(&format!("# HELP {name} {help}\n# TYPE {name} {kind}\n{name}{labels} {v}\n"));
};
let (rss, fds) = process();
if let Some(v) = rss {
gauge("play_process_resident_bytes", "gauge", "Memory the process holds.", "", v);
}
if let Some(v) = fds {
gauge("play_process_open_fds", "gauge", "Files and sockets the process has open.", "", v);
}
gauge("play_uptime_seconds", "gauge", "Seconds since ipx-play started.", "", started.elapsed().as_secs() as f64);
gauge(
"play_build_info",
"gauge",
"The version running, as a label.",
&format!("{{version=\"{}\"}}", env!("CARGO_PKG_VERSION")),
1.0,
);
gauge("play_shares_total", "counter", "Episodes ipx servers sent to be shared.", "", SHARES.load(Relaxed) as f64);
REQUESTS.render(
&mut out,
"play_http_request_duration_seconds",
"Requests answered and the seconds each took, by method, route and status.",
);
out
}
/// Serves /metrics on a listener of its own: the public port is behind the tunnel with no Access
/// in front, and these are for the LAN.
// ponytail: no gzip, unlike the directory's (#253): a few dozen lines a scrape. Add tower-http's
// CompressionLayer if the routes grow.
pub async fn serve(listener: TcpListener) {
let started = Instant::now();
let app = Router::new().route(
"/metrics",
axum::routing::get(move || async move {
([(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4")], render(started))
}),
);
if let Err(e) = axum::serve(listener, app).await {
tracing::error!(error = %e, "metrics stopped");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn every_play_metric_grafana_queries_is_served() {
// A row for each name, so a histogram's lines are there to find.
REQUESTS.observe("method=\"GET\",route=\"/e/{id}\",status=\"200\"", 0.01);
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let at = l.local_addr().unwrap();
tokio::spawn(serve(l));
let text = reqwest::get(format!("http://{at}/metrics")).await.unwrap().text().await.unwrap();
let src = [include_str!("../../../grafana/dashboard.py"), include_str!("../../../grafana/alerts.py")].concat();
let names: std::collections::BTreeSet<&str> = src
.match_indices("play_")
.filter(|(i, _)| !src[..*i].ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_'))
.filter_map(|(i, _)| {
let rest = &src[i..];
let end = rest.find(|c: char| !(c.is_ascii_lowercase() || c == '_')).unwrap_or(rest.len());
// A query names one with its labels, or the dashboard keeps it in a string; ipx's
// events, such as play_start in a panel's description, are neither.
rest[end..].starts_with(['{', '"']).then(|| &rest[..end])
})
// A histogram is queried by its series' names and served under its own.
.map(|n| n.trim_end_matches("_bucket").trim_end_matches("_count").trim_end_matches("_sum"))
.collect();
assert!(names.len() >= 3, "{names:?}");
for n in names {
// Memory comes from /proc, which a Mac has not.
if n.starts_with("play_process_") && process().0.is_none() {
continue;
}
assert!(text.contains(&format!("# TYPE {n} ")), "{n} is queried by grafana/ but not served: {text}");
}
}
}

27
crates/wire/Cargo.toml Normal file
View File

@@ -0,0 +1,27 @@
[package]
name = "ipx-wire"
version = "0.0.0"
publish = false
edition.workspace = true
[lints]
workspace = true
[dependencies]
axum.workspace = true
prost.workspace = true
prost-reflect.workspace = true
prost-types.workspace = true
serde.workspace = true
serde_json.workspace = true
tracing.workspace = true
[build-dependencies]
prost.workspace = true
prost-build.workspace = true
prost-types.workspace = true
protox.workspace = true
[dev-dependencies]
tokio.workspace = true
tower.workspace = true

47
crates/wire/build.rs Normal file
View File

@@ -0,0 +1,47 @@
//! Compiles the `.proto` files into one descriptor set the crate reads at run time, and into Rust
//! structs (prost) that read the handlers' JSON straight into protobuf (#470). protox is a
//! compiler in Rust, so building needs no `protoc` on the host or in the image.
use prost::Message as _;
use std::fmt::Write as _;
fn main() {
let files = ["proto/ipx.proto", "proto/directory.proto", "proto/play.proto"];
for f in files {
println!("cargo:rerun-if-changed={f}");
}
let set = protox::compile(files, ["proto"]).unwrap_or_else(|e| panic!("{e:?}"));
let out = std::path::PathBuf::from(std::env::var("OUT_DIR").expect("cargo sets OUT_DIR"));
std::fs::write(out.join("wire.bin"), set.encode_to_vec()).expect("writing the descriptor set");
// Every message that reads from JSON with serde: all but the bodies holding Google's Value or
// ListValue, whose JSON serde cannot read; those go the slow way, through prost-reflect.
let mut config = prost_build::Config::new();
let mut fast = String::from(
"/// An answer's JSON as message `name` in protobuf, when `name` has a struct here.\n\
pub fn json_to_proto(name: &str, json: &[u8]) -> Option<Result<Vec<u8>, String>> {\n match name {\n",
);
for file in set.file.iter().filter(|f| f.package() != "google.protobuf") {
for m in &file.message_type {
if m.field.iter().any(|f| f.type_name().starts_with(".google.")) {
continue;
}
let path = format!(".{}.{}", file.package(), m.name());
// A list message is the JSON array itself.
let list = matches!(&m.field[..], [only] if only.name() == "items"
&& only.label() == prost_types::field_descriptor_proto::Label::Repeated);
let attrs = if list {
"#[derive(serde::Deserialize)] #[serde(transparent)]"
} else {
// Debug builds refuse a field the message lacks, as the slow way does.
"#[derive(serde::Deserialize)] #[serde(default)] #[cfg_attr(debug_assertions, serde(deny_unknown_fields))]"
};
config.type_attribute(&path, attrs);
writeln!(fast, " {:?} => Some(encode::<pb::{}::{}>(json)),", &path[1..], file.package(), m.name())
.expect("writing to a String");
}
}
fast.push_str(" _ => None,\n }\n}\n");
std::fs::write(out.join("fast.rs"), fast).expect("writing fast.rs");
config.out_dir(&out).compile_fds(set).unwrap_or_else(|e| panic!("{e:?}"));
}

View File

@@ -0,0 +1,94 @@
// ipx-directory's API under /v1 (crates/directory/src/wire.rs), each message named after the Rust
// struct it mirrors. A field added there goes here too; debug builds refuse an answer with a field
// missing here. A message whose only field is `repeated items` is a JSON array.
syntax = "proto3";
package directory;
// GET /v1/me.
message Me {
string name = 1;
// "ro", "rw" or "rwa".
string access = 2;
}
message Listing {
string id = 1;
string url = 2;
optional string title = 3;
optional string image = 4;
optional string category = 5;
optional string subcategory = 6;
bool podcast = 7;
int64 subscribers = 8;
}
// GET /v1/feeds, GET /v1/popular.
message Listings {
repeated Listing items = 1;
}
message Item {
string guid = 1;
optional string title = 2;
optional string link = 3;
optional int64 published = 4;
optional int64 duration = 5;
optional string description = 6;
}
// GET /v1/feeds/{id}, POST /v1/feeds/{id}/refresh: a Listing's fields and these.
message FeedPage {
string id = 1;
string url = 2;
optional string title = 3;
optional string image = 4;
optional string category = 5;
optional string subcategory = 6;
bool podcast = 7;
int64 subscribers = 8;
optional string description = 9;
optional string failing = 10;
repeated Item items = 11;
}
message SnapshotEntry {
string url = 1;
int64 subscribers = 2;
optional string category = 3;
}
// POST /v1/snapshot, the body.
message Snapshot {
repeated SnapshotEntry items = 1;
}
// POST /v1/snapshot, the answer.
message SnapshotResult {
uint64 accepted = 1;
uint64 refused_private = 2;
uint64 refused_blocked = 3;
uint64 refused_invalid = 4;
}
message Instance {
string name = 1;
int64 feeds = 2;
int64 subscribers = 3;
}
// GET /v1/instances.
message Instances {
repeated Instance items = 1;
}
message Blocked {
string id = 1;
optional string url = 2;
optional string title = 3;
int64 at = 4;
}
// GET /v1/blocked.
message BlockedList {
repeated Blocked items = 1;
}

550
crates/wire/proto/ipx.proto Normal file
View File

@@ -0,0 +1,550 @@
// ipx's API under /api (crates/ipx/src/web.rs), the same answers its JSON gives, each message named
// after the Rust struct it mirrors where there is one (web/src/types.ts mirrors the same). A field
// added in Rust goes here too: debug builds refuse an answer with a field missing here.
//
// How the JSON maps (crates/wire/src/lib.rs):
// * A field name is the JSON key.
// * A Rust Option is `optional`, or a message; so is a field with a serde default, which an absent
// field must leave to Rust.
// * A message whose only field is `repeated ... items` is a JSON array, top-level or as a field.
// An Option<Vec> in a body is one (Words), so leaving a list alone and emptying it differ.
// * A body field that takes null to clear it is a google.protobuf.Value: absent leaves it, null
// clears it, a value sets it.
// * An answer of JSON null stays JSON null: the empty message would be a row of defaults.
syntax = "proto3";
package ipx;
import "google/protobuf/struct.proto";
import "directory.proto";
// A list of words, as an Option<Vec<String>> in a body: absent, or this.
message Words {
repeated string items = 1;
}
// ---- signing in, and you ----
// POST /api/login, the body.
message Credentials {
string name = 1;
string password = 2;
}
// POST /api/login, the answer.
message SignedIn {
string name = 1;
bool admin = 2;
}
message Theme {
string name = 1;
string mode = 2;
}
// GET /api/me.
message Me {
string name = 1;
bool admin = 2;
optional string sign_out = 3;
repeated string blocked = 4;
int64 deadair_saved = 5;
optional Theme theme = 6;
string version = 7;
bool typesafe_key_set = 8;
// "server" or "own".
string signals = 9;
uint64 signal_days = 10;
}
// PATCH /api/me, the body.
message MePatch {
Words blocked = 1;
google.protobuf.Value typesafe_key = 2;
}
message ApiToken {
int64 id = 1;
string name = 2;
int64 created = 3;
optional int64 last_used = 4;
}
// GET /api/tokens.
message ApiTokens {
repeated ApiToken items = 1;
}
// POST /api/tokens, the body.
message NewToken {
string name = 1;
}
// POST /api/tokens, the answer: the only time the token is shown.
message MadeToken {
int64 id = 1;
string name = 2;
string token = 3;
}
// POST /api/push/devices, the body.
message PushDevice {
string token = 1;
optional bool sandbox = 2;
}
// ---- feeds ----
message FailingRow {
string reason = 1;
optional string new_url = 2;
}
message FeedRow {
string id = 1;
string url = 2;
optional string title = 3;
optional string image = 4;
optional string folder = 5;
optional string category = 6;
optional string feed_category = 7;
repeated string keywords = 8;
repeated string blocked = 9;
bool deadair = 10;
int64 deadair_pause = 11;
bool allow_explicit = 12;
bool auto_download = 13;
optional uint64 max_new_per_check = 14;
optional string group = 15;
bool orphaned = 16;
bool managed = 17;
optional string schedule = 18;
optional uint64 schedule_mins = 19;
uint64 every_mins = 20;
optional int64 last_checked = 21;
optional int64 next_check = 22;
optional string last_error = 23;
optional FailingRow failing = 24;
int64 entries = 25;
int64 downloaded = 26;
int64 unread = 27;
int64 subscribers = 28;
bool pinned = 29;
bool kept = 30;
bool hide_from_all = 31;
bool hide_from_signals = 32;
bool private = 33;
bool private_by_address = 34;
// Has an audio or video file: on the Podcasts shelf (#474).
bool podcast = 35;
}
// GET /api/feeds.
message FeedRows {
repeated FeedRow items = 1;
}
// POST /api/feeds, the body.
message NewFeed {
string url = 1;
optional string folder = 2;
repeated string keywords = 3;
optional bool allow_explicit = 4;
}
// POST /api/feeds, the answer.
message AddedFeed {
string id = 1;
bool existing = 2;
}
// PATCH /api/feeds/{id}, the body: what is there changes, what is not is left.
message FeedPatch {
optional string url = 1;
google.protobuf.Value schedule = 2;
google.protobuf.Value folder = 3;
google.protobuf.Value category = 4;
Words keywords = 5;
Words blocked = 6;
optional bool allow_explicit = 7;
optional bool auto_download = 8;
google.protobuf.Value max_new_per_check = 9;
optional bool pinned = 10;
optional bool kept = 11;
optional bool hide_from_all = 12;
optional bool hide_from_signals = 13;
google.protobuf.Value deadair = 14;
optional int64 deadair_pause = 15;
optional bool private = 16;
}
// POST /api/feeds/{id}/download-latest, the body.
message HowMany {
optional int64 count = 1;
// One season, all of it (#482): its number, or "none" for the episodes naming none.
optional string season = 2;
}
// POST /api/feeds/{id}/download-latest, the answer.
message Queued {
uint64 queued = 1;
}
// POST /api/feeds/{id}/read-all, POST /api/read-all.
message Marked {
uint64 marked = 1;
}
// POST /api/fetch, the body.
message FetchBody {
optional string feed = 1;
optional bool force = 2;
}
// POST /api/opml, the body.
message OpmlBody {
string xml = 1;
}
// POST /api/opml, the answer.
message OpmlImported {
uint64 added = 1;
uint64 already = 2;
}
// ---- items ----
message EncRow {
int64 id = 1;
optional int64 deadair = 2;
optional bool deadair_pending = 3;
string feed_id = 4;
string guid = 5;
string url = 6;
optional string mime = 7;
optional int64 length = 8;
optional string path = 9;
string state = 10;
optional string last_error = 11;
}
// GET /api/entries/{feed_id}/{guid}.
message EntryRow {
string guid = 1;
string feed_id = 2;
optional string title = 3;
optional string link = 4;
optional int64 published = 5;
optional string description = 6;
optional string markdown = 7;
optional string markdown_html = 8;
bool read = 9;
bool flagged = 10;
optional string image = 11;
optional int64 duration = 12;
optional int64 episode = 13;
optional int64 season = 14;
int64 position = 15;
repeated EncRow enclosures = 16;
}
// GET /api/entries, /api/feeds/{id}/entries, /api/signals/{id}/entries.
message EntryPage {
int64 total = 1;
repeated EntryRow entries = 2;
}
// POST /api/playlists and PATCH /api/playlists/{id}, the body: a smart playlist (#476).
message PlaylistSpec {
string name = 1;
repeated string feeds = 2;
repeated string priority = 3;
bool only_unplayed = 4;
bool oldest_first = 5;
}
// A playlist in GET /api/playlists, with how many episodes it holds now.
message PlaylistRow {
int64 id = 1;
string name = 2;
repeated string feeds = 3;
repeated string priority = 4;
bool only_unplayed = 5;
bool oldest_first = 6;
int64 items = 7;
}
message PlaylistRows {
repeated PlaylistRow items = 1;
}
// One season of a podcast in GET /api/feeds/{id}/seasons (#482): its number, unset for the
// episodes that name none, how many episodes it has and how many are unread.
message SeasonRow {
optional int64 season = 1;
int64 episodes = 2;
int64 unread = 3;
}
message SeasonRows {
repeated SeasonRow items = 1;
}
// POST /api/playlists, the answer.
message PlaylistId {
int64 id = 1;
}
// One of Up Next's episodes (#473).
message QueueItem {
string feed_id = 1;
string guid = 2;
}
// PUT /api/queue, the body: Up Next in its new order. The answer is it as saved, an EntryPage.
message QueueItems {
repeated QueueItem items = 1;
}
// POST /api/entries/{feed_id}/{guid}/flags, the body. The answer is the feed's FeedRow, or JSON
// null when the feed is not yours.
message Flags {
optional bool read = 1;
optional bool flagged = 2;
}
// POST /api/entries/{feed_id}/{guid}/position, the body.
message Position {
int64 secs = 1;
optional int64 duration = 2;
optional int64 deadair = 3;
}
// POST /api/entries/{feed_id}/{guid}/share, the body.
message ShareBody {
optional int64 enc = 1;
}
// POST /api/entries/{feed_id}/{guid}/share, the answer.
message ShareLink {
optional string url = 1;
optional string why = 2;
}
// ---- Signals ----
message SignalRow {
int64 id = 1;
string name = 2;
repeated string keywords = 3;
optional string description = 4;
optional string icon = 5;
int64 items = 6;
int64 unread = 7;
}
// GET /api/signals.
message SignalRows {
repeated SignalRow items = 1;
}
// POST /api/signals and PATCH /api/signals/{id}, the body.
message SignalBody {
optional string name = 1;
Words keywords = 2;
google.protobuf.Value description = 3;
google.protobuf.Value icon = 4;
}
// POST /api/signals, the answer.
message SignalId {
int64 id = 1;
}
// POST /api/signals/icon, the body. Each candidate is [icon, label].
message IconAsk {
string name = 1;
repeated string keywords = 2;
optional string description = 3;
repeated google.protobuf.ListValue candidates = 4;
}
// POST /api/signals/icon, the answer.
message Icon {
string icon = 1;
}
// ---- the directory ----
message PopularRow {
string id = 1;
optional string title = 2;
optional string image = 3;
int64 subscribers = 4;
bool subscribed = 5;
optional string feed = 6;
optional string category = 7;
optional string subcategory = 8;
bool podcast = 9;
}
// GET /api/popular, GET /api/directory.
message PopularRows {
repeated PopularRow items = 1;
}
message ListedItem {
string guid = 1;
optional string title = 2;
optional string link = 3;
optional int64 published = 4;
optional int64 duration = 5;
optional string description = 6;
}
// GET /api/directory/{id}.
message Listed {
optional string description = 1;
optional string failing = 2;
repeated ListedItem items = 3;
bool can_admin = 4;
}
// POST /api/popular/{id}, the answer.
message FeedId {
string id = 1;
}
message BlockedRow {
string id = 1;
optional string title = 2;
int64 at = 3;
}
// GET /api/directory-admin.
message DirAdmin {
repeated directory.Instance instances = 1;
repeated BlockedRow blocked = 2;
}
// When the snapshot last went: a SnapshotResult's fields when it was taken, the error when not.
message Shared {
int64 at = 1;
optional uint64 accepted = 2;
optional uint64 refused_private = 3;
optional uint64 refused_blocked = 4;
optional uint64 refused_invalid = 5;
optional string error = 6;
}
// GET /api/directory-status.
message DirStatus {
bool configured = 1;
optional string name = 2;
optional string access = 3;
optional string error = 4;
optional Shared shared = 5;
}
// ---- the server ----
// GET /api/status.
message Status {
uint64 feeds = 1;
int64 pending = 2;
int64 downloaded = 3;
string version = 4;
}
// GET /api/settings.
message Settings {
string schedule = 1;
uint64 every_mins = 2;
uint64 max_new_per_check = 3;
repeated string media_types = 4;
string download_dir = 5;
double max_total_gb = 6;
uint64 max_age_days = 7;
uint64 art_cache_mb = 8;
string directory_url = 9;
bool directory_token_set = 10;
bool directory_share = 11;
string play_url = 12;
bool play_token_set = 13;
bool signals_on_server = 14;
uint64 signal_days = 15;
bool typesafe_server_key = 16;
}
// PATCH /api/settings, the body.
message SettingsPatch {
optional string schedule = 1;
optional uint64 max_new_per_check = 2;
Words media_types = 3;
optional double max_total_gb = 4;
optional uint64 max_age_days = 5;
optional uint64 art_cache_mb = 6;
optional string directory_url = 7;
optional string directory_token = 8;
optional bool directory_share = 9;
optional string play_url = 10;
optional string play_token = 11;
optional bool signals_on_server = 12;
optional uint64 signal_days = 13;
}
message Account {
int64 id = 1;
string name = 2;
bool admin = 3;
bool password = 4;
optional int64 created = 5;
optional int64 last_login = 6;
}
// GET /api/users.
message Accounts {
repeated Account items = 1;
}
// POST /api/users, the body.
message NewUser {
string name = 1;
optional string password = 2;
optional bool admin = 3;
}
// PATCH /api/users/{id}, the body.
message UserPatch {
bool admin = 1;
}
message LogLine {
uint64 seq = 1;
int64 ts = 2;
string level = 3;
string target = 4;
string msg = 5;
}
// GET /api/logs.
message LogPage {
repeated LogLine lines = 1;
uint64 latest = 2;
}
// POST /api/client, the body.
message ClientEvent {
string ev = 1;
optional string msg = 2;
optional string src = 3;
optional uint32 line = 4;
optional string feed = 5;
optional int64 enclosure = 6;
optional bool deadair = 7;
optional uint64 ms = 8;
optional string filter = 9;
optional string trace = 10;
optional string span = 11;
optional uint64 start = 12;
optional string state = 13;
}

View File

@@ -0,0 +1,25 @@
// ipx-play's API (crates/play/src/lib.rs), each message named after the Rust struct it mirrors.
// A field added there goes here too; debug builds refuse an answer with a field missing here.
syntax = "proto3";
package play;
// POST /v1/shares, the body.
message Episode {
string feed_url = 1;
string guid = 2;
optional string feed_title = 3;
optional string feed_image = 4;
optional string title = 5;
optional string description = 6;
optional string link = 7;
optional int64 published = 8;
optional int64 duration = 9;
string audio_url = 10;
optional string mime = 11;
}
// POST /v1/shares, the answer.
message Shared {
string id = 1;
string url = 2;
}

345
crates/wire/src/lib.rs Normal file
View File

@@ -0,0 +1,345 @@
//! Protobuf beside JSON (#465). The handlers speak JSON, as they always have; a route's
//! messages in `proto/` say what the same answer is in protobuf, and `negotiate` converts at the
//! edge: a request body sent as `application/x-protobuf` becomes the JSON the handler reads, and
//! an answer becomes protobuf for a client whose `Accept` asks for it. Anyone not asking gets JSON
//! exactly as before.
//!
//! How a message stands for JSON is said at the top of `proto/ipx.proto`: names as in JSON, an
//! Option `optional`, a message of only `repeated items` an array, null-to-clear a
//! `google.protobuf.Value`.
//!
//! Debug builds convert every JSON answer of a route in the table, asked for or not, refusing
//! fields the message lacks, and answer 500 when a route has no message: the cargo tests and the
//! browser suite, which run debug builds, then fail on a field added in Rust and not in `proto/`.
use std::sync::LazyLock;
use axum::body::{Body, to_bytes};
use axum::extract::{MatchedPath, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use prost_reflect::{DescriptorPool, DeserializeOptions, DynamicMessage, Kind, MessageDescriptor, SerializeOptions};
use serde::de::DeserializeOwned;
use serde_json::Value;
pub const PROTOBUF: &str = "application/x-protobuf";
/// For a client to encode and decode the structs in `pb` without naming prost itself.
pub use prost::Message;
/// The messages as Rust structs, which the answers go into from their JSON and which a client
/// in Rust reads and writes (#470): prost's own encoding, several times faster than going through
/// the descriptors at run time.
#[allow(clippy::all, clippy::pedantic, missing_docs)]
pub mod pb {
pub mod directory {
include!(concat!(env!("OUT_DIR"), "/directory.rs"));
}
pub mod ipx {
include!(concat!(env!("OUT_DIR"), "/ipx.rs"));
}
pub mod play {
include!(concat!(env!("OUT_DIR"), "/play.rs"));
}
}
include!(concat!(env!("OUT_DIR"), "/fast.rs"));
/// The JSON an answer was into its struct, and that into protobuf.
fn encode<T: DeserializeOwned + prost::Message>(json: &[u8]) -> Result<Vec<u8>, String> {
Ok(serde_json::from_slice::<T>(json).map_err(|e| e.to_string())?.encode_to_vec())
}
/// The most read of a body either way: axum's own limit for `Json`.
const LIMIT: usize = 2 << 20;
static POOL: LazyLock<DescriptorPool> = LazyLock::new(|| {
DescriptorPool::decode(include_bytes!(concat!(env!("OUT_DIR"), "/wire.bin")).as_slice())
.expect("build.rs wrote a valid descriptor set")
});
/// Each route's method, its path as the router has it, the message its body is and the message
/// it answers, by full name; "" where it takes or answers no JSON.
pub type Routes = &'static [(&'static str, &'static str, &'static str, &'static str)];
/// A message by full name (`ipx.Feed`).
pub fn message(name: &str) -> Option<MessageDescriptor> {
POOL.get_message_by_name(name)
}
fn is_list(d: &MessageDescriptor) -> bool {
let mut f = d.fields();
matches!((f.next(), f.next()), (Some(only), None) if only.name() == "items" && only.is_list())
}
/// Each message field of `d` in `v`, with its descriptor, for `wrap` and `unwrap` to go down.
/// Not maps, and not Google's own types, whose JSON is theirs.
fn children<'a>(d: &MessageDescriptor, v: &'a mut Value) -> Vec<(MessageDescriptor, &'a mut Value)> {
let Some(obj) = v.as_object_mut() else { return vec![] };
let mut out = Vec::new();
for (key, val) in obj.iter_mut() {
let Some(f) = d.get_field_by_name(key) else { continue };
let Kind::Message(m) = f.kind() else { continue };
if f.is_map() || m.package_name() == "google.protobuf" {
continue;
}
if f.is_list() {
out.extend(val.as_array_mut().into_iter().flatten().map(|i| (m.clone(), i)));
} else {
out.push((m, val));
}
}
out
}
/// A JSON array where a list message is, made that message.
fn wrap(d: &MessageDescriptor, v: &mut Value) {
if v.is_array() && is_list(d) {
*v = serde_json::json!({ "items": v.take() });
}
for (m, c) in children(d, v) {
wrap(&m, c);
}
}
/// A list message made the array it stands for; none sent is an empty one.
fn unwrap(d: &MessageDescriptor, v: &mut Value) {
for (m, c) in children(d, v) {
unwrap(&m, c);
}
if is_list(d) {
*v = match v["items"].take() {
Value::Null => Value::Array(vec![]),
items => items,
};
}
}
/// JSON to protobuf. `strict` refuses a field the message does not have, where otherwise it is
/// left out, as a newer server's field is for an older client. JSON null is the empty message.
pub fn to_proto(d: &MessageDescriptor, mut v: Value, strict: bool) -> Result<Vec<u8>, String> {
if v.is_null() {
return Ok(vec![]);
}
wrap(d, &mut v);
let opts = DeserializeOptions::new().deny_unknown_fields(strict);
let msg =
DynamicMessage::deserialize_with_options(d.clone(), v, &opts).map_err(|e| format!("{}: {e}", d.full_name()))?;
Ok(msg.encode_to_vec())
}
/// Protobuf to the JSON the same struct reads: field names as written, 64-bit numbers as numbers,
/// a field without presence always, so a default value reads as itself, and an `optional` or a
/// message only when sent, so an absent one reads as None.
pub fn from_proto(d: &MessageDescriptor, bytes: &[u8]) -> Result<Value, String> {
let msg = DynamicMessage::decode(d.clone(), bytes).map_err(|e| format!("{}: {e}", d.full_name()))?;
let opts =
SerializeOptions::new().use_proto_field_name(true).stringify_64_bit_integers(false).skip_default_fields(false);
let mut v = msg.serialize_with_options(serde_json::value::Serializer, &opts).map_err(|e| e.to_string())?;
unwrap(d, &mut v);
whole(&mut v);
Ok(v)
}
/// A whole number as an integer: a google.protobuf.Value holds every number as a double, and
/// `3.0` does not read as a usize where `3` reads as an f64 too.
fn whole(v: &mut Value) {
match v {
Value::Number(n) => {
if let Some(f) = n.as_f64().filter(|f| n.is_f64() && f.fract() == 0.0 && f.abs() < 9e15) {
*v = Value::from(f as i64);
}
}
Value::Array(a) => a.iter_mut().for_each(whole),
Value::Object(o) => o.values_mut().for_each(whole),
_ => {}
}
}
fn is(headers: &HeaderMap, name: header::HeaderName, mime: &str) -> bool {
// shortcut: a substring, not a parsed Accept, so `q=0` still counts; parse it if a client sends one.
headers.get(name).and_then(|v| v.to_str().ok()).is_some_and(|v| v.contains(mime))
}
fn refuse(code: StatusCode, msg: String) -> Response {
(code, axum::Json(serde_json::json!({ "error": msg }))).into_response()
}
/// The layer, as `route_layer(from_fn_with_state(ROUTES, ipx_wire::negotiate))`, inside any
/// request decompression so it reads the body unpacked.
pub async fn negotiate(State(routes): State<Routes>, path: MatchedPath, req: Request, next: Next) -> Response {
let method = req.method().as_str().to_owned();
let (takes, answers) =
routes.iter().find(|r| r.0 == method && r.1 == path.as_str()).map(|r| (r.2, r.3)).unwrap_or(("", ""));
let req = if is(req.headers(), header::CONTENT_TYPE, PROTOBUF) {
let Some(d) = message(takes) else {
return refuse(StatusCode::UNSUPPORTED_MEDIA_TYPE, format!("{method} {} takes no protobuf", path.as_str()));
};
let (mut parts, body) = req.into_parts();
let Ok(bytes) = to_bytes(body, LIMIT).await else {
return refuse(StatusCode::PAYLOAD_TOO_LARGE, "the body is too large".into());
};
let json = match from_proto(&d, &bytes) {
Ok(v) => v.to_string(),
Err(e) => return refuse(StatusCode::BAD_REQUEST, format!("the body did not read as {e}")),
};
parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
parts.headers.remove(header::CONTENT_LENGTH);
Request::from_parts(parts, Body::from(json))
} else {
req
};
let wants = is(req.headers(), header::ACCEPT, PROTOBUF);
let mut resp = next.run(req).await;
if !answers.is_empty() {
resp.headers_mut().append(header::VARY, HeaderValue::from_static("accept"));
}
let json = resp.status().is_success() && is(resp.headers(), header::CONTENT_TYPE, "application/json");
if !json || !(wants || cfg!(debug_assertions)) {
return resp;
}
let Some(d) = message(answers) else {
if cfg!(debug_assertions) {
return refuse(
StatusCode::INTERNAL_SERVER_ERROR,
format!("{method} {} answers JSON with no message for it in ipx-wire", path.as_str()),
);
}
return resp;
};
let (mut parts, body) = resp.into_parts();
let Ok(bytes) = to_bytes(body, usize::MAX).await else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
// None stays JSON null: as protobuf it would be the empty message, which is also every field
// at its default, and a client could not tell "no feed row" from a blank one.
if bytes.trim_ascii() == b"null" {
return Response::from_parts(parts, Body::from(bytes));
}
let converted = json_to_proto(answers, &bytes).unwrap_or_else(|| {
serde_json::from_slice(&bytes).map_err(|e| e.to_string()).and_then(|v| to_proto(&d, v, cfg!(debug_assertions)))
});
match converted {
Ok(pb) if wants => {
// Which message it is, for a client with no table of routes (the page).
let ct = format!("{PROTOBUF}; messageType={answers}");
parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_str(&ct).expect("a message name is ASCII"));
parts.headers.remove(header::CONTENT_LENGTH);
Response::from_parts(parts, Body::from(pb))
}
Err(e) if cfg!(debug_assertions) => refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("not as protobuf: {e}")),
// Asked for protobuf and it would not convert: the JSON, which says what it is.
Err(e) => {
tracing::warn!(route = path.as_str(), error = %e, "answer did not convert to protobuf");
Response::from_parts(parts, Body::from(bytes))
}
Ok(_) => Response::from_parts(parts, Body::from(bytes)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::routing::post;
use serde_json::json;
use tower::ServiceExt as _;
fn round(name: &str, v: Value) -> Value {
let d = message(name).unwrap();
from_proto(&d, &to_proto(&d, v, true).unwrap()).unwrap()
}
#[test]
fn every_message_named_in_a_table_exists() {
// The tables live in the services; these are the names that would break a client first.
for m in ["ipx.FeedRows", "ipx.EntryPage", "ipx.Me", "ipx.Position", "directory.Snapshot", "play.Shared"] {
assert!(message(m).is_some(), "{m}");
}
}
#[test]
fn options_and_lists_come_back_as_they_went() {
let ep = json!({ "feed_url": "https://a/f", "guid": "g", "title": "T", "published": 1_700_000_000_000_i64,
"audio_url": "https://a/1.mp3" });
let back = round("play.Episode", ep.clone());
assert_eq!(back, ep, "absent optionals stay absent, 64-bit numbers stay numbers");
let rows = json!([{ "id": "a", "url": "u", "subscribers": 2, "podcast": true }]);
let back = round("directory.Listings", rows);
assert_eq!(back[0]["id"], "a");
assert_eq!(back[0]["subscribers"], 2);
assert_eq!(round("directory.Listings", json!([])), json!([]), "an empty list is an empty array");
}
#[test]
fn a_patch_tells_absent_from_empty_and_from_null() {
assert_eq!(round("ipx.MePatch", json!({})), json!({}), "nothing sent changes nothing");
assert_eq!(round("ipx.MePatch", json!({ "blocked": [] })), json!({ "blocked": [] }), "emptied");
assert_eq!(round("ipx.MePatch", json!({ "typesafe_key": null })), json!({ "typesafe_key": null }), "cleared");
assert_eq!(
round("ipx.FeedPatch", json!({ "max_new_per_check": 3, "pinned": false })),
json!({
"max_new_per_check": 3, "pinned": false })
);
}
#[test]
fn the_structs_encode_as_the_descriptors_do() {
let feeds = json!([{ "id": "a", "url": "u", "title": null, "keywords": ["k"], "every_mins": 60,
"failing": { "reason": "gone", "new_url": null }, "subscribers": 2, "private": true }]);
let slow = to_proto(&message("ipx.FeedRows").unwrap(), feeds.clone(), false).unwrap();
let fast = json_to_proto("ipx.FeedRows", feeds.to_string().as_bytes()).unwrap().unwrap();
assert_eq!(fast, slow);
assert!(json_to_proto("ipx.FeedPatch", b"{}").is_none(), "a body with a Value goes the slow way");
if cfg!(debug_assertions) {
assert!(json_to_proto("play.Shared", br#"{"id":"x","url":"u","new":1}"#).unwrap().is_err());
}
}
#[test]
fn strict_refuses_a_field_the_message_lacks() {
let d = message("play.Shared").unwrap();
assert!(to_proto(&d, json!({ "id": "x", "url": "u", "new": 1 }), true).is_err());
assert!(to_proto(&d, json!({ "id": "x", "url": "u", "new": 1 }), false).is_ok());
assert_eq!(to_proto(&message("ipx.FeedRow").unwrap(), Value::Null, true).unwrap(), Vec::<u8>::new());
}
#[tokio::test]
async fn the_layer_converts_only_for_who_asks() {
const ROUTES: Routes = &[("POST", "/v1/shares", "play.Episode", "play.Shared")];
let app =
axum::Router::new()
.route(
"/v1/shares",
post(|axum::Json(e): axum::Json<Value>| async move {
axum::Json(json!({ "id": e["guid"], "url": "u" }))
}),
)
.route_layer(axum::middleware::from_fn_with_state(ROUTES, negotiate));
let ep =
pb::play::Episode { feed_url: "f".into(), guid: "g1".into(), audio_url: "a".into(), ..Default::default() };
let body = ep.encode_to_vec();
let ask = |accept: &'static str| {
Request::post("/v1/shares")
.header(header::CONTENT_TYPE, PROTOBUF)
.header(header::ACCEPT, accept)
.body(Body::from(body.clone()))
.unwrap()
};
let resp = app.clone().oneshot(ask(PROTOBUF)).await.unwrap();
assert_eq!(resp.headers()[header::CONTENT_TYPE], "application/x-protobuf; messageType=play.Shared");
let got = pb::play::Shared::decode(to_bytes(resp.into_body(), LIMIT).await.unwrap()).unwrap();
assert_eq!((got.id.as_str(), got.url.as_str()), ("g1", "u"));
let resp = app.clone().oneshot(ask("application/json")).await.unwrap();
assert_eq!(resp.headers()[header::CONTENT_TYPE], "application/json");
let bad =
Request::post("/v1/shares").header(header::CONTENT_TYPE, PROTOBUF).body(Body::from("\u{ff}")).unwrap();
assert_eq!(app.oneshot(bad).await.unwrap().status(), StatusCode::BAD_REQUEST);
}
}

View File

@@ -10,6 +10,11 @@ ignore = [
# ringbuf 0.4's double free needs an element whose Drop panics; librqbit-utp's buffer holds
# only u8, which has no Drop. Its fix is ringbuf 0.5, which librqbit 9.0.1 cannot take (#281).
{ id = "RUSTSEC-2026-0293", reason = "librqbit-utp's ring buffer holds u8: no Drop to panic" },
# SQLite before 3.54 can return stale memory when it opens a database with a -wal file another
# party crafted. ipx opens only its own state.db, in its own data directory, and production is
# on Postgres. The fix is libsqlite3-sys 0.39, which sqlx-sqlite 0.9.0, the latest, cannot take:
# drop this when sqlx allows it (#467).
{ id = "RUSTSEC-2026-0459", reason = "opens only its own SQLite files; waits on sqlx for libsqlite3-sys 0.39 (#467)" },
]
[licenses]

View File

@@ -208,6 +208,20 @@ else a `401`. A feed's items and files (its entries, `download-latest`, `/api/en
| `GET /api/logs` | admin-only; the ring buffer, with a sequence cursor |
| `GET /media/{id}` | the file, with Range support so seeking works |
Every route that takes or answers JSON also speaks protobuf (#465): `Content-Type:
application/x-protobuf` for a body, `Accept: application/x-protobuf` for an answer, JSON
otherwise. The messages are in `crates/wire/proto/` (ipx, directory and play), and the handlers do
not know: `ipx_wire::negotiate`, a layer on each service's routes, converts the JSON at the edge
by its table of each route's messages (`WIRE` in `web.rs`, `api.rs` and play's `lib.rs`). A route
added to a router goes in its table. Debug builds convert every JSON answer strictly, so the cargo
tests and the browser suite answer `500` for a field missing from the `.proto` or a route missing
from the table. Errors stay JSON, and so does an answer of null. An answer goes into a struct
generated from its message (prost, in `crates/wire/build.rs`) and out as protobuf, named in its
`Content-Type` (`application/x-protobuf; messageType=ipx.FeedRows`); the page reads it with
`web/src/wire.ts`, a decoder of its own driven by the same `.proto` files, which `web/build.mts`
reads into the page and the offline worker (#470). The iOS app's own calls go in protobuf (#469), from Swift
generated off the same files: a change to them is `sh ios/scripts/proto.sh` too.
Show notes are feed-supplied HTML from an untrusted source, sanitized with `ammonia` server-side
before they reach the page.

View File

@@ -162,6 +162,9 @@ blocks it, so no snapshot brings it back.
| `DELETE /v1/instances/{name}` | rwa | drop one token's snapshot, its counts with it |
| `POST /v1/feeds/{id}/refresh` | rwa | fetch the feed now, answering with its page |
Each also speaks protobuf, by `Accept` and `Content-Type: application/x-protobuf` (#465), in the
messages of `crates/wire/proto/directory.proto`; ipx asks for it.
A feed's `id` is the first 64 bits of the SHA-256 of its address, normalised (scheme and host in
lower case, no default port or fragment), so every server arrives at the same id. `subscribers`
is the sum over every token's latest snapshot. A feed is listed once the directory has read it as

View File

@@ -32,10 +32,13 @@ The compose service, beside `ipx-directory`:
environment:
PLAY_LOG_FORMAT: json
OTEL_EXPORTER_OTLP_ENDPOINT: http://192.168.1.130:4318 # Tempo is not on this network
# The dashboard's trace panels show only spans with this tag, as the others' are.
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=production
volumes:
- /mnt/fast/appdata/ipx-play:/config
ports:
- "8102:8102"
- "9191:9191" # /metrics, for Prometheus on the LAN; not in the tunnel
```
Its config, `/mnt/fast/appdata/ipx-play/play.toml`:
@@ -43,6 +46,9 @@ Its config, `/mnt/fast/appdata/ipx-play/play.toml`:
```toml
bind = "0.0.0.0:8102"
public_url = "https://play.ipxreader.app"
# Prometheus metrics, on a port of their own and not the one the tunnel publishes. Empty, or
# left out, serves none.
metrics_bind = "0.0.0.0:9191"
# One for each ipx server allowed to make links; `ipx-play token <name>` prints the lines.
[[tokens]]
@@ -60,6 +66,27 @@ The tunnel publishes `play.ipxreader.app` to `http://192.168.1.130:8102` with no
the pages are anyone's. cloudflared is not on the project's network, so not `ipx-play:8102`, as
the directory's route is the host's port too. `/v1` takes a token for everything.
## Watching it
Its traces go to Tempo as service `ipx-play`: a span a request, a child of ipx's when ipx shared
an episode, so one trace runs from the page's Share through ipx to here. Its log is a JSON line a
request (`target` `ipx_play::http`: `method`, `path`, `status`, `duration_ms`, `token`, the
server's name and never its token) and one a share (`an episode was shared`: `server`, `id`).
Its metrics (#458), on `metrics_bind`, scraped as `job="ipx-play"`, beside the directory's job in
Prometheus's config:
```yaml
- job_name: ipx-play
static_configs:
- targets: ["192.168.1.130:9191"]
```
`play_http_request_duration_seconds{method,route,status}` (a page opened is `route="/e/{id}"`, an
address no route has `route=""`), `play_shares_total`, `play_process_resident_bytes`,
`play_process_open_fds`, `play_uptime_seconds` and `play_build_info`. The iPX dashboard's
`ipx-play` row draws them, and the alert `ipx-play is down` fires when Prometheus cannot reach it.
## Setting up ipx
In Admin, Directory, Sharing episodes: the address ipx reaches it at, `http://ipx-play:8102`

View File

@@ -41,6 +41,8 @@ rules = [
"Prometheus cannot reach ipx's /metrics: the iPX container is down or restarting.", no_data="Alerting"),
rule("directory-down", "ipx-directory is down", 'up{job="ipx-directory"}', "lt", 1, "5m",
"Prometheus cannot reach the directory's /metrics.", no_data="Alerting"),
rule("play-down", "ipx-play is down", 'up{job="ipx-play"}', "lt", 1, "5m",
"Prometheus cannot reach ipx-play's /metrics: shared links are likely not opening.", no_data="Alerting"),
rule("web-down", "ipx-web is down", 'up{job="ipx-web"}', "lt", 1, "5m",
"Prometheus cannot reach Caddy's /metrics: the page is likely down too.", no_data="Alerting"),
# The worker: the daemon answers `ipxd status` while it is stuck, so only these say so.

View File

@@ -1,11 +1,11 @@
"""The iPX dashboard in Grafana: the three containers of the Arcane project ipx (ipx, ipx-web,
ipx-directory) and Tower under them, from Prometheus, Loki (their logs, shipped by Alloy) and Tempo.
"""The iPX dashboard in Grafana: the four containers of the Arcane project ipx (ipx, ipx-web,
ipx-directory, ipx-play) and Tower under them, from Prometheus, Loki (their logs, shipped by Alloy) and Tempo.
python3 grafana/dashboard.py > /mnt/fast/arcane/projects/monitoring/grafana-provisioning/dashboards/ipx.json
Grafana reads that file on its own within a minute; edits made in Grafana are refused. Rows go
top-down as a request does: an overview, Tower, then each container (ipx-web, ipx's API, its
worker and its process, the directory), then traces and logs. Prometheus scrapes ipx's /metrics
worker and its process, the directory, ipx-play), then traces and logs. Prometheus scrapes ipx's /metrics
(job ipx, #194) and Tower's node exporter (job node); nothing scrapes the containers themselves,
so ipx-web and the directory are read from their logs. The log panels read fields: ipx's
(ipc.rs log_event), ipx's metrics (metrics.rs), the directory's and Caddy's; renaming one has to be
@@ -41,7 +41,9 @@ WEB = ('{container="ipx-web"} |= "http.log.access" | json | __error__=""'
' | request_uri !~ "/(api|media)/.*" | request_remote_ip != "127.0.0.1"') # not its healthcheck
# Less what Caddy says at every start, by design: no admin endpoint, and no HTTPS or HTTP/3
# behind the tunnel; and its goodbye on a restart.
OTHERS_BAD = ('{container=~"ipx-web|ipx-directory"} | json | __error__="" | level =~ "(?i)warn|error"'
# ipx-play's (#447): a line a request (method, path, status, duration_ms, token), and one a share.
PLAY_REQ = "play_http_request_duration_seconds"
OTHERS_BAD = ('{container=~"ipx-web|ipx-directory|ipx-play"} | json | __error__="" | level =~ "(?i)warn|error"'
' | msg !~ "admin endpoint disabled|automatic HTTPS is completely disabled|HTTP/[23] skipped.*|exiting; byeee.*"')
@@ -149,7 +151,7 @@ stat("Page and API errors", loki(f'sum(count_over_time({WEB_ALL} | status >= 500
thresholds=GOOD_BAD, desc="Answers of 500 and up from ipx-web, for the page or passed on from ipx: 502 is ipx not answering.")
stat("Warnings and errors", loki(f'sum(count_over_time({BAD} [$__range])) + sum(count_over_time({OTHERS_BAD} [$__range])) or vector(0)', instant=True), 20,
thresholds=[{"color": "green", "value": None}, {"color": "orange", "value": 1}, {"color": "red", "value": 50}],
desc="All three containers, in the time range.")
desc="All four containers, in the time range.")
y += 4
stat("Feed failures", loki(f'sum(count_over_time({EV} | ev="feed_error" [$__range])) or vector(0)', instant=True), 0,
thresholds=GOOD_BAD, desc="Failed feed checks in the time range.")
@@ -394,7 +396,33 @@ ts("Feed bytes fetched", [prom('rate(ipx_feed_bytes_total{job="ipx"}[$__rate_int
12, unit="Bps", desc="Feeds are read whole, so this is what scans and checks allocate; set it beside memory.")
y += 8
# ---- Traces: all three send them to Tempo (#213)
# ---- ipx-play: the page a shared episode opens, public at play.ipxreader.app (#447), from its
# /metrics on a port apart from the tunnel's (#458)
row("ipx-play")
stat("ipx-play", prom('max(up{job="ipx-play"})'), 0, thresholds=[{"color": "red", "value": None}, {"color": "green", "value": 1}],
desc="Prometheus reaching ipx-play's /metrics: 1 is up.")["fieldConfig"]["defaults"]["mappings"] = [
{"type": "value", "options": {"0": {"text": "down"}, "1": {"text": "up"}}}]
stat("Episodes shared", prom('sum(increase(play_shares_total{job="ipx-play"}[$__range])) or vector(0)', instant=True), 4,
desc="Links ipx servers asked for, the same episode again included.")
stat("Pages opened", prom(f'sum(increase({PLAY_REQ}_count{{job="ipx-play",route="/e/{{id}}",status="200"}}[$__range])) or vector(0)', instant=True), 8,
desc="Shared episodes someone opened, a link preview's fetch included.")
stat("Links not found", prom(f'sum(increase({PLAY_REQ}_count{{job="ipx-play",status="404"}}[$__range])) or vector(0)', instant=True), 12,
desc="A link mistyped, or someone trying addresses.")
stat("Server errors", prom(f'sum(increase({PLAY_REQ}_count{{job="ipx-play",status=~"5.."}}[$__range])) or vector(0)', instant=True), 16,
thresholds=GOOD_BAD, desc="Mostly its database not answering; its log has an error for each.")
stat("Requests refused", prom(f'sum(increase({PLAY_REQ}_count{{job="ipx-play",status=~"401|422"}}[$__range])) or vector(0)', instant=True), 20,
thresholds=GOOD_BAD, desc="A share without a valid token (401), or of an episode that looked private (422): ipx's own check should have kept it.")
y += 4
ts("Requests by route", [prom(f'sum by (route, status) (increase({PLAY_REQ}_count{{job="ipx-play"}}[$__interval]))', legend="{{status}} {{route}}")],
0, w=8, bars=True, stack=True, desc="An empty route is an address no route has.")
ts("Response time", [prom(f'histogram_quantile(0.5, sum by (le) (rate({PLAY_REQ}_bucket{{job="ipx-play"}}[$__rate_interval])))', legend="median"),
prom(f'histogram_quantile(0.95, sum by (le) (rate({PLAY_REQ}_bucket{{job="ipx-play"}}[$__rate_interval])))', ref="B", legend="95th percentile")],
8, w=8, unit="s")
ts("ipx-play memory", [prom('play_process_resident_bytes{job="ipx-play"}', legend="resident")], 16, w=8, unit="bytes",
desc="mimalloc, as the directory's: a rise that never comes down is a leak.")
y += 8
# ---- Traces: all four send them to Tempo (#213)
row("Traces")
for x, title, q in [(0, "Recent", TRACES + "}"),
(8, "Slow (over 2s)", TRACES + " && duration > 2s}"),
@@ -408,7 +436,7 @@ y += 10
# ---- Logs
row("Logs")
panel("logs", "ipx: warnings and errors", 12, 10, 0, [loki(BAD + TEXT)], options=LOG_OPTS)
panel("logs", "ipx-web and ipx-directory: warnings and errors", 12, 10, 12,
panel("logs", "ipx-web, ipx-directory and ipx-play: warnings and errors", 12, 10, 12,
[loki(OTHERS_BAD + ' | line_format "{{.container}} {{.level}}: {{.message}}{{.msg}}"')], options=LOG_OPTS)
y += 10
panel("logs", "ipx log", 24, 12, 0,

View File

@@ -6,6 +6,7 @@ The iOS app, `ios/`. Format: [Keep a Changelog](https://keepachangelog.com/en/1.
### Added
- Up Next plays on with the screen locked: the app is told what follows and starts it when an episode ends, without waiting for the page (#473).
- iPX on the iPhone: the page in an app, playing through the phone's own player, so an episode plays on with the screen locked and the lock screen, Control Center and a car's buttons drive it (#418).
- Player token (Settings, This device): an ipx API token, kept in the keychain, which the player, the badge and CarPlay send to `https://ipxapi.sdf1.net` instead of using the page's sign-in cookie, so playback does not stop when that cookie expires (#419).
- The icon shows All Subscriptions' unread count, as the page's badge does: set when the app comes forward, after an item is marked read, and by a refresh iOS runs now and then while the app is closed, so it can be hours behind (#421). Reading in the app and new items arriving while it is open set it at once, and while an episode plays it is checked every quarter of an hour.
@@ -19,3 +20,11 @@ The iOS app, `ios/`. Format: [Keep a Changelog](https://keepachangelog.com/en/1.
- A widget for the home screen and lock screen: the unread count, and the episode you were on with a button to resume or pause it (#428).
- The icon's count stays right with the app closed: ipx sends it to the phone when it changes, once its `[push]` is set up, in place of waiting for iOS's background refresh (#433).
- Presses are felt: a light tap on play, pause, flag and pull to refresh, a success on marking read, a warning with an error (#430).
### Changed
- The player, the badge and CarPlay talk to ipx in protobuf rather than JSON, which is smaller and quicker to read; they need an ipx with protobuf (#465), and a place saved offline by an older build is still sent (#469).
### Fixed
- A question the page asks before going ahead (deleting a file, sharing an address that carries your access) is shown with Cancel and OK, rather than answered Cancel at once with nothing shown (#453).

View File

@@ -74,6 +74,7 @@ on the `sdf1.net` zone) blocks every request to it except a bearer-token one for
| `Sources/CookieBridge.swift` | the web view's cookies into `HTTPCookieStorage.shared`, for the player |
| `Sources/Server.swift` | which server |
| `Sources/Intents.swift`, `Shared/PlayPauseIntent.swift` | Siri and Shortcuts (#427) |
| `Sources/API.swift`, `Sources/Wire` | ipx's API without the page, in protobuf (#469): `Wire` is generated from `crates/wire/proto` by `scripts/proto.sh`, and committed |
| `Sources/LastPlayed.swift` | the last episode and its place, so Resume works with the app closed |
| `Widgets/`, `Shared/Snapshot.swift`, `Sources/WidgetFeed.swift` | the widget (#428), and what the app writes for it |

View File

@@ -1,8 +1,13 @@
import Foundation
import SwiftProtobuf
/// Reading ipx without the page: the badge and CarPlay (#420), which has no web view. Signed in
/// as the player is, by the credentials or else the cookies the web view left (CookieBridge).
enum API {
/// What ipx answers and reads in protobuf rather than JSON (#465, #469). The messages are
/// `Sources/Wire`, generated from ipx's own `.proto` files by `scripts/proto.sh`.
static let protobuf = "application/x-protobuf"
private static let session: URLSession = {
let cfg = URLSessionConfiguration.default
cfg.httpCookieStorage = .shared
@@ -11,13 +16,25 @@ enum API {
}()
/// The body of a 200, or nil: not signed in, no server, no connection.
static func get(_ path: String) async -> Data? {
guard let url = Server.resolveForPlayer(path) else { return nil }
var req = URLRequest(url: url)
req.setValue("application/json", forHTTPHeaderField: "Accept")
Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) }
guard let (data, resp) = try? await session.data(for: req),
(resp as? HTTPURLResponse)?.statusCode == 200 else { return nil }
static func get(_ path: String, accept: String? = nil) async -> Data? {
guard let (data, resp) = await fetch(path, accept: accept), resp.statusCode == 200 else { return nil }
return data
}
/// A 200's body as message `M`, or nil. Nil too for an answer not in protobuf: a server from
/// before #465 answers JSON whatever it is asked, and JSON can read as a message of nothing.
static func get<M: SwiftProtobuf.Message>(_ type: M.Type, _ path: String) async -> M? {
guard let (data, resp) = await fetch(path, accept: protobuf), resp.statusCode == 200,
resp.value(forHTTPHeaderField: "Content-Type")?.hasPrefix(protobuf) == true else { return nil }
return try? M(serializedBytes: data)
}
private static func fetch(_ path: String, accept: String?) async -> (Data, HTTPURLResponse)? {
guard let url = Server.resolveForPlayer(path) else { return nil }
var req = URLRequest(url: url)
if let accept { req.setValue(accept, forHTTPHeaderField: "Accept") }
Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) }
guard let (data, resp) = try? await session.data(for: req), let http = resp as? HTTPURLResponse else { return nil }
return (data, http)
}
}

View File

@@ -11,22 +11,13 @@ import UserNotifications
enum Badge {
static let taskId = "net.sdf1.ipx.refresh"
private struct Row: Decodable {
let id: String
let group: String?
let unread: Int?
let hide_from_all: Bool?
}
/// web/src/feeds.ts `unreadInAll`: a feed counts unless it, or the OPML it came from, is
/// hidden from All Subscriptions. Nil when the body is not a feed list, so an error page
/// does not turn the badge to zero.
static func unread(inAll body: Data) -> Int? {
guard let rows = try? JSONDecoder().decode([Row].self, from: body) else { return nil }
let hidden = Set(rows.filter { $0.hide_from_all == true }.map(\.id))
/// hidden from All Subscriptions.
static func unread(inAll rows: [Ipx_FeedRow]) -> Int {
let hidden = Set(rows.filter(\.hideFromAll).map(\.id))
return rows.reduce(0) { n, f in
if f.hide_from_all == true || f.group.map(hidden.contains) == true { return n }
return n + max(0, f.unread ?? 0)
if f.hideFromAll || (f.hasGroup && hidden.contains(f.group)) { return n }
return n + max(0, Int(f.unread))
}
}
@@ -69,10 +60,11 @@ enum Badge {
return true
}
/// All Subscriptions' unread count from ipx, or nil when it cannot be had.
/// All Subscriptions' unread count from ipx, or nil when it cannot be had: an answer that is
/// not a feed list leaves the badge as it was rather than turning it to zero.
static func fetch() async -> Int? {
guard let data = await API.get("/api/feeds") else { return nil }
return unread(inAll: data)
guard let feeds = await API.get(Ipx_FeedRows.self, "/api/feeds") else { return nil }
return unread(inAll: feeds.items)
}
// MARK: - while the app is closed

View File

@@ -122,7 +122,7 @@ final class Bridge: NSObject, WKScriptMessageHandler {
if let r = m["rate"] as? Double { playback.setRate(Float(r)) }
if let v = m["volume"] as? Double { playback.setVolume(Float(v)) }
// What this build can do, so a newer page offers nothing it would ask for in vain.
send(["t": "host", "can": ["sleep", "route", "settings"]])
send(["t": "host", "can": ["sleep", "route", "settings", "next"]])
sendAppSettings()
// A page reloaded while the timer runs is told how long is left.
if let at = playback.sleepAt { send(["t": "sleep", "left": max(0, at.timeIntervalSinceNow)]) }
@@ -139,6 +139,21 @@ final class Bridge: NSObject, WKScriptMessageHandler {
feedTitle: m["feedTitle"] as? String ?? "",
artwork: m["artwork"] as? String,
duration: m["duration"] as? Int))
case "next":
// Without an episode it says nothing follows.
guard let path = m["url"] as? String, let url = Server.resolveForPlayer(path),
let enc = m["enc"] as? Int,
let feedId = m["feedId"] as? String, let guid = m["guid"] as? String else {
playback.next = nil
return
}
let at = m["position"] as? Double ?? 0
playback.next = (.init(
url: url, enc: enc, feedId: feedId, guid: guid,
title: m["title"] as? String ?? "",
feedTitle: m["feedTitle"] as? String ?? "",
artwork: m["artwork"] as? String,
duration: m["duration"] as? Int), at > 5 ? at : nil)
case "play": playback.play()
case "pause": playback.pause()
case "stop": playback.stop()

View File

@@ -7,14 +7,22 @@ import UIKit
// does. Now Playing is the system's, fed by Playback's now-playing info and remote commands.
/// An item as a car's list needs it: db.rs EntryRow, the fields used.
struct CarEpisode: Decodable {
struct Enclosure: Decodable {
struct CarEpisode {
struct Enclosure {
let id: Int
let url: String
let mime: String?
let deadair: Double?
/// Set once ipx has the file; `/media/{id}` answers 404 before that.
let path: String?
init(_ e: Ipx_EncRow) {
id = Int(e.id)
url = e.url
mime = e.hasMime ? e.mime : nil
deadair = e.hasDeadair ? Double(e.deadair) : nil
path = e.hasPath ? e.path : nil
}
}
let guid: String
@@ -25,6 +33,16 @@ struct CarEpisode: Decodable {
let position: Double
let enclosures: [Enclosure]
init(_ e: Ipx_EntryRow) {
guid = e.guid
feed_id = e.feedID
title = e.hasTitle ? e.title : nil
image = e.hasImage ? e.image : nil
duration = e.hasDuration ? Double(e.duration) : nil
position = Double(e.position)
enclosures = e.enclosures.map(Enclosure.init)
}
/// The file to play: the first downloaded one that is sound (items.ts isPlayable, less video,
/// which a car would play the sound of with nothing to say so). An item with none is not listed
/// (#443): a post's picture or a file still to come is nothing a car can play.
@@ -69,7 +87,7 @@ struct CarEpisode: Decodable {
}
/// A subscription, from `/api/feeds`.
struct CarFeed: Decodable {
struct CarFeed {
let id: String
let title: String?
let image: String?
@@ -80,10 +98,16 @@ struct CarFeed: Decodable {
let group: String?
var name: String { title ?? id }
}
private struct CarPage: Decodable {
let entries: [CarEpisode]
init(_ f: Ipx_FeedRow) {
id = f.id
title = f.hasTitle ? f.title : nil
image = f.hasImage ? f.image : nil
unread = Int(f.unread)
entries = Int(f.entries)
downloaded = Int(f.downloaded)
group = f.hasGroup ? f.group : nil
}
}
final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate {
@@ -143,19 +167,18 @@ final class CarScreen: NSObject, CPTabBarTemplateDelegate {
}
private func loadFeeds() async {
guard let data = await API.get("/api/feeds"),
let rows = try? JSONDecoder().decode([CarFeed].self, from: data) else { return }
guard let rows = await API.get(Ipx_FeedRows.self, "/api/feeds")?.items.map(CarFeed.init) else { return }
feeds = Dictionary(rows.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
}
private func episodes(in list: CPListTemplate, from path: String, empty: String, oneFeed: Bool = false) async {
guard let data = await API.get(path), let page = try? JSONDecoder().decode(CarPage.self, from: data) else {
guard let page = await API.get(Ipx_EntryPage.self, path) else {
unreachable(list)
return
}
let kept = Set(Offline.shared.store.paths)
let playing = Playback.shared.current
let rows: [CPListItem] = page.entries.compactMap { e in
let rows: [CPListItem] = page.entries.map(CarEpisode.init).compactMap { e in
let feed = feeds[e.feed_id]
guard let item = e.item(feedTitle: feed?.name ?? e.feed_id, feedImage: feed?.image, kept: kept) else {
return nil

View File

@@ -1,5 +1,6 @@
import Foundation
import Network
import SwiftProtobuf
/// Writes the player made with no connection, sent when there is one (#425): where you got to in
/// an episode, and that you finished it. In a browser the page's service worker holds these; the
@@ -10,7 +11,13 @@ import Network
enum Outbox {
struct Write: Codable, Equatable {
var path: String
var json: Data
var body: Data
/// The body is protobuf (#469). Nil in a write queued by a build before it, whose body is
/// JSON, and is sent as JSON.
var protobuf: Bool?
// `json` was the body's name when it could only be JSON; kept, so those writes still read.
enum CodingKeys: String, CodingKey { case path, body = "json", protobuf }
}
private static let key = "ipx.outbox"
@@ -24,11 +31,11 @@ enum Outbox {
/// A write that never arrived. Only the player's own two kinds are kept: anything else, such
/// as adding a feed, fails offline as it always has.
static func add(path: String, json: [String: Any]) {
static func add(path: String, _ body: any SwiftProtobuf.Message) {
guard path.hasSuffix("/position") || path.hasSuffix("/flags"),
let data = try? JSONSerialization.data(withJSONObject: json, options: [.sortedKeys]) else { return }
let data = try? body.serializedData() else { return }
var all = pending.filter { $0.path != path }
all.append(Write(path: path, json: data))
all.append(Write(path: path, body: data, protobuf: true))
pending = all
}
@@ -46,9 +53,9 @@ enum Outbox {
guard let url = Server.resolveForPlayer(w.path) else { return }
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue(w.protobuf == true ? API.protobuf : "application/json", forHTTPHeaderField: "Content-Type")
Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) }
req.httpBody = w.json
req.httpBody = w.body
guard (try? await session.data(for: req)) != nil else { return }
// Removed by what it is, not where it was: a newer write may have replaced it while
// this one was on its way.

View File

@@ -1,5 +1,6 @@
import AVFoundation
import MediaPlayer
import SwiftProtobuf
import UIKit
/// The phone's player: the one that plays on with the screen locked, and the one the lock screen
@@ -31,6 +32,9 @@ final class Playback: NSObject {
var onSlept: (() -> Void)?
/// Something the page did not choose is loaded now: the car's pick (#420).
var onChosen: (() -> Void)?
/// What plays when this one ends: the first in Up Next (#473), and where in it to start, as
/// the page last said. Here, not in the page, which is frozen while the screen is locked.
var next: (item: Item, startAt: Double?)?
private let session: URLSession = {
let cfg = URLSessionConfiguration.default
@@ -269,14 +273,15 @@ final class Playback: NSObject {
s.position = Double(secs)
if let d = duration { s.duration = d }
}
var body: [String: Any] = ["secs": secs]
if let d = duration { body["duration"] = Int(d.rounded()) }
var body = Ipx_Position()
body.secs = Int64(secs)
if let d = duration { body.duration = Int64(d.rounded()) }
// DeadAir's copy runs on a shorter clock; the server has to know which one this is.
if item.url.path.contains("/deadair") { body["deadair"] = item.enc }
if item.url.path.contains("/deadair") { body.deadair = Int64(item.enc) }
let path = entryPath(item, "position")
// Not arrived, kept for when the connection is back: offline, the ten-second retry would
// only fail again, and the place reached on the last pause would be lost.
Task { if await request("POST", path, body) == nil { Outbox.add(path: path, json: body) } }
Task { if await request("POST", path, body) == nil { Outbox.add(path: path, body) } }
}
// MARK: - as it plays
@@ -304,6 +309,12 @@ final class Playback: NSObject {
s.playing = false
}
markRead()
// Up Next goes on, and the page takes it up from nowPlaying as it does the car's pick.
if let n = next {
next = nil
playChosen(n.item, startAt: n.startAt)
return
}
onState?(false)
onEnded?()
updateNowPlaying()
@@ -314,7 +325,9 @@ final class Playback: NSObject {
markedRead = true
let path = entryPath(item, "flags")
Task {
if await request("POST", path, ["read": true]) == nil { Outbox.add(path: path, json: ["read": true]) }
var read = Ipx_Flags()
read.read = true
if await request("POST", path, read) == nil { Outbox.add(path: path, read) }
await Badge.refresh()
}
}
@@ -406,14 +419,14 @@ final class Playback: NSObject {
/// One call to ipx, signed in by the credentials or else the web view's cookies; its status, or nil if it never
/// arrived. A position that does not save is saved again ten seconds on.
@discardableResult
private func request(_ method: String, _ path: String, _ json: [String: Any]? = nil) async -> Int? {
private func request(_ method: String, _ path: String, _ body: (any SwiftProtobuf.Message)? = nil) async -> Int? {
guard let url = Server.resolveForPlayer(path) else { return nil }
var req = URLRequest(url: url)
req.httpMethod = method
Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) }
if let json {
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try? JSONSerialization.data(withJSONObject: json)
if let body {
req.setValue(API.protobuf, forHTTPHeaderField: "Content-Type")
req.httpBody = try? body.serializedData()
}
guard let (_, resp) = try? await session.data(for: req) else { return nil }
return (resp as? HTTPURLResponse)?.statusCode

View File

@@ -122,6 +122,20 @@ final class WebViewController: UIViewController, WKNavigationDelegate, WKUIDeleg
decisionHandler(.cancel)
}
/// The page's confirm(): without this WebKit answers Cancel at once and shows nothing, so
/// anything that asked first (deleting a file, sharing a Patreon address) could not go ahead
/// in the app (#453). The page uses no alert() or prompt().
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String,
initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping @MainActor (Bool) -> Void) {
// Another alert already up cannot have this one over it: answered as before, Cancel.
guard presentedViewController == nil else { return completionHandler(false) }
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(false) })
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(true) })
present(alert, animated: true)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error) {
let host = Server.url?.host ?? "the server"

View File

@@ -0,0 +1,941 @@
// DO NOT EDIT.
// swift-format-ignore-file
// swiftlint:disable all
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: directory.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
/// ipx-directory's API under /v1 (crates/directory/src/wire.rs), each message named after the Rust
/// struct it mirrors. A field added there goes here too; debug builds refuse an answer with a field
/// missing here. A message whose only field is `repeated items` is a JSON array.
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate nonisolated struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// GET /v1/me.
nonisolated struct Directory_Me: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var name: String = String()
/// "ro", "rw" or "rwa".
var access: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
nonisolated struct Directory_Listing: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var id: String = String()
var url: String = String()
var title: String {
get {_title ?? String()}
set {_title = newValue}
}
/// Returns true if `title` has been explicitly set.
var hasTitle: Bool {self._title != nil}
/// Clears the value of `title`. Subsequent reads from it will return its default value.
mutating func clearTitle() {self._title = nil}
var image: String {
get {_image ?? String()}
set {_image = newValue}
}
/// Returns true if `image` has been explicitly set.
var hasImage: Bool {self._image != nil}
/// Clears the value of `image`. Subsequent reads from it will return its default value.
mutating func clearImage() {self._image = nil}
var category: String {
get {_category ?? String()}
set {_category = newValue}
}
/// Returns true if `category` has been explicitly set.
var hasCategory: Bool {self._category != nil}
/// Clears the value of `category`. Subsequent reads from it will return its default value.
mutating func clearCategory() {self._category = nil}
var subcategory: String {
get {_subcategory ?? String()}
set {_subcategory = newValue}
}
/// Returns true if `subcategory` has been explicitly set.
var hasSubcategory: Bool {self._subcategory != nil}
/// Clears the value of `subcategory`. Subsequent reads from it will return its default value.
mutating func clearSubcategory() {self._subcategory = nil}
var podcast: Bool = false
var subscribers: Int64 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _title: String? = nil
fileprivate var _image: String? = nil
fileprivate var _category: String? = nil
fileprivate var _subcategory: String? = nil
}
/// GET /v1/feeds, GET /v1/popular.
nonisolated struct Directory_Listings: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var items: [Directory_Listing] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
nonisolated struct Directory_Item: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var guid: String = String()
var title: String {
get {_title ?? String()}
set {_title = newValue}
}
/// Returns true if `title` has been explicitly set.
var hasTitle: Bool {self._title != nil}
/// Clears the value of `title`. Subsequent reads from it will return its default value.
mutating func clearTitle() {self._title = nil}
var link: String {
get {_link ?? String()}
set {_link = newValue}
}
/// Returns true if `link` has been explicitly set.
var hasLink: Bool {self._link != nil}
/// Clears the value of `link`. Subsequent reads from it will return its default value.
mutating func clearLink() {self._link = nil}
var published: Int64 {
get {_published ?? 0}
set {_published = newValue}
}
/// Returns true if `published` has been explicitly set.
var hasPublished: Bool {self._published != nil}
/// Clears the value of `published`. Subsequent reads from it will return its default value.
mutating func clearPublished() {self._published = nil}
var duration: Int64 {
get {_duration ?? 0}
set {_duration = newValue}
}
/// Returns true if `duration` has been explicitly set.
var hasDuration: Bool {self._duration != nil}
/// Clears the value of `duration`. Subsequent reads from it will return its default value.
mutating func clearDuration() {self._duration = nil}
var description_p: String {
get {_description_p ?? String()}
set {_description_p = newValue}
}
/// Returns true if `description_p` has been explicitly set.
var hasDescription_p: Bool {self._description_p != nil}
/// Clears the value of `description_p`. Subsequent reads from it will return its default value.
mutating func clearDescription_p() {self._description_p = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _title: String? = nil
fileprivate var _link: String? = nil
fileprivate var _published: Int64? = nil
fileprivate var _duration: Int64? = nil
fileprivate var _description_p: String? = nil
}
/// GET /v1/feeds/{id}, POST /v1/feeds/{id}/refresh: a Listing's fields and these.
nonisolated struct Directory_FeedPage: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var id: String = String()
var url: String = String()
var title: String {
get {_title ?? String()}
set {_title = newValue}
}
/// Returns true if `title` has been explicitly set.
var hasTitle: Bool {self._title != nil}
/// Clears the value of `title`. Subsequent reads from it will return its default value.
mutating func clearTitle() {self._title = nil}
var image: String {
get {_image ?? String()}
set {_image = newValue}
}
/// Returns true if `image` has been explicitly set.
var hasImage: Bool {self._image != nil}
/// Clears the value of `image`. Subsequent reads from it will return its default value.
mutating func clearImage() {self._image = nil}
var category: String {
get {_category ?? String()}
set {_category = newValue}
}
/// Returns true if `category` has been explicitly set.
var hasCategory: Bool {self._category != nil}
/// Clears the value of `category`. Subsequent reads from it will return its default value.
mutating func clearCategory() {self._category = nil}
var subcategory: String {
get {_subcategory ?? String()}
set {_subcategory = newValue}
}
/// Returns true if `subcategory` has been explicitly set.
var hasSubcategory: Bool {self._subcategory != nil}
/// Clears the value of `subcategory`. Subsequent reads from it will return its default value.
mutating func clearSubcategory() {self._subcategory = nil}
var podcast: Bool = false
var subscribers: Int64 = 0
var description_p: String {
get {_description_p ?? String()}
set {_description_p = newValue}
}
/// Returns true if `description_p` has been explicitly set.
var hasDescription_p: Bool {self._description_p != nil}
/// Clears the value of `description_p`. Subsequent reads from it will return its default value.
mutating func clearDescription_p() {self._description_p = nil}
var failing: String {
get {_failing ?? String()}
set {_failing = newValue}
}
/// Returns true if `failing` has been explicitly set.
var hasFailing: Bool {self._failing != nil}
/// Clears the value of `failing`. Subsequent reads from it will return its default value.
mutating func clearFailing() {self._failing = nil}
var items: [Directory_Item] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _title: String? = nil
fileprivate var _image: String? = nil
fileprivate var _category: String? = nil
fileprivate var _subcategory: String? = nil
fileprivate var _description_p: String? = nil
fileprivate var _failing: String? = nil
}
nonisolated struct Directory_SnapshotEntry: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var url: String = String()
var subscribers: Int64 = 0
var category: String {
get {_category ?? String()}
set {_category = newValue}
}
/// Returns true if `category` has been explicitly set.
var hasCategory: Bool {self._category != nil}
/// Clears the value of `category`. Subsequent reads from it will return its default value.
mutating func clearCategory() {self._category = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _category: String? = nil
}
/// POST /v1/snapshot, the body.
nonisolated struct Directory_Snapshot: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var items: [Directory_SnapshotEntry] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// POST /v1/snapshot, the answer.
nonisolated struct Directory_SnapshotResult: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var accepted: UInt64 = 0
var refusedPrivate: UInt64 = 0
var refusedBlocked: UInt64 = 0
var refusedInvalid: UInt64 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
nonisolated struct Directory_Instance: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var name: String = String()
var feeds: Int64 = 0
var subscribers: Int64 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// GET /v1/instances.
nonisolated struct Directory_Instances: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var items: [Directory_Instance] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
nonisolated struct Directory_Blocked: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var id: String = String()
var url: String {
get {_url ?? String()}
set {_url = newValue}
}
/// Returns true if `url` has been explicitly set.
var hasURL: Bool {self._url != nil}
/// Clears the value of `url`. Subsequent reads from it will return its default value.
mutating func clearURL() {self._url = nil}
var title: String {
get {_title ?? String()}
set {_title = newValue}
}
/// Returns true if `title` has been explicitly set.
var hasTitle: Bool {self._title != nil}
/// Clears the value of `title`. Subsequent reads from it will return its default value.
mutating func clearTitle() {self._title = nil}
var at: Int64 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _url: String? = nil
fileprivate var _title: String? = nil
}
/// GET /v1/blocked.
nonisolated struct Directory_BlockedList: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var items: [Directory_Blocked] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate nonisolated let _protobuf_package = "directory"
nonisolated extension Directory_Me: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Me"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}name\0\u{1}access\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.name) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.access) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
}
if !self.access.isEmpty {
try visitor.visitSingularStringField(value: self.access, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_Me, rhs: Directory_Me) -> Bool {
if lhs.name != rhs.name {return false}
if lhs.access != rhs.access {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_Listing: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Listing"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}url\0\u{1}title\0\u{1}image\0\u{1}category\0\u{1}subcategory\0\u{1}podcast\0\u{1}subscribers\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.url) }()
case 3: try { try decoder.decodeSingularStringField(value: &self._title) }()
case 4: try { try decoder.decodeSingularStringField(value: &self._image) }()
case 5: try { try decoder.decodeSingularStringField(value: &self._category) }()
case 6: try { try decoder.decodeSingularStringField(value: &self._subcategory) }()
case 7: try { try decoder.decodeSingularBoolField(value: &self.podcast) }()
case 8: try { try decoder.decodeSingularInt64Field(value: &self.subscribers) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if !self.id.isEmpty {
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
}
if !self.url.isEmpty {
try visitor.visitSingularStringField(value: self.url, fieldNumber: 2)
}
try { if let v = self._title {
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
} }()
try { if let v = self._image {
try visitor.visitSingularStringField(value: v, fieldNumber: 4)
} }()
try { if let v = self._category {
try visitor.visitSingularStringField(value: v, fieldNumber: 5)
} }()
try { if let v = self._subcategory {
try visitor.visitSingularStringField(value: v, fieldNumber: 6)
} }()
if self.podcast != false {
try visitor.visitSingularBoolField(value: self.podcast, fieldNumber: 7)
}
if self.subscribers != 0 {
try visitor.visitSingularInt64Field(value: self.subscribers, fieldNumber: 8)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_Listing, rhs: Directory_Listing) -> Bool {
if lhs.id != rhs.id {return false}
if lhs.url != rhs.url {return false}
if lhs._title != rhs._title {return false}
if lhs._image != rhs._image {return false}
if lhs._category != rhs._category {return false}
if lhs._subcategory != rhs._subcategory {return false}
if lhs.podcast != rhs.podcast {return false}
if lhs.subscribers != rhs.subscribers {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_Listings: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Listings"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.items.isEmpty {
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_Listings, rhs: Directory_Listings) -> Bool {
if lhs.items != rhs.items {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_Item: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Item"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}guid\0\u{1}title\0\u{1}link\0\u{1}published\0\u{1}duration\0\u{1}description\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.guid) }()
case 2: try { try decoder.decodeSingularStringField(value: &self._title) }()
case 3: try { try decoder.decodeSingularStringField(value: &self._link) }()
case 4: try { try decoder.decodeSingularInt64Field(value: &self._published) }()
case 5: try { try decoder.decodeSingularInt64Field(value: &self._duration) }()
case 6: try { try decoder.decodeSingularStringField(value: &self._description_p) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if !self.guid.isEmpty {
try visitor.visitSingularStringField(value: self.guid, fieldNumber: 1)
}
try { if let v = self._title {
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
} }()
try { if let v = self._link {
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
} }()
try { if let v = self._published {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 4)
} }()
try { if let v = self._duration {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 5)
} }()
try { if let v = self._description_p {
try visitor.visitSingularStringField(value: v, fieldNumber: 6)
} }()
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_Item, rhs: Directory_Item) -> Bool {
if lhs.guid != rhs.guid {return false}
if lhs._title != rhs._title {return false}
if lhs._link != rhs._link {return false}
if lhs._published != rhs._published {return false}
if lhs._duration != rhs._duration {return false}
if lhs._description_p != rhs._description_p {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_FeedPage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".FeedPage"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}url\0\u{1}title\0\u{1}image\0\u{1}category\0\u{1}subcategory\0\u{1}podcast\0\u{1}subscribers\0\u{1}description\0\u{1}failing\0\u{1}items\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.url) }()
case 3: try { try decoder.decodeSingularStringField(value: &self._title) }()
case 4: try { try decoder.decodeSingularStringField(value: &self._image) }()
case 5: try { try decoder.decodeSingularStringField(value: &self._category) }()
case 6: try { try decoder.decodeSingularStringField(value: &self._subcategory) }()
case 7: try { try decoder.decodeSingularBoolField(value: &self.podcast) }()
case 8: try { try decoder.decodeSingularInt64Field(value: &self.subscribers) }()
case 9: try { try decoder.decodeSingularStringField(value: &self._description_p) }()
case 10: try { try decoder.decodeSingularStringField(value: &self._failing) }()
case 11: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if !self.id.isEmpty {
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
}
if !self.url.isEmpty {
try visitor.visitSingularStringField(value: self.url, fieldNumber: 2)
}
try { if let v = self._title {
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
} }()
try { if let v = self._image {
try visitor.visitSingularStringField(value: v, fieldNumber: 4)
} }()
try { if let v = self._category {
try visitor.visitSingularStringField(value: v, fieldNumber: 5)
} }()
try { if let v = self._subcategory {
try visitor.visitSingularStringField(value: v, fieldNumber: 6)
} }()
if self.podcast != false {
try visitor.visitSingularBoolField(value: self.podcast, fieldNumber: 7)
}
if self.subscribers != 0 {
try visitor.visitSingularInt64Field(value: self.subscribers, fieldNumber: 8)
}
try { if let v = self._description_p {
try visitor.visitSingularStringField(value: v, fieldNumber: 9)
} }()
try { if let v = self._failing {
try visitor.visitSingularStringField(value: v, fieldNumber: 10)
} }()
if !self.items.isEmpty {
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 11)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_FeedPage, rhs: Directory_FeedPage) -> Bool {
if lhs.id != rhs.id {return false}
if lhs.url != rhs.url {return false}
if lhs._title != rhs._title {return false}
if lhs._image != rhs._image {return false}
if lhs._category != rhs._category {return false}
if lhs._subcategory != rhs._subcategory {return false}
if lhs.podcast != rhs.podcast {return false}
if lhs.subscribers != rhs.subscribers {return false}
if lhs._description_p != rhs._description_p {return false}
if lhs._failing != rhs._failing {return false}
if lhs.items != rhs.items {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_SnapshotEntry: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SnapshotEntry"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}url\0\u{1}subscribers\0\u{1}category\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.url) }()
case 2: try { try decoder.decodeSingularInt64Field(value: &self.subscribers) }()
case 3: try { try decoder.decodeSingularStringField(value: &self._category) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if !self.url.isEmpty {
try visitor.visitSingularStringField(value: self.url, fieldNumber: 1)
}
if self.subscribers != 0 {
try visitor.visitSingularInt64Field(value: self.subscribers, fieldNumber: 2)
}
try { if let v = self._category {
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
} }()
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_SnapshotEntry, rhs: Directory_SnapshotEntry) -> Bool {
if lhs.url != rhs.url {return false}
if lhs.subscribers != rhs.subscribers {return false}
if lhs._category != rhs._category {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_Snapshot: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Snapshot"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.items.isEmpty {
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_Snapshot, rhs: Directory_Snapshot) -> Bool {
if lhs.items != rhs.items {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_SnapshotResult: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SnapshotResult"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}accepted\0\u{3}refused_private\0\u{3}refused_blocked\0\u{3}refused_invalid\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularUInt64Field(value: &self.accepted) }()
case 2: try { try decoder.decodeSingularUInt64Field(value: &self.refusedPrivate) }()
case 3: try { try decoder.decodeSingularUInt64Field(value: &self.refusedBlocked) }()
case 4: try { try decoder.decodeSingularUInt64Field(value: &self.refusedInvalid) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.accepted != 0 {
try visitor.visitSingularUInt64Field(value: self.accepted, fieldNumber: 1)
}
if self.refusedPrivate != 0 {
try visitor.visitSingularUInt64Field(value: self.refusedPrivate, fieldNumber: 2)
}
if self.refusedBlocked != 0 {
try visitor.visitSingularUInt64Field(value: self.refusedBlocked, fieldNumber: 3)
}
if self.refusedInvalid != 0 {
try visitor.visitSingularUInt64Field(value: self.refusedInvalid, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_SnapshotResult, rhs: Directory_SnapshotResult) -> Bool {
if lhs.accepted != rhs.accepted {return false}
if lhs.refusedPrivate != rhs.refusedPrivate {return false}
if lhs.refusedBlocked != rhs.refusedBlocked {return false}
if lhs.refusedInvalid != rhs.refusedInvalid {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_Instance: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Instance"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}name\0\u{1}feeds\0\u{1}subscribers\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.name) }()
case 2: try { try decoder.decodeSingularInt64Field(value: &self.feeds) }()
case 3: try { try decoder.decodeSingularInt64Field(value: &self.subscribers) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
}
if self.feeds != 0 {
try visitor.visitSingularInt64Field(value: self.feeds, fieldNumber: 2)
}
if self.subscribers != 0 {
try visitor.visitSingularInt64Field(value: self.subscribers, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_Instance, rhs: Directory_Instance) -> Bool {
if lhs.name != rhs.name {return false}
if lhs.feeds != rhs.feeds {return false}
if lhs.subscribers != rhs.subscribers {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_Instances: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Instances"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.items.isEmpty {
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_Instances, rhs: Directory_Instances) -> Bool {
if lhs.items != rhs.items {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_Blocked: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Blocked"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}url\0\u{1}title\0\u{1}at\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
case 2: try { try decoder.decodeSingularStringField(value: &self._url) }()
case 3: try { try decoder.decodeSingularStringField(value: &self._title) }()
case 4: try { try decoder.decodeSingularInt64Field(value: &self.at) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if !self.id.isEmpty {
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
}
try { if let v = self._url {
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
} }()
try { if let v = self._title {
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
} }()
if self.at != 0 {
try visitor.visitSingularInt64Field(value: self.at, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_Blocked, rhs: Directory_Blocked) -> Bool {
if lhs.id != rhs.id {return false}
if lhs._url != rhs._url {return false}
if lhs._title != rhs._title {return false}
if lhs.at != rhs.at {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Directory_BlockedList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".BlockedList"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0")
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.items.isEmpty {
try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Directory_BlockedList, rhs: Directory_BlockedList) -> Bool {
if lhs.items != rhs.items {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -13,6 +13,12 @@ settings:
SWIFT_VERSION: "5.9"
TARGETED_DEVICE_FAMILY: "1,2"
CODE_SIGN_STYLE: Automatic
packages:
# The app's half of ipx's protobuf (#469). The same version as the protoc-gen-swift that made
# Sources/Wire (scripts/proto.sh), whose code refuses another.
SwiftProtobuf:
url: https://github.com/apple/swift-protobuf
exactVersion: 1.41.0
targets:
iPX:
type: application
@@ -23,12 +29,13 @@ targets:
- Resources/Assets.xcassets
dependencies:
- target: iPXWidgets
- package: SwiftProtobuf
info:
path: Resources/Info.plist
properties:
CFBundleDisplayName: iPX
CFBundleShortVersionString: $(MARKETING_VERSION)
CFBundleVersion: "14"
CFBundleVersion: "15"
# Playing on with the screen locked. A plist key, not a signed entitlement.
UIBackgroundModes: [audio, fetch, remote-notification]
# The unread badge's refresh while the app is closed (#421).
@@ -107,7 +114,7 @@ targets:
properties:
CFBundleDisplayName: iPX
CFBundleShortVersionString: $(MARKETING_VERSION)
CFBundleVersion: "14"
CFBundleVersion: "15"
NSExtension:
NSExtensionPointIdentifier: com.apple.widgetkit-extension
entitlements:

12
ios/scripts/proto.sh Executable file
View File

@@ -0,0 +1,12 @@
#!/bin/sh
# The app's protobuf messages (#469), generated from the .proto files ipx serves them by
# (crates/wire/proto) into Sources/Wire, which is committed: XcodeGen and Xcode build it as it is,
# with no protoc in the build. Run again after a change to those files. Needs protoc and
# protoc-gen-swift, the generator at the version of the SwiftProtobuf package in project.yml, which
# refuses code from another: on a Mac `brew install protobuf swift-protobuf`, here /src/install.sh.
set -eu
cd "$(dirname "$0")/.."
proto=../crates/wire/proto
rm -f Sources/Wire/*.pb.swift
protoc -I "$proto" --swift_out=Sources/Wire --swift_opt=Visibility=Internal "$proto/ipx.proto" "$proto/directory.proto"
protoc-gen-swift --version

View File

@@ -12,7 +12,7 @@ set -eu
MEM=6g # the builder's memory cap (Tower has no swap to spill into)
CPUS=0-5 # six of twelve threads; cargo inside sees six and runs six jobs
NEED_KB=$((9 * 1024 * 1024)) # the cap plus 3 GB for everything else
NEED_KB=$((6 * 1024 * 1024)) # the cap; the cgroup kills a build that outgrows it
MAX_LOAD=12
BUILDER=ipx-capped

View File

@@ -66,7 +66,7 @@ function makeContext(html: string, script: string, { media = false } = {}) {
localStorage: { getItem: () => null, setItem(){}, removeItem(){} },
navigator: { clipboard: undefined, sendBeacon(){}, mediaSession: undefined },
fetch: (url: unknown) => Promise.resolve({
ok: true, status: 200, text: () => Promise.resolve(''),
ok: true, status: 200, headers: new Headers({ 'Content-Type': 'application/json' }), text: () => Promise.resolve(''),
json: () => Promise.resolve(
String(url).includes('/api/settings')
? { schedule: 'every 60m', every_mins: 60, download_dir: '/tmp', max_total_gb: 0, max_age_days: 0 }
@@ -75,7 +75,7 @@ function makeContext(html: string, script: string, { media = false } = {}) {
: /\/api\/(popular|directory)/.test(String(url))
? [{ id: 'f', title: 'A Feed', image: null, subscribers: 2, subscribed: true },
{ id: 'g', title: null, image: null, subscribers: 1, subscribed: false }]
: /entries/.test(String(url)) ? { total: 0, entries: [] } : []),
: /entries|\/api\/queue/.test(String(url)) ? { total: 0, entries: [] } : []),
}),
EventSource: class { close() {} },
MediaMetadata: class {},

View File

@@ -118,8 +118,9 @@ ok(audio.calls.includes('src:/media/99'), 'a video did not play on the element')
// Kept on the phone (#425): no service worker in a WebView, so the button is the app's to answer.
const enc42 = { id: 42, deadair: 0, mime: 'audio/mpeg' };
ok(String(vm.runInContext('keepBtn(X)', Object.assign(ctx, { X: enc42 }))).includes('data-a="offline"'),
'no Keep button in the app, which has no service worker to keep a file');
// ⬇ ends on the phone in the app, whatever the width (#457).
ok(vm.runInContext('toDevice(X)', Object.assign(ctx, { X: enc42 })) === true,
'in the app, a file\'s download button did not bring it to the phone, which has no service worker to keep it');
since();
await vm.runInContext('toggleKept(X, "Episode One")', ctx);
ok(last('keep')?.url === '/media/42', 'Keep did not ask the app for the file');
@@ -229,6 +230,21 @@ ctx.window.ipxNative.on({ t: 'nowPlaying', feedId: 'f', guid: 'g2', enc: 7, titl
playing: false, cur: 130 });
ok(audio.paused === true && audio.currentTime === 130, 'told again on coming forward, the bar did not follow');
// Up Next (#473): the app is told what follows, to play it with the screen locked, and taking it
// up from nowPlaying takes it out of Up Next.
const queued = { feed_id: 'f', guid: 'n1', title: 'Next One', position: 0, duration: 60, image: null,
enclosures: [{ id: 9, mime: 'audio/mpeg', path: '/n.mp3', url: 'http://x/n.mp3' }] };
since();
vm.runInContext(`upNext=[${JSON.stringify(queued)}]; hostNext()`, ctx);
ok(!last('next'), 'an app that never said it can was told what follows');
ctx.window.ipxNative.on({ t: 'host', can: ['next'] });
ok(last('next')?.guid === 'n1' && last('next')?.enc === 9 && last('next')?.url === '/media/9', 'the app was not told what plays next');
ctx.window.ipxNative.on({ t: 'nowPlaying', feedId: 'f', guid: 'n1', enc: 9, title: 'Next One', feedTitle: 'A Feed',
playing: true, cur: 0, dur: 60 });
ok(vm.runInContext('player.guid', ctx) === 'n1', 'the bar did not take up the next one');
ok(vm.runInContext('upNext.length', ctx) === 0, 'the one under way is still in Up Next');
ok(!!last('next') && !last('next')?.guid, 'the app was not told nothing follows');
if (failed) { console.error(`\n${failed} failed`); process.exit(1); }
console.log('OK: native-bridge: the host takes playback, keeping, the sleep timer and haptics, and the page follows it');
console.log('OK: native-bridge: the host takes playback, keeping, the sleep timer, haptics and Up Next, and the page follows it');
process.exit(0);

View File

@@ -28,6 +28,28 @@ test('esc makes text safe to put in markup and attributes', () => {
assert.equal(run('esc(undefined)'), '');
});
test('names sort as a shelf files them, a leading The, A or An aside (#481)', () => {
const names = ['The Rest Is Science', 'science weekly', 'Theory of Everything', 'Episode 10', 'Episode 2', 'the Daily', 'Radiolab',
'A Question of Science', 'An Hour', 'Anchor', 'Abba'];
// As JSON: an array from the page's VM is of another realm, which deepEqual tells apart.
assert.deepEqual(JSON.parse(run(`JSON.stringify(${JSON.stringify(names)}.sort(nameOrder))`)),
['Abba', 'Anchor', 'the Daily', 'Episode 2', 'Episode 10', 'An Hour', 'A Question of Science', 'Radiolab',
'The Rest Is Science', 'science weekly', 'Theory of Everything']);
});
test('a podcast gets its seasons only when most of it is in two or more (#482)', () => {
const shown = (list: object) => run(`seasonsShown(${JSON.stringify(list)})`);
const s = (season: number | null, episodes: number) => ({ season, episodes, unread: 0 });
assert.equal(shown([s(6, 25), s(5, 40), s(1, 30)]), true, 'Oxide and Friends');
assert.equal(shown([s(7, 40), s(1, 30), s(null, 3)]), true, 'a few trailers aside');
assert.equal(shown([s(232, 1), s(225, 1), s(null, 364)]), false, 'two numbered of 366');
assert.equal(shown([s(2023, 150), s(12026, 44), s(null, 573)]), false, 'years on a quarter of them');
assert.equal(shown([s(1, 40)]), false, 'one season is no choice');
assert.equal(shown([{ episodes: 3, unread: 0 }, s(2, 2), s(1, 2)]), true, 'none sent as absent, as protobuf does');
assert.equal(run('seasonName(null)'), 'Other episodes');
assert.equal(run('seasonName(3)'), 'Season 3');
});
test('webUrl keeps only web addresses from a feed', () => {
assert.equal(run(`webUrl('https://example.com/a')`), 'https://example.com/a');
assert.equal(run(`webUrl('HTTP://example.com/')`), 'HTTP://example.com/');
@@ -239,7 +261,7 @@ test('Signals are everyone\'s on the server\'s key, and yours on your own once a
});
test('a tap is its trace\'s root span, reported with its ids once it has an answer (#376)', () => {
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
run(`newTrace('pointerdown'); traceAt = Date.now()`);
const [, trace, parent] = run('traceparent()').split('-');
assert.equal(parent, run('rootId'), 'requests hang from the tap');
@@ -253,7 +275,7 @@ test('a tap is its trace\'s root span, reported with its ids once it has an answ
});
test('a request begun long after a tap\'s last answer does not stretch the tap (#379)', async () => {
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
run(`newTrace('pointerdown'); traceAt = Date.now()`);
await run(`api('/api/a')`);
const answered = run('answeredAt');
@@ -266,7 +288,7 @@ test('a request begun long after a tap\'s last answer does not stretch the tap (
});
test('a tap ended over a minute after its last request reports once, without recursing (#378)', () => {
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
run(`newTrace('pointerdown'); answeredAt = rootAt + 100; traceAt = Date.now() - 120_000`);
run('endTap()');
assert.equal(run(`sent.filter(([u, o]) => JSON.parse(o.body).ev === 'tap').length`), 1);
@@ -352,3 +374,50 @@ test('a Patreon feed or file carries your access, a post page does not (#455)',
assert.equal(carries('https://www.patreon.com/glasscannon/posts/music-from-room-174604106'), false);
assert.equal(carries('https://example.com/ep.mp3'), false);
});
test('a file\'s box says where it is: the publisher, on its way, iPX, this device (#457)', () => {
const where = (x: object) => run(`whereText(${JSON.stringify({ id: 7, deadair: 0, path: null, state: 'held', ...x })})`) as string;
assert.equal(where({}), 'Publisher only');
assert.equal(where({ state: 'pending' }), 'Queued for iPX');
assert.equal(where({ state: 'error' }), 'iPX could not download it');
run(`want(7, 'Ep')`);
assert.equal(where({ state: 'pending' }), 'Downloading to iPX, then this device');
run('unwant(7)');
assert.equal(where({ path: '/d/ep.mp3', state: 'done' }), 'On iPX');
run(`kept.add('/media/7')`);
assert.equal(where({ path: '/d/ep.mp3', state: 'done' }), 'On iPX and this device');
// iPX let its copy go; the one here stays.
assert.equal(where({ state: 'reaped' }), 'On this device');
run('kept.clear()');
});
test('wireDecode reads protobuf into what the JSON would have been (#470)', () => {
// A browser has TextDecoder; the stub's sandbox does not, and the page makes one only to decode.
ctx.TextDecoder = TextDecoder;
const dec = (type: string, bytes: number[]) => run(`wireDecode(${JSON.stringify(type)}, new Uint8Array(${JSON.stringify(bytes)}))`);
assert.deepEqual({ ...dec('ipx.Marked', [0x08, 0xac, 0x02]) }, { marked: 300 }, 'a varint over a byte');
assert.equal(dec('ipx.SignalId', [0x08, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1]).id, -1, 'a negative int64');
assert.equal(dec('ipx.Marked', []).marked, 0, 'a field at its default is not sent');
// A field this page does not know, as from a newer server, is passed over.
assert.equal(dec('ipx.Marked', [0x4a, 0x01, 0x78, 0x08, 0x05]).marked, 5);
const rows = dec('ipx.FeedRows', [0x0a, 0x03, 0x0a, 0x01, 0x61]);
assert.ok(Array.isArray(rows) && rows.length === 1, 'a list message is its array');
assert.equal(rows[0].id, 'a');
assert.equal(rows[0].title, null, 'an optional not sent is null, as JSON had it');
assert.equal(rows[0].failing, null, 'so is a message');
assert.deepEqual([...rows[0].keywords], []);
assert.equal(rows[0].pinned, false);
assert.equal(dec('ipx.Settings', [0x31, 0, 0, 0, 0, 0, 0, 0xf8, 0x3f]).max_total_gb, 1.5, 'a double');
assert.equal(run(`wireType('application/x-protobuf; messageType=ipx.FeedRows')`), 'ipx.FeedRows');
assert.equal(run(`wireType('application/json')`), undefined);
});
test('nextUp is the first in Up Next that can play, passing over the one playing', () => {
const ep = (guid: string, path: string | null) =>
({ feed_id: 'f', guid, enclosures: [{ id: 1, mime: 'audio/mpeg', path, url: 'http://x/a.mp3' }] });
const list = JSON.stringify([ep('a', '/a.mp3'), ep('b', null), ep('c', '/c.mp3')]);
assert.equal(run(`nextUp(${list}, null)?.guid`), 'a');
assert.equal(run(`nextUp(${list}, 'f\\na')?.guid`), 'c', 'b is not downloaded yet');
assert.equal(run(`nextUp(${list}, 'f\\nc')?.guid`), 'a');
assert.equal(run(`nextUp([], null)`), undefined);
});

View File

@@ -10,6 +10,8 @@ import type { Locator, Page, Request } from '@playwright/test';
declare global {
interface Window { started: string[]; done: boolean; shared: ShareData[] }
}
/// Answers the page's own question (#462): yes, or Cancel.
const answer = (page: Page, yes = true) => page.locator(`dialog.ask [value="${yes ? 'y' : ''}"]`).click();
/// What a failed `ipx` command said, from execFileSync's error.
const said = (e: unknown) => { const x = e as { stderr?: unknown, stdout?: unknown }; return String(x.stderr || x.stdout); };
@@ -54,9 +56,9 @@ test.beforeEach(async ({ page }) => {
test('the page loads and lists the configured feeds', async ({ page }) => {
// Regression: a ReferenceError in the script left the shell rendered and the sidebar
// empty, with every handler below the error dead. Server-side checks all passed.
// Four top-level feeds in the fixture config; the OPML's children are inside a closed folder.
// The Signals folder is above them, and no feed.
await expect(page.locator('.feed:not(.sigs)')).toHaveCount(5, { timeout: 15_000 });
// Six top-level feeds in the fixture config, the season one's (#482) among them; the OPML's
// children are inside a closed folder. The Signals folder is above them, and no feed.
await expect(page.locator('.feed:not(.sigs):not(.plists)')).toHaveCount(6, { timeout: 15_000 });
await expect(page.locator('.feed', { hasText: 'Test Show' })).toBeVisible();
const errors: string[] = [];
page.on('pageerror', e => errors.push(e.message));
@@ -297,7 +299,7 @@ test('the three panes are there and the item text lands in the bottom one', asyn
const downloaded = page.locator('.ep', { has: page.locator('.kind.here') }).first();
await downloaded.click();
await expect(page.locator('#files [data-a="play"]')).toBeVisible();
await expect(page.locator('#files .encbox [title="Save to this computer"]')).toBeVisible();
await expect(page.locator('#files .encbox [title="Save a copy to this computer"]')).toBeVisible();
// Selecting another item replaces the pane rather than stacking.
await page.locator('.ep', { hasText: 'First Episode' }).click();
@@ -349,7 +351,7 @@ test('a downloaded file that is not audio gets no player', async ({ page }) => {
// What it is and that it is here: one icon, green, with the words in its tooltip.
await expect(page.locator('#files .encbox .kind.here')).toHaveAttribute('title', 'image, downloaded');
// Still offered as a file, just not as an episode: viewable and keepable.
await expect(page.locator('#files [title="Save to this computer"]')).toBeVisible();
await expect(page.locator('#files [title="Save a copy to this computer"]')).toBeVisible();
const view = page.locator('#files a[title="View in a new tab"]');
await expect(view).toHaveAttribute('target', '_blank');
await expect(view).toHaveAttribute('rel', /noopener/);
@@ -423,6 +425,125 @@ test('Currently Listening, its own place below the Directory, resumes an episode
await expect(row.locator('.eq')).toBeHidden();
});
test('Up Next lines episodes up, moves them, and plays the next when one ends (#473)', async ({ page }) => {
await page.evaluate(() => saveUpNext([]));
await page.locator('.feed', { hasText: 'Test Show' }).click();
for (const name of ['First Episode', 'Second Episode']) {
const ep = page.locator('#eps .ep', { hasText: name });
await ep.hover();
await ep.locator('[data-a=queue]').click();
await expect(ep.locator('[data-a=queue]')).toHaveAttribute('aria-pressed', 'true');
}
const place = page.locator('#feedlist .place', { hasText: 'Up Next' });
await expect(place.locator('.badge')).toHaveText('2');
await place.click();
const rows = page.locator('#listening .childrow .txt b');
await expect(rows).toHaveText(['First Episode', 'Second Episode']);
// Moved by its handle's arrow keys, and kept so on the server.
await page.locator('#listening .childrow', { hasText: 'Second Episode' }).locator('.grip').press('ArrowUp');
await expect(rows).toHaveText(['Second Episode', 'First Episode']);
await expect.poll(() => page.evaluate(async () => (await api('/api/queue')).entries.map((e: Entry) => e.guid)))
.toEqual(['ui-2', 'ui-1']);
// Playing one takes it out; the end of it plays the next.
await page.locator('#listening .childrow', { hasText: 'Second Episode' }).click();
await expect(page.locator('#ptitle')).toHaveText('Second Episode');
await expect(rows).toHaveText(['First Episode']);
await expect(page.locator('#pnext')).toBeVisible();
// The fixture files are not real audio, so the end is said rather than played to.
await page.evaluate(() => audio.dispatchEvent(new Event('ended')));
await expect(page.locator('#ptitle')).toHaveText('First Episode', { timeout: 20_000 });
await expect(page.locator('#listening')).toContainText('Nothing lined up');
await expect(page.locator('#pnext')).toBeHidden();
await page.locator('#pclose').click();
await page.evaluate(() => api('/api/entries/test-show/ui-1/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) }));
await page.evaluate(() => api('/api/entries/test-show/ui-2/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) }));
});
test('the Podcasts shelf shows the feeds with episodes, as their artwork, and opens one (#474)', async ({ page }) => {
await page.locator('#feedlist .place', { hasText: 'Podcasts' }).click();
const shows = page.locator('#content .shelf .show');
await expect(shows.filter({ hasText: 'Test Show' })).toBeVisible();
// A blog of pictures has files, and no episodes.
await expect(shows.filter({ hasText: 'Picture Blog' })).toHaveCount(0);
await page.locator('#epSearch').fill('multi');
await expect(shows).toHaveText([/Multi Show/]);
await page.locator('#epSearch').fill('');
await shows.filter({ hasText: 'Test Show' }).click();
await expect(page.locator('#eps .ep', { hasText: 'First Episode' })).toBeVisible();
});
test('Now Playing opens from the player bar with the artwork, show notes and Up Next (#475)', async ({ page }) => {
await page.evaluate(() => saveUpNext([]));
await page.locator('.feed', { hasText: 'Test Show' }).click();
const first = page.locator('#eps .ep', { hasText: 'First Episode' });
await first.hover();
await first.locator('[data-a=queue]').click();
const second = page.locator('#eps .ep', { hasText: 'Second Episode' });
await second.hover();
await second.locator('[data-a=play]').click();
await expect(page.locator('#ptitle')).toHaveText('Second Episode');
const sheet = page.locator('#nowsheet');
await page.locator('#pnow').click();
await expect(sheet).toBeVisible();
await expect(page.locator('#pnow')).toHaveAttribute('aria-expanded', 'true');
await expect(sheet.locator('h2')).toHaveText('Second Episode');
await expect(sheet.locator('.dbody')).toContainText('Notes for the second.');
await expect(sheet.locator('#nowqueue .childrow')).toHaveText([/First Episode/]);
await page.keyboard.press('Escape');
await expect(sheet).toBeHidden();
// From the keyboard too, and the podcast's name opens its feed.
await page.locator('#pnow').focus();
await page.keyboard.press('Enter');
await sheet.locator('.nowshow').click();
await expect(sheet).toBeHidden();
await expect(page.locator('#eps .ep', { hasText: 'Second Episode' })).toBeVisible();
await page.locator('#pclose').click();
await page.evaluate(() => saveUpNext([]));
await page.evaluate(() => api('/api/entries/test-show/ui-2/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) }));
});
test('a smart playlist puts its first podcasts ahead and plays on through itself (#476)', async ({ page }) => {
await page.evaluate(() => saveUpNext([]));
await page.locator('#feedlist .feed', { hasText: 'Playlists' }).click();
await page.locator('#content .acts [data-a="new"]').click();
await page.locator('#plname').fill('Commute');
await page.locator('[data-in="test-show"]').check();
await page.locator('[data-in="multi-show"]').check();
await page.locator('[data-first="multi-show"]').check();
await page.locator('#plunplayed').uncheck();
await page.locator('#plsave').click();
const rows = page.locator('#listening .childrow .txt b');
await expect(rows).toHaveText(['Two Files', 'Second Episode', 'First Episode']);
await expect(page.locator('#feedlist .feed.child', { hasText: 'Commute' }).locator('.badge')).toHaveText('3');
// Both of Test Show's files here, whatever ran before: only a downloaded one plays next.
const missing = async () => (await page.evaluate(() => api('/api/feeds/test-show/entries')) as ListPage).entries
.flatMap(e => e.enclosures).filter(x => !x.path).map(x => x.id);
for (const id of await missing()) await page.evaluate(id => api(`/api/enclosures/${id}/download`, { method: 'POST' }), id);
await expect.poll(missing, { timeout: 20_000 }).toEqual([]);
await page.locator('#feedlist .feed.child', { hasText: 'Commute' }).click();
// Played from the playlist, the end of one plays the next in it.
await page.locator('#listening .childrow', { hasText: 'Second Episode' }).click();
await expect(page.locator('#ptitle')).toHaveText('Second Episode');
await expect(page.locator('#pnext')).toBeVisible();
await page.evaluate(() => audio.dispatchEvent(new Event('ended')));
await expect(page.locator('#ptitle')).toHaveText('First Episode');
await page.locator('#pclose').click();
await page.locator('#content .acts [data-a="rm"]').click();
await answer(page);
await expect(page.locator('#feedlist .feed.child', { hasText: 'Commute' })).toHaveCount(0);
for (const g of ['ui-1', 'ui-2'])
await page.evaluate(g => api(`/api/entries/test-show/${g}/position`, { method: 'POST', body: JSON.stringify({ secs: 0 }) }), g);
});
test('a player nobody has played since it last saved does not save again', async ({ page }) => {
// A tab left paused at 41:15 saved that as it reloaded, over the 32:48 another had reached,
// and the episode dropped out of Currently Listening. The fixture audio does not decode, so
@@ -527,7 +648,7 @@ test('an OPML subscription is a collapsible folder', async ({ page }) => {
const chev = page.locator('.feed.group .chev');
await expect(chev).toBeVisible({ timeout: 20_000 });
// The Signals folder is a folder too (#255).
await expect(page.locator('.feed:not(.group):not(.sigs) .chev')).toHaveCount(0);
await expect(page.locator('.feed:not(.group):not(.sigs):not(.plists) .chev')).toHaveCount(0);
await expect(chev).toHaveAttribute('aria-expanded', 'false');
// Closed by default: the children are not listed until the folder is opened.
@@ -611,6 +732,107 @@ test('a show inside an OPML can be kept, and only it', async ({ page }) => {
await expect(page.locator('#content [data-a="keep"]')).toHaveCount(0);
});
test('feeds in every shape are read, and what is no feed is refused saying why (#463)', async ({ page }) => {
const F = 'http://127.0.0.1:8792';
const add = (url: string) => page.request.post('/api/feeds', { data: { url } });
for (const [file, said] of [
['said.txt', 'the site sent "Unable to establish a DB connection" instead of a feed'],
['long.txt', '…" instead of a feed'],
['empty.xml', 'the site sent an empty reply'],
['garbled.xml', 'not RSS ('],
] as const) {
const r = await add(`${F}/${file}`);
expect(r.status(), file).toBe(400);
expect(await r.text(), file).toContain(said);
}
const ids: Record<string, string> = {};
for (const file of ['atom.xml', 'amp.xml', 'wp.json']) {
const r = await add(`${F}/${file}`);
expect(r.status(), file).toBe(200);
ids[file] = (await r.json()).id;
}
const entries = async (file: string) => ((await (await page.request.get(
`/api/feeds/${encodeURIComponent(ids[file]!)}/entries?limit=50`)).json()) as ListPage).entries;
const byTitle = async (file: string) => Object.fromEntries((await entries(file)).map(e => [e.title, e]));
const feed = async (file: string) => (await (await page.request.get('/api/feeds')).json() as Feed[])
.find(f => f.id === ids[file])!;
// Atom: its title's entity decoded, the player's repeat of one file dropped, Markdown made HTML.
await expect.poll(async () => Object.keys(await byTitle('atom.xml')).sort(), { timeout: 20_000 })
.toEqual(['Markdown entry', 'Q&A in Atom']);
const atom = await byTitle('atom.xml');
expect(atom['Q&A in Atom']!.enclosures).toHaveLength(1);
expect(atom['Q&A in Atom']!.description).toContain('<b>notes</b>');
expect(atom['Markdown entry']!.description).toContain('<strong>bold</strong>');
expect((await feed('atom.xml')).title).toBe('Atom’s Show');
// A bare "&" read after all, with the iTunes and Media RSS fields.
await expect.poll(async () => Object.keys(await byTitle('amp.xml')).length, { timeout: 20_000 }).toBe(3);
const amp = await byTitle('amp.xml');
expect(amp['Tom & Jerry']!.duration).toBe(3723);
expect(amp['Tom & Jerry']!.image).toBe(`${F}/art2.jpg`);
expect(amp['Tom & Jerry']!.description).toMatch(/^<p><em>A subtitle not in the body<\/em><\/p>/);
expect(amp['Cut body']!.description).toBe('The whole description');
expect(amp['Cut body']!.image).toBe(`${F}/pic.png`);
expect(amp['Picture only']!.image).toBe(`${F}/amp-pic.png`);
expect((await feed('amp.xml')).feed_category).toBe('Games');
// WordPress.com's posts, as its API sends them, read as a feed.
await expect.poll(async () => Object.keys(await byTitle('wp.json')), { timeout: 20_000 })
.toEqual(['WordPress “post”']);
for (const id of Object.values(ids)) await page.request.delete(`/api/feeds/${encodeURIComponent(id)}`);
});
test('a feed that starts failing says why, and after a day in words with something to do (#463)', async ({ page }) => {
const F = 'http://127.0.0.1:8792';
const flip = (to: string) => page.request.get(`${F}/flip?to=${to}`);
await flip('ok');
const id = (await (await page.request.post('/api/feeds', { data: { url: `${F}/flip.xml` } })).json()).id as string;
const feed = async () => (await (await page.request.get('/api/feeds')).json() as Feed[]).find(f => f.id === id)!;
await expect.poll(async () => (await feed()).entries, { timeout: 20_000 }).toBe(1);
const db = path.join(setup.root, 'data', 'state.db');
try {
for (const [to, error, reason] of [
['404', /HTTP 404/, 'took this feed down'],
['403', /HTTP 403/, 'refuses'],
['402', /HTTP 402/, 'paid plan'],
['500', /HTTP 500/, null],
['text', /the site sent/, 'sent a message'],
['page', /got a web page, not a feed; it links .*moved\.xml/, 'The feed moved'],
['garbled', /not RSS/, null],
['loop', /redirect/i, null],
['drop', /./, null],
] as const) {
await flip(to);
await page.request.post('/api/fetch', { data: { feed: id, force: true } });
await expect.poll(async () => (await feed()).last_error ?? '', { timeout: 20_000 }).toMatch(error);
// A day in, which is when the page names a failure in words.
execFileSync('sqlite3', [db, `UPDATE feeds SET error_since = ${Math.floor(Date.now() / 1000) - 2 * 86_400} WHERE id = '${id}'`]);
const f = await feed();
if (reason) expect(f.failing?.reason, to).toContain(reason);
else expect(f.failing, to).toBeNull();
if (to === 'page') {
expect(f.failing?.new_url).toBe(`${F}/moved.xml`);
await page.reload();
await page.locator('#feedlist .feed', { hasText: 'Flip Show' }).click();
await expect(page.locator('#content .fail')).toContainText('The feed moved');
await expect(page.locator('#content [data-ffail="newurl"]')).toBeVisible();
}
}
// Back again, from the address it moved to for good: the error goes, and the feed is read
// from there from now on.
await flip('moved');
await page.request.post('/api/fetch', { data: { feed: id, force: true } });
await expect.poll(async () => (await feed()).last_error, { timeout: 20_000 }).toBeNull();
await expect.poll(async () => (await feed()).url, { timeout: 20_000 }).toBe(`${F}/moved.xml`);
} finally {
await flip('ok');
await page.request.delete(`/api/feeds/${encodeURIComponent(id)}`);
}
});
test('an item sent as HTML and Markdown switches between them', async ({ page }) => {
const api = (p: string, init?: { method?: string, body?: string }) => page.evaluate(([p, init]) => fetch(p, { headers: { 'Content-Type': 'application/json' }, ...init })
.then((r) => r.json().catch(() => null)), [p, init] as const);
@@ -860,22 +1082,20 @@ test('deleting a shared file warns that it is everyone\'s copy', async ({ page }
await expect(row).toBeVisible({ timeout: 20_000 });
await row.click();
// An icon now; what it does, and to whom, is in its tooltip.
const del = page.locator('#files button[data-a="del"]');
await expect(del).toHaveAttribute('title', /^Delete for everyone \(shared with 1 other person/);
// Under the file's menu (#457), saying what it does, and to whom.
await page.locator('#files .encbox [data-a="more"]').last().click();
const del = page.locator('#modalCard [data-m="del"]');
await expect(del).toHaveText(/^Delete from iPX, for everyone \(shared with 1 other person/);
// Two prompts: the page's own, then the server's, because someone else has not played
// it. Accept the first, decline the second, and the file must survive.
const seen: string[] = [];
page.on('dialog', d => {
seen.push(d.message());
if (seen.length === 1) d.accept();
else d.dismiss();
});
// Two questions: the page's own, then the server's, because someone else has not played
// it. Yes to the first, Cancel to the second, and the file must survive.
await del.click();
await expect.poll(() => seen.length, { timeout: 10_000 }).toBe(2);
expect(seen[0]).toContain('shared with 1 other person');
expect(seen[1]).toContain('one copy of this file');
const ask = page.locator('dialog.ask');
await expect(ask).toContainText('shared with 1 other person');
await answer(page);
await expect(ask).toContainText('one copy of this file');
await answer(page, false);
await expect(ask).toHaveCount(0);
await page.reload();
await page.locator('.feed', { hasText: 'Test Show' }).click();
@@ -912,8 +1132,8 @@ test('an admin adds someone, makes them an admin, and removes them', async ({ pa
(await (await page.request.get('/api/users')).json()).find((u: Account) => u.name === 'pat')?.admin
).toBe(true);
page.once('dialog', d => d.accept());
await row.locator('[data-a="rm"]').click();
await answer(page);
await expect(row).toHaveCount(0);
});
@@ -1028,6 +1248,43 @@ test('an export from one account imports into another', async ({ page, browser }
await ctx.close();
});
test('ipxd user adds, lists, renames and removes accounts, and says what is wrong (#463)', async () => {
// Its own database, as the import test has, so the suite's accounts are not touched.
const dir = path.join(setup.root, 'cli-users');
fs.rmSync(dir, { recursive: true, force: true });
fs.mkdirSync(path.join(dir, 'data'), { recursive: true });
fs.writeFileSync(path.join(dir, 'config.toml'),
`[general]\ndownload_dir = "${dir}/downloads"\nsocket = "${dir}/ipx.sock"\nfetch_internal = ["127.0.0.1"]\n`);
const env = { ...process.env, IPX_CONFIG: path.join(dir, 'config.toml'), IPX_DATA_DIR: path.join(dir, 'data') };
const cli = (args: string[]) => execFileSync(setup.IPX_BIN, args, { env, encoding: 'utf8' });
const ipx = (args: string[], input = '') => execFileSync(setup.IPX_BIN, ['user', ...args], { env, input, encoding: 'utf8' });
const fails = (args: string[], input = '') => { try { ipx(args, input); } catch (e) { return said(e); } throw new Error(`${args} succeeded`); };
expect(ipx(['list'])).toContain('no accounts yet');
expect(fails(['add', 'ada'])).toContain('no password on stdin');
expect(fails(['add', ' '])).toContain('a name is required');
expect(ipx(['add', 'Ada'], 'adapassword\n')).toBe('added ada (admin)\n');
expect(fails(['add', 'ada'], 'x')).toContain('ada already exists');
expect(ipx(['add', 'bo', '--no-password'])).toBe('added bo, signs in through the proxy\n');
const list = ipx(['list']);
expect(list).toMatch(/^ada\s+admin\s+password\s+added \d{4}-\d\d-\d\d\s+never signed in$/m);
expect(list).toMatch(/^bo\s+proxy only\s+added /m);
expect(ipx(['passwd', 'ada'], 'newpassword')).toContain('password changed for ada');
expect(fails(['passwd', 'nobody'], 'x')).toContain('no such account: nobody');
expect(fails(['rename', 'bo', 'b;o'])).toContain('not a usable name');
expect(fails(['rename', 'bo', 'ada'])).toContain('ada already exists');
expect(ipx(['rename', 'bo', 'bea'])).toBe('renamed bo to bea\n');
expect(ipx(['rm', 'bea'])).toBe('removed bea\n');
expect(fails(['rm', 'bea'])).toContain('no such account: bea');
expect(ipx(['list'])).not.toContain('bea');
// ipxd list: the feeds, each with its id on a line of its own.
expect(cli(['list'])).toContain('No feeds configured');
cli(['add', 'http://127.0.0.1:8792/cli.xml']);
expect(cli(['list'])).toMatch(/^ {4}id {11}\S+\n {4}url {10}http:\/\/127\.0\.0\.1:8792\/cli\.xml\n {4}last checked never$/m);
});
test('ipxd import subscribes the admin, and ipxd export writes the feeds out', async () => {
// Its own config and database. The CLI works in-process, and the suite's running daemon
// reads config.toml once at start, so it would not see what the CLI added anyway.
@@ -1345,7 +1602,7 @@ test('a download by hand fills its bar and names its file, and only on its own s
const slow = page.locator('.ep', { hasText: 'Slow episode' });
await expect(slow).toBeVisible({ timeout: 20_000 });
await slow.click();
await page.locator('#files button[title="Download to the server"]').click();
await page.locator('#files button[title="Download to iPX"]').click();
await expect(slow.locator('.dlbar.live')).toBeAttached({ timeout: 10_000 });
await expect(page.locator('#count')).toContainText(/downloading .+ — \d+%/);
await expect(page.locator('.toast', { hasText: /^Downloaded .+\.mp3/ })).toBeVisible({ timeout: 20_000 });
@@ -1358,7 +1615,7 @@ test('a download by hand fills its bar and names its file, and only on its own s
// A download that fails says which item, and what to do (#304).
const broken = page.locator('.ep', { hasText: 'Broken episode' });
await broken.click();
await page.locator('#files button[title="Download to the server"]').click();
await page.locator('#files button[title="Download to iPX"]').click();
await expect(page.locator('.toast', { hasText: 'Unable to download "Broken episode". Try again with its download button.' }))
.toBeVisible({ timeout: 20_000 });
await expect(broken.locator('.dlbar.live')).toHaveCount(0);
@@ -1493,20 +1750,23 @@ test('the player keeps its speed and volume, marks an item played to its end rea
});
test('a deleted file looks as if it was never downloaded', async ({ page }) => {
// Other people subscribe to Picture Blog by now, so both prompts come; take them.
page.on('dialog', d => d.accept());
// Other people subscribe to Picture Blog by now, so both questions come; yes to each.
await page.locator('.feed', { hasText: 'Picture Blog' }).click();
const row = page.locator('.ep', { hasText: 'An Article' });
await expect(row).toBeVisible({ timeout: 20_000 });
await row.click();
await page.locator('#files button[data-a="del"]').click();
await page.locator('#files .encbox [data-a="more"]').last().click();
await page.locator('#modalCard [data-m="del"]').click();
await answer(page);
await answer(page);
// No "reaped", no chip at all: just the way to get it again.
await expect(row.locator('.kind.here')).toHaveCount(0);
await expect(row).not.toContainText(/reaped/i);
await row.click();
await expect(page.locator('#files')).not.toContainText(/reaped/i);
await expect(page.locator('#files button[title="Download to the server"]')).toBeVisible();
await expect(page.locator('#files button[title="Download to iPX"]')).toBeVisible();
await expect(page.locator('#files .encbox .meta')).toContainText('Publisher only');
});
test('one action, one icon: the toolbar, the page and every dialog agree', async ({ page }) => {
@@ -1572,8 +1832,8 @@ test('All Subscriptions marks everything read, across every feed', async ({ page
await expect(page.locator('#epSearch')).toHaveAttribute('placeholder', 'Search');
await expect(page.locator('#epSearch')).toHaveAccessibleName('Search All Subscriptions');
page.once('dialog', d => d.accept());
await page.locator('#content .acts [data-a="readall"]').click();
await answer(page);
await expect(all.locator('.badge')).toHaveText('0');
await page.locator('.tabs button', { hasText: 'Unread' }).click();
await expect(page.locator('.ep')).toHaveCount(0);
@@ -1877,8 +2137,8 @@ test('an admin removes a feed from the directory, and unblocks it (#206)', async
await piper.locator('.show [data-a="drefresh"]').click();
await expect(piper.locator('.toast', { hasText: 'Checked' })).toBeVisible();
await expect(piper.locator('.show [data-a="dremove"]')).toHaveCount(1);
piper.once('dialog', d => d.accept());
await piper.locator('.show [data-a="dremove"]').click();
await answer(piper);
await expect(piper.locator('.show h2')).toHaveCount(0);
expect(await listed()).not.toContain('Aardvark Radio');
} finally {
@@ -1923,7 +2183,8 @@ test.describe('on a phone', () => {
await page.locator('.feed', { hasText: 'Test Show' }).click();
await page.locator('.tabs button', { hasText: 'Downloaded' }).first().click();
await page.locator('.ep').first().click();
const del = page.locator('#detail [data-a="del"]');
// Delete is under the file's menu (#457), which sits above the notes.
const del = page.locator('#detail .encbox [data-a="more"]').first();
await expect(del).toBeInViewport();
// Below a long set of notes it was screens down and looked missing (issue #21).
expect(await page.locator('#detail').evaluate(d =>
@@ -2130,6 +2391,31 @@ test.describe('an item with no files, on a phone', () => {
await expect(page.locator('#detail')).not.toContainText('No files');
});
test('one press of a file\'s button brings it from the publisher, through iPX, to the phone (#457)', async ({ page }) => {
// A file iPX does not have: Test Show's downloaded one, deleted first, so the test owns it.
const enc = await page.evaluate(async () => {
const list = await api('/api/feeds/test-show/entries?filter=all') as ListPage;
const x = list.entries.flatMap(e => e.enclosures).find(x => x.path && playsKind(x))!;
await api(`/api/enclosures/${x.id}?force=true`, { method: 'DELETE' });
return x.id;
});
await page.locator('#burger').click();
await page.locator('.feed', { hasText: 'Test Show' }).click();
await page.locator('.tabs button', { hasText: 'All' }).first().click();
// The row of a file not on iPX carries its download bar, by the file's id.
await page.locator('.ep').filter({ has: page.locator(`.dlbar[data-bar="${enc}"]`) }).click();
const box = page.locator('#detail .encbox');
await expect(box.locator('.meta')).toContainText('Publisher only');
await box.locator('[data-a="want"]').click();
await expect(box.locator('.meta')).toHaveText(/On iPX and this device$/, { timeout: 20_000 });
await expect(box.locator('[data-a="more"][aria-pressed="true"]')).toBeVisible();
expect(await page.evaluate(() => localStorage.getItem('ipx.wanted'))).toBe('[]');
// Taken off the phone from its menu; iPX keeps its copy.
await box.locator('[data-a="more"][aria-pressed="true"]').click();
await page.locator('#modalCard [data-m="offline"]').click();
await expect(box.locator('.meta')).toHaveText(/On iPX$/);
});
test('back and the item\'s actions stay at hand anywhere in a long post (#456)', async ({ page }) => {
await page.locator('#burger').click();
await page.locator('#feedlist .place', { hasText: 'All Subscriptions' }).click();
@@ -2144,7 +2430,9 @@ test.describe('an item with no files, on a phone', () => {
});
const bar = page.locator('#detail .dfloat');
await expect(bar.locator('#dback')).toBeVisible();
await expect(bar.locator('.dacts [data-a]')).toHaveCount(3);
// By name, not counted: an episode has Up Next's button too (#473), so the count depended on
// which item the tests before had left first.
for (const a of ['read', 'flag', 'share']) await expect(bar.locator(`.dacts [data-a="${a}"]`)).toBeVisible();
await page.locator('#detail').evaluate(el => { el.scrollTop = 3000; });
// Still at the top of the screen, not scrolled away with the title.
for (const q of ['#dback', '.dacts']) expect((await bar.locator(q).boundingBox())!.y).toBeLessThan(80);
@@ -2154,6 +2442,10 @@ test.describe('an item with no files, on a phone', () => {
await flag.click();
await expect(bar.locator('[data-a="flag"]')).not.toHaveAttribute('aria-pressed', was!);
expect(await page.locator('#detail').evaluate(el => el.scrollTop)).toBeGreaterThan(2500);
// Pinned, it keeps its accent disc in the bar: cleared like the others, its pin was drawn in the
// colour meant for the accent, white on a light theme's capsule (#480).
const pinned = bar.locator('[data-a="flag"][aria-pressed="true"]');
if (was !== 'true') await expect(pinned).not.toHaveCSS('background-color', 'rgba(0, 0, 0, 0)');
await bar.locator('[data-a="flag"]').click();
await expect(bar.locator('[data-a="flag"]')).toHaveAttribute('aria-pressed', was!);
await bar.locator('#dback').click();
@@ -2163,7 +2455,7 @@ test.describe('an item with no files, on a phone', () => {
test('a pinned feed, even one from inside a folder, goes to the top of the list', async ({ page }) => {
// The Signals folder is first, under All Subscriptions (#256), and no feed.
const rows = page.locator('#feedlist .feed:not(.sigs)');
const rows = page.locator('#feedlist .feed:not(.sigs):not(.plists)');
const group = page.locator('.feed.group').first();
if ((await group.locator('.chev').getAttribute('aria-expanded')) !== 'true') await group.locator('.chev').click();
const child = page.locator('.feed.child').first();
@@ -2289,10 +2581,8 @@ test('Share hands the feed, and an episode as a link to its page on ipx-play (#4
const paid = await page.evaluate(() => api('/api/entries/paid-show/paid-1/share', { method: 'POST', body: '{}' }));
expect(paid).toEqual({ url: null, why: 'private' });
// Through the same menu all the same: the sheet needs a press of its own after that request
// (#452), and a key in the address is warned of there, not asked with confirm(), which the iOS
// app answers Cancel (#453).
// (#452), and a key in the address is warned of there rather than asked first.
await page.evaluate(async () => {
window.confirm = () => false;
const e = (await api('/api/feeds/paid-show/entries') as ListPage).entries[0];
await shareEpisode({ ...e, link: 'https://www.patreon.com/posts/1?auth=secret123' }, null);
});
@@ -2312,6 +2602,22 @@ test('Share hands the feed, and an episode as a link to its page on ipx-play (#4
await expect(page.locator('#modalCard')).not.toContainText('own access');
await page.locator('#shlink').click();
await expect.poll(() => page.evaluate(() => window.shared.at(-1)?.url)).toBe('https://www.patreon.com/glasscannon/posts/1');
await page.keyboard.press('Escape');
// A feed whose address carries its key is asked about first, in the page's own dialog (#462):
// Cancel shares nothing, and Escape closes the question alone.
const before = await page.evaluate(() => window.shared.length);
await page.locator('.feed', { hasText: 'Paid Show' }).click();
await page.locator('#content .acts [data-a="share"]').click();
await expect(page.locator('dialog.ask')).toContainText('includes your own access');
await answer(page, false);
await page.locator('#content .acts [data-a="share"]').click();
await page.keyboard.press('Escape');
await expect(page.locator('dialog.ask')).toHaveCount(0);
expect(await page.evaluate(() => window.shared.length)).toBe(before);
await page.locator('#content .acts [data-a="share"]').click();
await answer(page);
await expect.poll(() => page.evaluate(() => window.shared.at(-1)?.url)).toBe('http://127.0.0.1:8792/paid.xml?auth=secret123');
});
test('a refresh button turns from the press to the end of the scan it asked for', async ({ page }) => {
@@ -2585,9 +2891,10 @@ test('a downloaded file\'s buttons sit on one row in the files pane', async ({ p
await expect(page.locator('.ep').first()).toBeVisible();
await page.evaluate(() => showDetail(S.entries.find(e => e.enclosures.some(x => x.path)) ?? null));
const box = page.locator('#files .encbox').first();
await expect(box.locator('.btn')).toHaveCount(5);
// Play, the one button that brings it here, share, and the rest under ⋯ (#457).
await expect(box.locator('.btn')).toHaveCount(4);
const tops = await box.locator('.btn').evaluateAll(bs => bs.map(b => Math.round(b.getBoundingClientRect().top)));
expect(new Set(tops).size, 'play, keep, save, share and delete wrapped onto two rows').toBe(1);
expect(new Set(tops).size, 'play, save, share and more wrapped onto two rows').toBe(1);
// And on a phone, where the pane is the whole width (#412 added keep).
await page.setViewportSize({ width: 375, height: 800 });
const phone = await box.locator('.btn').evaluateAll(bs => bs.map(b => Math.round(b.getBoundingClientRect().top)));
@@ -2741,8 +3048,8 @@ signalsTest('a Signal is renamed from its own page and deleted from there', asyn
const one = async () => (await (await page.request.get('/api/signals')).json() as Signal[]).find(s => s.id === id);
expect((await one())?.name).toBe('Bread and cakes');
page.once('dialog', d => d.accept());
await page.locator('#content [data-a="rm"]').click();
await answer(page);
await expect(page.locator('.toast', { hasText: 'Deleted' })).toBeVisible();
await expect(page.locator('#feedlist .feed.child', { hasText: 'Bread and cakes' })).toHaveCount(0);
expect(await one()).toBeUndefined();
@@ -2768,8 +3075,8 @@ signalsTest('Signals are turned on in Settings with a key TypeSafe takes, and of
await page.locator('#stskey').fill('test-key');
await page.locator('#stskey').blur();
await expect(page.locator('#feedlist .sigs')).toHaveCount(1);
page.once('dialog', d => d.accept());
await page.locator('#ssigon').uncheck();
await page.locator('#ssigon').click();
await answer(page);
await expect(page.locator('#feedlist .sigs')).toHaveCount(0);
expect((await (await page.request.get('/api/me')).json()).typesafe_key_set).toBe(false);
await page.keyboard.press('Escape');
@@ -2853,3 +3160,99 @@ test('an error toast is announced and stays until it is dismissed', async ({ pag
await t.getByRole('button', { name: 'Dismiss' }).click();
await expect(t).toHaveCount(0);
});
/// A scrape as Prometheus makes it: gzipped (#253), and every sample a name, labels perhaps, and a
/// number, since one line that is not fails the whole scrape.
async function scrape(page: Page, port: number): Promise<string> {
const r = await page.request.get(`http://127.0.0.1:${port}/metrics`, { headers: { 'Accept-Encoding': 'gzip' } });
expect(r.status()).toBe(200);
expect(r.headers()['content-type']).toContain('text/plain');
const text = await r.text();
const bad = text.split('\n').filter(l => l && !l.startsWith('#') && !/^[a-z_:][a-z0-9_:]*(\{.*\})? (-?[0-9.e+-]+|NaN|\+Inf)$/i.test(l));
expect(bad, `port ${port}`).toEqual([]);
return text;
}
test('each service serves its metrics as Prometheus reads them, the requests made counted by route', async ({ page }) => {
// #194, #370, #458: production's Prometheus scrapes these every 15 s; the dashboard and the
// alerts go blank if one stops answering, and nothing else in the suite asks for them.
await page.request.get('/api/feeds');
const ipx = await scrape(page, 8799);
expect(ipx).toMatch(/^# TYPE ipx_http_request_duration_seconds histogram$/m);
expect(ipx).toMatch(/^ipx_http_request_duration_seconds_count\{method="GET",route="\/api\/feeds",status="200"\} [1-9]/m);
expect(ipx).toMatch(/^ipx_build_info\{version="[^"]+"\} 1$/m);
expect(ipx).toMatch(/^ipx_db_connections_max [1-9]/m);
expect(ipx).toMatch(/^ipx_feeds [1-9]/m);
// The suite's ipx shares with its directory, so the directory has taken a snapshot and answered.
const dir = await scrape(page, 8797);
expect(dir).toMatch(/^directory_build_info\{version="[^"]+"\} 1$/m);
expect(dir).toMatch(/^directory_snapshots_total [1-9]/m);
expect(dir).toMatch(/^directory_http_request_duration_seconds_count\{/m);
const play = await scrape(page, 8790);
expect(play).toMatch(/^play_build_info\{version="[^"]+"\} 1$/m);
expect(play).toMatch(/^play_uptime_seconds [0-9]/m);
});
test('a reap over the quota says what it would delete and, dry, deletes nothing', async ({ page }) => {
// Retention (retention.rs) runs on the daemon's own clock in production, once a day; nothing in
// the suite ran it. Dry, so the files the tests after this one play are still there.
const env = { ...process.env, IPX_CONFIG: `${setup.root}/config/config.toml`, IPX_DATA_DIR: `${setup.root}/data` };
const ipx = (args: string[]) => execFileSync(setup.IPX_BIN, args, { env, encoding: 'utf8', timeout: 30_000 });
const files = () => fs.readdirSync(`${setup.root}/downloads`, { recursive: true, withFileTypes: true }).filter(f => f.isFile()).length;
const had = (await (await page.request.get('/api/settings')).json()).max_total_gb;
const before = files();
expect(before, 'the suite has downloaded files by now').toBeGreaterThan(0);
expect((await page.request.patch('/api/settings', { data: { max_total_gb: 0.000001 } })).status()).toBe(204);
try {
const out = ipx(['reap', '--dry-run']);
// Said as what would go, not as gone (#461).
expect(out).toMatch(/^would delete [1-9]\d* old file\(s\)/m);
expect(out).toMatch(/^would delete .+\/downloads\/.+ \(\d+\.\d MB\)$/m);
expect(out).not.toMatch(/^deleted /m);
expect(files(), 'a dry run deletes nothing').toBe(before);
} finally {
await page.request.patch('/api/settings', { data: { max_total_gb: had } });
}
// No limit: a real reap only tidies (the directory, where unread lists start, the artwork kept).
expect(ipx(['reap'])).toContain('deleted 0 old file(s), 0.0 MB');
expect(files()).toBe(before);
});
test('a podcast told in seasons runs in its own order, one season at a time or all, and a season downloads whole (#482)', async ({ page }) => {
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click({ timeout: 20_000 });
await page.locator('#content .tabs button[data-f="all"]').click();
const picker = page.locator('#content .seasons');
await expect(picker.locator('button')).toHaveText(['All seasons', 'Season 1', 'Season 2', 'Other']);
// Every season, in the podcast's own order, season 1 episode 1 first: each season's start said.
await expect(page.locator('#eps .ep .t')).toHaveText(['The Pilot', 'Season One Close', 'Season Two Opener', 'Season Two Finale', 'A Bonus Between']);
await expect(page.locator('#eps .sdiv')).toHaveText(['Season 1', 'Season 2', 'Other episodes']);
// A heading clicked sorts by it, newest first, as on any other podcast.
await page.locator('.ephead [data-sort="published"]').click();
await expect(page.locator('#eps .ep .t').first()).toHaveText('Season Two Finale');
await picker.locator('button', { hasText: 'Season 1' }).click();
await expect(page.locator('#content .seasons button', { hasText: 'Season 1' })).toHaveAttribute('aria-pressed', 'true');
await expect(page.locator('#eps .ep .t')).toHaveText(['The Pilot', 'Season One Close']);
await expect(page.locator('#eps .sdiv')).toHaveCount(0);
// The count under the list is the season's, as the server counts it.
const unread = await page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/seasons').then(r => r.json()))
.find((s: { season?: number }) => s.season === 1).unread);
await expect(page.locator('#count')).toHaveText(`Seasoned Show: 2 items, ${unread} unread`);
// The whole season onto iPX, after asking, its first episode first.
await page.locator('#content .seasondl').click();
await page.locator('#sgo').click();
// By its words: each file's own toast follows at once on the fixtures' tiny files.
await expect(page.locator('.toast', { hasText: /Downloading 2 episodes of Season 1|All of Season 1 is on iPX already/ })).toBeAttached();
await expect.poll(async () => page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/entries?season=1').then(r => r.json()))
.entries.every((e: { enclosures: { path: string | null }[] }) => e.enclosures.every(x => x.path))), { timeout: 20_000 }).toBe(true);
expect(await page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/entries?season=2').then(r => r.json()))
.entries.some((e: { enclosures: { path: string | null }[] }) => e.enclosures.some(x => x.path)))).toBe(false);
await page.locator('#content .seasons button', { hasText: 'Other' }).click();
await expect(page.locator('#eps .ep .t')).toHaveText(['A Bonus Between']);
// A podcast with one season has no picker, and opening it again starts from every season.
await page.locator('#feedlist .feed', { hasText: 'Test Show' }).first().click();
await expect(page.locator('#content .seasons')).toHaveCount(0);
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click();
await expect(page.locator('#content .seasons button.on')).toHaveText('All seasons');
});

View File

@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
<channel><title>Seasoned Show</title><link>http://127.0.0.1:8792/</link><description>A fixture podcast told in seasons (#482).</description>
<item><title>Season Two Finale</title><guid>sn-4</guid><pubDate>Mon, 01 Jun 2026 10:00:00 +0000</pubDate>
<itunes:season>2</itunes:season><itunes:episode>2</itunes:episode>
<enclosure url="http://127.0.0.1:8792/ep2.mp3?s2e2" length="40000" type="audio/mpeg"/></item>
<item><title>Season Two Opener</title><guid>sn-3</guid><pubDate>Mon, 25 May 2026 10:00:00 +0000</pubDate>
<itunes:season>2</itunes:season><itunes:episode>1</itunes:episode>
<enclosure url="http://127.0.0.1:8792/ep2.mp3?s2e1" length="40000" type="audio/mpeg"/></item>
<item><title>A Bonus Between</title><guid>sn-b</guid><pubDate>Mon, 18 May 2026 10:00:00 +0000</pubDate></item>
<item><title>The Pilot</title><guid>sn-1</guid><pubDate>Mon, 11 May 2026 10:00:00 +0000</pubDate>
<itunes:season>1</itunes:season><itunes:episode>1</itunes:episode>
<enclosure url="http://127.0.0.1:8792/ep2.mp3?s1e1" length="40000" type="audio/mpeg"/></item>
<item><title>Season One Close</title><guid>sn-2</guid><pubDate>Mon, 04 May 2026 10:00:00 +0000</pubDate>
<itunes:season>1</itunes:season><itunes:episode>2</itunes:episode>
<enclosure url="http://127.0.0.1:8792/ep2.mp3?s1e2" length="40000" type="audio/mpeg"/></item>
</channel></rss>

View File

@@ -6,6 +6,8 @@ import path from 'node:path';
const dir = import.meta.dirname;
const port = Number(process.env.FIXTURE_PORT || 8792);
let flip = 'ok';
http.createServer((req, res) => {
// Jev, for Signals (#254): sure of an item whose text has a question's keyword in it. Refuses
// a request in the shape TypeSafe refuses, as it does (#257).
@@ -87,6 +89,63 @@ http.createServer((req, res) => {
next();
return;
}
// Feeds in the shapes the others are not (#463): Atom and RSS each with a bare "&", the RSS with the iTunes and
// Media RSS fields; WordPress.com's posts as its API sends them; and replies that are no feed.
const at = `http://127.0.0.1:${port}`;
const shapes: Record<string, [string, string]> = {
'/atom.xml': ['application/atom+xml', `<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"><title type="html">Atom&amp;#8217;s Show</title>
<subtitle>An Atom feed</subtitle><link rel="alternate" href="${at}/atom.html"/><logo>${at}/art.jpg</logo>
<id>urn:atom-show</id><updated>2026-01-01T00:00:00Z</updated>
<entry><id>urn:atom-1</id><title>Q&A in Atom</title><updated>2026-01-02T00:00:00Z</updated>
<published>2026-01-02T00:00:00Z</published><link rel="alternate" href="${at}/atom-1.html"/>
<link rel="enclosure" href="${at}/atom-1.mp3" type="audio/mpeg" length="40000"/>
<link rel="enclosure" href="${at}/atom-1.mp3?_=1" type="audio/mpeg" length="40000"/>
<category term="tech"/><summary>Short summary</summary>
<content type="html">&lt;p&gt;Full &lt;b&gt;notes&lt;/b&gt;&lt;/p&gt;</content></entry>
<entry><id>urn:atom-2</id><title>Markdown entry</title><updated>2026-01-03T00:00:00Z</updated>
<summary>A [link](http://example.com) and **bold**</summary></entry></feed>`],
'/amp.xml': ['application/rss+xml', `<?xml version="1.0"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel><title>Ampersand Radio</title><link>${at}/amp.html?a=1&b=2</link><description></description><ttl>90</ttl>
<itunes:summary>Summary from iTunes</itunes:summary><itunes:explicit>yes</itunes:explicit>
<itunes:category text="Leisure"><itunes:category text="Games"/></itunes:category>
<item><guid>amp-1</guid><title>Tom & Jerry</title><pubDate>2026-01-05T10:00:00Z</pubDate>
<itunes:duration>1:02:03</itunes:duration><media:thumbnail url="${at}/art2.jpg"/>
<description>A subtitle not in the body</description><content:encoded><![CDATA[<p>The body of the notes.</p>]]></content:encoded></item>
<item><guid>amp-2</guid><title>Cut body</title><description>The whole description</description>
<content:encoded><![CDATA[x">tail of a tag</p>]]></content:encoded><media:content url="${at}/pic.png" medium="image"/></item>
<item><title>Picture only</title><enclosure url="${at}/amp-pic.png" type="image/png" length="10"/></item>
</channel></rss>`],
'/wp.json': ['application/json', JSON.stringify([{
guid: { rendered: `${at}/?p=1` }, link: `${at}/wp-1`, title: { rendered: 'WordPress &#8220;post&#8221;' },
date_gmt: '2026-01-04T12:00:00', content: { rendered: '<p>Post body</p>' }, jetpack_featured_media_url: `${at}/art.jpg`,
}])],
// Where /flip.xml moves to for good.
'/moved.xml': ['application/rss+xml', `<?xml version="1.0"?><rss version="2.0"><channel><title>Flip Show</title>
<item><guid>flip-1</guid><title>Flip one</title></item></channel></rss>`],
'/said.txt': ['text/plain', 'Unable to establish a DB connection'],
'/long.txt': ['text/plain', 'This site is down for maintenance and will be back shortly, thank you for your patience while we work'],
'/empty.xml': ['application/xml', ''],
'/garbled.xml': ['application/xml', '<rss><channel><title>Broken'],
};
const shape = shapes[req.url ?? ''];
if (shape) { res.writeHead(200, { 'content-type': shape[0] }).end(shape[1]); return; }
// A feed that starts failing, in whichever way a test asks for with /flip?to= (#463).
if (req.url?.startsWith('/flip?to=')) { flip = req.url.slice('/flip?to='.length); res.writeHead(204).end(); return; }
if (req.url === '/flip.xml') {
if (/^\d{3}$/.test(flip)) { res.writeHead(Number(flip)).end('no'); return; }
if (flip === 'moved') { res.writeHead(301, { location: '/moved.xml' }).end(); return; }
if (flip === 'loop') { res.writeHead(302, { location: '/flip.xml' }).end(); return; }
if (flip === 'drop') { req.socket.destroy(); return; }
const body = flip === 'text' ? 'Unable to establish a DB connection'
: flip === 'nothing' ? ''
: flip === 'page' ? `<!doctype html><html><head><link rel="alternate" type="application/rss+xml" href="${at}/moved.xml"></head></html>`
: flip === 'garbled' ? '<rss><channel><title>Broken'
: `<?xml version="1.0"?><rss version="2.0"><channel><title>Flip Show</title><item><guid>flip-1</guid><title>Flip one</title></item></channel></rss>`;
res.writeHead(200, { 'content-type': 'application/xml' }).end(body);
return;
}
const name = decodeURIComponent((req.url ?? '/').split('?')[0]!.replace(/^\//, '')) || 'index';
const file = path.join(dir, path.basename(name));
fs.readFile(file, (err, body) => {

View File

@@ -56,11 +56,18 @@ token = "${TOKEN}"
trusted_header = "X-Test-User"
trusted_proxies = ["127.0.0.1"]
sign_out_url = "/signed-out-by-the-proxy"
# What Prometheus scrapes in production (#194), read by a test once the others have made requests.
metrics_bind = "127.0.0.1:8799"
[feeds.test-show]
url = "http://127.0.0.1:8792/show.xml"
auto_download = true
# Told in seasons, with a bonus naming none between them: the season picker (#482).
[feeds.seasoned-show]
url = "http://127.0.0.1:8792/seasons.xml"
auto_download = false
# Downloads its image, so the UI has a file that is not playable to deal with.
[feeds.picture-blog]
url = "http://127.0.0.1:8792/pics.xml"
@@ -82,6 +89,7 @@ auto_download = false
`);
fs.writeFileSync(path.join(root, 'directory.toml'), `
bind = "127.0.0.1:8795"
metrics_bind = "127.0.0.1:8797"
database_url_env = "DIRECTORY_DATABASE_URL"
# The fixture feeds are on loopback, which the refresher refuses otherwise (#329).
fetch_internal = ["127.0.0.1"]
@@ -93,6 +101,7 @@ token_sha256 = "${crypto.createHash('sha256').update(DIRECTORY_TOKEN).digest('he
`);
fs.writeFileSync(path.join(root, 'play.toml'), `
bind = "127.0.0.1:8798"
metrics_bind = "127.0.0.1:8790"
public_url = "${PLAY}"
[[tokens]]

View File

@@ -92,6 +92,23 @@ test('a place in an episode saved offline waits, and is saved once back', async
expect((await call(page, '/api/entries/offline-blog/offline-2')).position).toBe(321);
});
test('a page older than the script the server sends is loaded again, not run with it', async ({ page }) => {
// #449: a page kept from before a deploy asks for its script by the old hash, and the server
// sends the new one whatever the name says.
await controlled(page);
const mine = await page.evaluate(() => document.querySelector('script[src^="/app.js"]')!.getAttribute('src')!);
const kept = () => page.evaluate(async () => (await (await caches.open('ipx-page')).keys()).map(k => new URL(k.url).pathname + new URL(k.url).search));
await expect.poll(kept).toContain(mine);
await page.evaluate(() => { (window as unknown as { stale: boolean }).stale = true; });
const reloaded = page.waitForEvent('load');
expect(await page.evaluate(() => fetch('/app.js?v=000000000000').then(() => 'given', () => 'refused'))).toBe('refused');
await reloaded;
expect(await page.evaluate(() => 'stale' in window), 'the page was loaded again').toBe(false);
// What is kept is still the script under its own name, not the new one under the old.
expect(await kept()).toContain(mine);
expect(await kept()).not.toContain('/app.js?v=000000000000');
});
test('online, a picture in an item\'s text still comes from its publisher, through the worker', async ({ page }) => {
await controlled(page);
await page.locator('#feedlist .feed', { hasText: 'Offline Blog' }).click({ timeout: 20_000 });
@@ -146,12 +163,17 @@ test('an episode kept on the device plays from it offline, and its place waits t
await page.locator('.ep', { hasText: 'Listen on a Plane' }).click();
};
await open();
const keep = page.locator('#files [data-a="offline"]');
// Kept by its menu on a computer; the line in its box says where it is (#457).
const where = page.locator('#files .encbox .meta');
const menu = async (m: string) => {
await page.locator('#files .encbox [data-a="more"]').last().click();
await page.locator(`#modalCard [data-m="${m}"]`).click();
};
const row = page.locator('.ep', { hasText: 'Listen on a Plane' });
await expect(keep).toHaveAttribute('aria-pressed', 'false');
await expect(where).toHaveText(/On iPX$/);
await expect(row.locator('.kept')).toHaveCount(0);
await keep.click();
await expect(keep).toHaveAttribute('aria-pressed', 'true', { timeout: 15_000 });
await menu('offline');
await expect(where).toHaveText(/On iPX and this device$/, { timeout: 15_000 });
expect(await cacheSize(page, 'ipx-episodes')).toBe(1);
// Its row in the list says so too (#413).
await expect(row.locator('.kept')).toHaveText('On this device');
@@ -160,7 +182,7 @@ test('an episode kept on the device plays from it offline, and its place waits t
await page.reload();
await open();
// Still kept, as the page reads it from the cache at start.
await expect(keep).toHaveAttribute('aria-pressed', 'true');
await expect(where).toHaveText(/On iPX and this device$/);
await expect(row.locator('.kept')).toBeVisible();
await page.locator('#files [data-a="play"]').click();
await expect.poll(() => page.evaluate(() => audio.currentTime), { timeout: 15_000 }).toBeGreaterThan(0.3);
@@ -180,8 +202,8 @@ test('an episode kept on the device plays from it offline, and its place waits t
expect((await call(page, `/api/entries/${encodeURIComponent(id)}/offline-ep-1`)).position).toBeGreaterThanOrEqual(0);
// Taken off the device again.
await keep.click();
await expect(keep).toHaveAttribute('aria-pressed', 'false');
await menu('offline');
await expect(where).toHaveText(/On iPX$/);
expect(await cacheSize(page, 'ipx-episodes')).toBe(0);
await expect(row.locator('.kept')).toHaveCount(0);
});

View File

@@ -10,5 +10,5 @@
"noUncheckedIndexedAccess": true,
"skipLibCheck": true
},
"include": ["web/sw/*.ts"]
"include": ["web/sw/*.ts", "web/src/wire.ts"]
}

View File

@@ -13,6 +13,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- A podcast told in seasons lists its episodes in its own order, season 1 episode 1 first, until a heading is clicked to sort it otherwise, with each season's start marked. A season picker under its tabs lists one season at a time, or the episodes in none, and a season picked can be downloaded whole (#482).
- Smart playlists, in a folder of their own in the feed list: choose the podcasts, which of them play first, unplayed episodes only or all, newest or oldest first, and the playlist keeps itself up to date. Playing from one goes on through it once Up Next is empty (#476).
- Now Playing: tap the player bar to see what is playing with its artwork large, its podcast (a tap opens it), its show notes and what follows in Up Next; Esc or the bar closes it (#475).
- Podcasts: your podcasts as a shelf of their artwork, each with how many episodes are new; the search box narrows it, and a tap opens one (#474).
- Up Next: line episodes up with the list button on a row or in the reader (`q`, or `Shift Q` to play one next), move them by their handles, and each plays when the one before it ends. The player has a Next button while something is lined up, and the lock screen's next-track button does the same (#473).
- The page reads ipx's answers in protobuf, with a decoder of its own and no library, and in JSON from a server that has none; offline, a kept answer still shows what was read offline (#470).
- On a phone, back and the item's actions (read, pin, open, share) float over the text as it scrolls, so they are at hand anywhere in a long post without scrolling back to the top; pressing one there keeps your place (#456).
- Share on an episode offers Share link, Share from where you are, and Copy link, with a link to the episode's page on ipx-play that anyone can play; an episode of a private feed offers its own page in the same menu, never its file, which a paid feed signs for you, and says why there is no page anyone can play. An admin sets ipx-play up in Admin, Directory (#447, #452, #454, #455).
- In the iOS app, Settings has a This device section for the app's server and player token, with a button that makes a token and hands it to the app (#445).
@@ -33,6 +39,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- On a phone, a pinned item's pin in the reader's floating actions is on its accent disc again, rather than nearly invisible on a light theme (#480).
- Swiping between items on a phone no longer flashes: the pictures of the items either side are loaded ahead, so the preview under your finger shows its picture with its text, and the swipe ends only once the new item's pictures are ready (#471).
- Deleting a downloaded file, marking everything read, deleting a signal and the other actions that ask first now ask in the page's own dialog, so they go ahead in the iOS app, which answered the browser's question Cancel without showing it (#462).
- A page kept for offline from before a deploy, shown on waking before the network was back, is loaded again rather than run with the new script, which left it dead until reloaded by hand (#449).
- On a phone the totals along the bottom (All Subscriptions: N items, N unread) are text alone, centred just above the home indicator, instead of a band and rule that ran to the bottom edge and were cut off by the screen's rounded corners (#424).
- The admin page's top bar clears the status bar in the iOS app, so its back button can be tapped; the page asked for no room under the clock as the app page does (#423).
- Swiping, or j, through more than 50 items no longer stops at the 50th until a reload: the next ones are fetched as you near the end, and Load more on the Unread tab no longer skips as many unread items as you had read (#383).
@@ -44,6 +54,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Podcasts are in order by name with a leading "The", "A" or "An" set aside, in the feed list, the Podcasts shelf, a playlist's choices and the Directory: The Rest Is Science is under R, not T (#481).
- A file has one button that brings it to where you are: on a phone or in the iOS app it ends on the device, with iPX fetching it first when it has not got it, and on a computer iPX fetches it and the button then saves a copy. A line beside the file's size says where it is (publisher only, queued for iPX, on iPX, on this device), and the rarer actions (remove from this device, delete from iPX, download to iPX only) are under ⋯ (#457).
- The admin page is laid out as a feed's settings are: each tab in named parts, numbers with their unit beside them, switches for on and off, Server's Save always in reach, and on a phone the tabs in a row of their own so all four fit (#414).
- An item's title and text take four fifths of the reading pane's width, no longer running to its far edge (#360).

View File

@@ -509,7 +509,7 @@ a{color:var(--accent)}
::-webkit-scrollbar-track{background:transparent}
/* ---------- shell ---------- */
#shell{display:grid;grid-template-columns:290px 1fr;min-height:0;min-width:0;overflow:hidden}
#shell{display:grid;grid-template-columns:290px 1fr;min-height:0;min-width:0;overflow:hidden;position:relative}
/* [ hides the feed list. A phone slides it over the page instead, so this is for wider screens. */
@media (min-width:821px){
body.nosb #shell{grid-template-columns:minmax(0,1fr)}
@@ -688,22 +688,60 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
/* Currently Listening: how far into each episode you are, as a rail along the foot of its row.
The one in the player is marked as it is everywhere else, by the amber EQ bars, and its rail
and time left move as it plays. The rest stay neutral, so that one is what stands out. */
#listening .childrow{position:relative;overflow:hidden;gap:12px;padding:10px 10px 13px}
#listening .childrow .art{width:44px;height:44px;font-size:13px}
#listening .txt b{display:flex;align-items:center;gap:7px}
#listening .txt b span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#listening .txt small{display:flex;gap:12px;margin-top:3px;color:var(--faint);font-size:11.5px}
#listening .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#listening .txt small .left{flex:none;color:var(--dim)}
#listening .childrow:not(.now) .eq{display:none}
#listening .rail{position:absolute;left:0;right:0;bottom:0;height:3px;background:var(--raise)}
#listening .rail i{display:block;height:100%;width:0;background:var(--faint);transition:width .25s linear}
#listening .now{border-color:color-mix(in srgb,var(--accent2) 60%,var(--line))}
#listening .now .eq,#listening .now .left{color:var(--accent2)}
#listening .now .rail i{background:var(--accent2)}
#listening .childrow,#nowqueue .childrow{position:relative;overflow:hidden;gap:12px;padding:10px 10px 13px}
#listening .childrow .art,#nowqueue .childrow .art{width:44px;height:44px;font-size:13px}
#listening .txt b,#nowqueue .txt b{display:flex;align-items:center;gap:7px}
#listening .txt b span,#nowqueue .txt b span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#listening .txt small,#nowqueue .txt small{display:flex;gap:12px;margin-top:3px;color:var(--faint);font-size:11.5px}
#listening .txt small .fd,#nowqueue .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#listening .txt small .left,#nowqueue .txt small .left{flex:none;color:var(--dim)}
#listening .childrow:not(.now) .eq,#nowqueue .childrow:not(.now) .eq{display:none}
/* Now Playing (#475): over the feeds and the list, above the player bar, which keeps the
controls. The artwork is the one large thing on the page. */
#nowsheet{position:absolute;inset:0;z-index:30;overflow:auto;background:var(--bg);
padding:22px max(16px,calc((100% - 720px)/2)) 32px}
#nowclose{position:sticky;float:right;top:0;margin:-8px -4px 0 0;right:max(12px,calc((100% - 720px)/2 - 44px))}
.nowhead{display:grid;grid-template-columns:minmax(0,280px) minmax(0,1fr);gap:24px;align-items:end;margin:10px 0 26px}
.nowhead .nowart{width:100%;height:auto;aspect-ratio:1;border-radius:14px;font-size:56px}
.nowmeta{display:flex;flex-direction:column;gap:6px;min-width:0}
.nowmeta h2{margin:0;font-size:24px;line-height:1.2;text-wrap:balance}
.nowshow{align-self:flex-start;color:var(--accent);font-size:15px;font-weight:500;text-align:left}
.nowmeta small{color:var(--dim);font-size:12.5px;font-variant-numeric:tabular-nums}
#nowsheet h3{font-size:14px;font-weight:600;margin:22px 0 10px;color:var(--dim)}
#nowqueue{display:flex;flex-direction:column;gap:6px}
#pnow{cursor:pointer;border-radius:8px}
@media (max-width:820px){
.nowhead{grid-template-columns:1fr;justify-items:center;text-align:center;gap:18px}
.nowhead .nowart{max-width:300px}
.nowmeta{align-items:center}
.nowshow{align-self:center;text-align:center}
}
/* The Podcasts shelf (#474): the artwork is the podcast, as on a shelf of records, so nothing
frames it: no card, no shadow, the name and its new episodes under it. */
.shelf{display:grid;grid-template-columns:repeat(auto-fill,minmax(112px,1fr));gap:20px 14px;padding:4px 2px 24px}
.shelf .show{display:flex;flex-direction:column;gap:6px;min-width:0;text-align:left;cursor:pointer;border-radius:10px}
.shelf .show .art{width:100%;height:auto;aspect-ratio:1;border-radius:10px;font-size:26px}
.shelf .show b{font-weight:500;font-size:13px;line-height:1.3;color:var(--fg);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.shelf .show small{color:var(--dim);font-size:11.5px;min-height:1em;margin-top:-3px}
@media (hover:hover){.shelf .show:hover .art{outline:2px solid var(--accent);outline-offset:2px}}
/* A playlist's podcasts in its dialog: each one in or out, and whether it plays first. */
.plshows{display:flex;flex-direction:column;gap:2px;max-height:min(46vh,360px);overflow:auto;margin-top:4px}
.plshow{display:grid;grid-template-columns:28px minmax(0,1fr) auto;gap:10px;align-items:center;padding:4px 2px}
.plshow .art{width:28px;height:28px;font-size:10px}
.plshow .check{margin:0;min-width:0}
.plshow .first{color:var(--dim);font-size:12.5px}
/* Up Next's handle: dragged, it takes the pointer, so the list does not scroll under the finger. */
#listening .grip{width:22px;margin-left:-4px;color:var(--faint);cursor:grab;touch-action:none}
#listening .grip svg{width:12px;height:12px}
#listening .childrow.dragging{border-color:var(--accent);cursor:grabbing}
#listening .rail,#nowqueue .rail{position:absolute;left:0;right:0;bottom:0;height:3px;background:var(--raise)}
#listening .rail i,#nowqueue .rail i{display:block;height:100%;width:0;background:var(--faint);transition:width .25s linear}
#listening .now,#nowqueue .now{border-color:color-mix(in srgb,var(--accent2) 60%,var(--line))}
#listening .now .eq,#nowqueue .now .eq,#listening .now .left,#nowqueue .now .left{color:var(--accent2)}
#listening .now .rail i,#nowqueue .now .rail i{background:var(--accent2)}
/* Quiet buttons: a filled one on every row outshouted the row that is playing. */
#listening [data-a=play]{color:var(--accent)}
#listening [data-a=remove]{color:var(--faint)}
#listening [data-a=play],#nowqueue [data-a=play]{color:var(--accent)}
#listening [data-a=remove],#nowqueue [data-a=remove]{color:var(--faint)}
/* The Directory, laid out as Apple's is: a large title, then sections. Every page carries what
kind of feed (.tabs, as the item filters are) in its title row. */
.dhead{margin-bottom:6px}
@@ -951,6 +989,14 @@ kbd{font:inherit;font-size:12px;color:var(--fg);background:var(--panel2);border:
.tabs button.on{background:var(--raise);color:var(--fg);font-weight:500}
.tabs a{padding:5px 12px;border-radius:7px;font-size:13px;color:var(--dim);text-decoration:none}
.tabs a.on{background:var(--raise);color:var(--fg);font-weight:500}
/* A podcast's seasons (#482): the tabs' track, scrolled sideways when there are more than fit. */
.seasonrow{display:flex;gap:8px;align-items:center;min-width:0;max-width:100%}
.tabs.seasons{min-width:0;overflow-x:auto;scrollbar-width:none}
.tabs.seasons::-webkit-scrollbar{display:none}
.tabs.seasons button{white-space:nowrap;flex:none}
/* Where a season starts in the list of every season. */
.sdiv{padding:14px 8px 5px;font-size:12px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:var(--dim);border-bottom:1px solid var(--line)}
.sdiv:first-child{padding-top:4px}
/* ---------- the admin page (admin.html) ---------- */
/* One column that scrolls under the same header, rather than the app's fixed panes. */
@@ -1011,7 +1057,7 @@ body.adminpage #logbox{height:calc(100dvh - 230px);min-height:240px}
/* A table, as the original's was: unread, kept, title, feed, file, size, published. */
.ephead,.ep{
display:grid;gap:8px;align-items:center;
grid-template-columns:22px 22px minmax(120px,1fr) minmax(0,160px) 56px minmax(0,72px) minmax(0,92px) 64px;
grid-template-columns:22px 22px minmax(120px,1fr) minmax(0,160px) 56px minmax(0,72px) minmax(0,92px) 96px;
}
/* A pixel more side padding than a row's: a row has a 1px border the heading has not, and without
it every heading sat a pixel left of its column. */
@@ -1081,7 +1127,7 @@ body.playing .eq i:nth-child(3){animation-delay:-.6s}
.ep .file .dlbar{position:absolute;left:0;right:0;bottom:-5px;margin:0}
.ep .rowacts{justify-content:flex-end}
/* One feed's own table has no need of a Feed column; All Subscriptions does. */
#split.one .ephead,#split.one .ep{grid-template-columns:22px 22px minmax(120px,1fr) 56px minmax(0,72px) minmax(0,92px) 64px}
#split.one .ephead,#split.one .ep{grid-template-columns:22px 22px minmax(120px,1fr) 56px minmax(0,72px) minmax(0,92px) 96px}
#split.one .h-fd,#split.one .ep .fd{display:none}
.dot{width:3px;height:3px;border-radius:50%;background:var(--faint);flex:none}
.ep .rowacts{display:flex;gap:2px;align-items:flex-start;opacity:0;transition:opacity .12s}
@@ -1152,6 +1198,10 @@ input[type=range]::-moz-range-thumb{width:12px;height:12px;border:0;border-radiu
overscroll-behavior:contain;
}
.card.wide{width:min(1000px,100%)}
/* The page's own question before something hard to take back (#462): over any dialog already up. */
dialog.ask{color:inherit;margin:auto;width:min(420px,calc(100% - 32px))}
dialog.ask::backdrop{background:rgba(0,0,0,.6)}
dialog.ask p{margin:0;line-height:1.45}
#logbox{
background:var(--bg);border:1px solid var(--line);border-radius:9px;padding:10px 12px;
height:min(60vh,520px);overflow:auto;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;
@@ -1374,6 +1424,9 @@ body:has(#player.on) #status{padding-bottom:3px}
.dfloat #dback{margin:0;width:44px;height:44px;border-radius:999px}
.dfloat .dacts{gap:2px;padding:2px 6px;border-radius:999px}
#detail .dfloat .dacts .btn{background:transparent;border-color:transparent;box-shadow:none}
/* Pinned keeps its accent disc: cleared with the rest, its pin, in the colour drawn on the accent,
was white on a light theme's capsule (#480). */
#detail .dfloat .dacts .btn[data-a=flag][aria-pressed=true]{background:var(--accent);border-color:var(--accent)}
/* Beside the reader while it is swiped (gestures.ts): the item next to it, with a strip of the
page's own background between them, so the list under the reader never shows (#52). */
#dpeek{position:fixed;top:0;bottom:0;left:0;width:calc(100% + 16px);z-index:38;background:var(--bg);pointer-events:none}
@@ -1494,6 +1547,10 @@ body:has(#player.on) #status{padding-bottom:3px}
.tabs{flex:1 1 100%;border-radius:10px;padding:2px}
.tabs button,.tabs a{flex:1;text-align:center;padding:7px 4px;border-radius:8px;font-size:14px}
.tabs button.on,.tabs a.on{box-shadow:0 1px 3px rgba(0,0,0,.22)}
/* Seasons keep their own widths, scrolling past the edge, rather than squeezing eight into 390px. */
.seasonrow{flex:1 1 100%}
.seasonrow .tabs.seasons{flex:1 1 auto}
.tabs.seasons button{flex:none;padding:7px 12px}
/* Rows: taller, larger type, and a hairline between them that starts where the text does. */
.ep{padding:10px 8px;border-radius:10px;min-height:44px}
@@ -1519,6 +1576,8 @@ body:has(#player.on) #status{padding-bottom:3px}
width:100%;max-height:calc(100dvh - var(--safe-t) - 12px);border-color:var(--edge);border-radius:20px 20px 0 0;
padding:20px 16px calc(20px + var(--safe-b));animation:sheet .3s cubic-bezier(.2,.8,.2,1);
}
/* A sheet, as every dialog is here. */
dialog.ask{margin:auto 0 0;width:100%;max-width:100%}
.card h3{font-size:22px}
.field label,.field .hint{font-size:13px}
.check{font-size:17px}

View File

@@ -29,13 +29,34 @@ const WEB_VERSION = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.js
// The files are one script, concatenated in this order, not modules: they share one top-level
// scope, as the single inline script did, and code that runs at load needs what came before it.
const PAGES: Record<string, { script: string, src: string[] }> = {
'index.html': { script: 'app.js', src: ['util', 'theme', 'feeds', 'feedpage', 'items', 'player', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] },
'admin.html': { script: 'admin.js', src: ['util', 'theme', 'admin'] },
'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'seasons', 'player', 'upnext', 'nowplaying', 'dialogs', 'signals', 'playlists', 'gestures', 'offline', 'events', 'native'] },
'admin.html': { script: 'admin.js', src: ['util', 'wire', 'theme', 'admin'] },
'login.html': { script: 'login.js', src: ['login'] },
};
// The stylesheet the app and admin pages share, served and named by hash as the scripts are.
const STYLE = 'app.css';
/// The protobuf messages ipx answers in (#470), for web/src/wire.ts: { 'pkg.Name': [[number, name,
/// type, repeated, optional]] }, read from crates/wire/proto. Only what those files use: proto3,
/// one level of messages, scalar types and messages as field types.
export function wireMessages() {
const dir = path.join(here, '..', 'crates', 'wire', 'proto');
const short: Record<string, string> = { string: 's', bool: 'b', int64: 'i', int32: 'i', uint64: 'u', uint32: 'u', double: 'd' };
const out: Record<string, [number, string, string, 0 | 1, 0 | 1][]> = {};
for (const file of fs.readdirSync(dir).filter(f => f.endsWith('.proto')).sort()) {
const text = fs.readFileSync(path.join(dir, file), 'utf8').replace(/\/\/.*$/gm, '');
const pkg = /^\s*package\s+([\w.]+)\s*;/m.exec(text)?.[1];
if (!pkg) throw new Error(`${file}: no package`);
for (const [, name, body] of text.matchAll(/message\s+(\w+)\s*\{([^}]*)\}/g)) {
out[`${pkg}.${name}`] = [...body!.matchAll(/^\s*(optional\s+|repeated\s+)?([\w.]+)\s+(\w+)\s*=\s*(\d+)\s*;/gm)].map(
([, label, type, field, num]) => [Number(num), field!, short[type!] ?? (type!.includes('.') ? type! : `${pkg}.${type}`),
label?.trim() === 'repeated' ? 1 : 0, label?.trim() === 'optional' ? 1 : 0]);
}
}
return out;
}
const WIRE = JSON.stringify(wireMessages());
const hash = (s: string | Buffer) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 12);
// hls.js, for browsers that cannot play DeadAir's playlists themselves (#181). Served as it comes,
@@ -62,7 +83,7 @@ const ICONS_URL = `/icons/index.json?v=${hash(ICONS)}`;
/// The shared stylesheet, minified. @swc/html minifies CSS inside a page, so it goes through as
/// one; the doctype only keeps it from complaining that a fragment has none.
export function buildStyle({ minify = true } = {}) {
export function buildStyle({ minify = !coverageMap } = {}) {
const css = fs.readFileSync(path.join(here, STYLE), 'utf8');
if (!minify) return css;
const r = html.minifySync(`<!doctype html><style>${css}</style>`, { minifyCss: true, removeComments: true });
@@ -78,9 +99,11 @@ export function buildStyle({ minify = true } = {}) {
return out;
}
/// A script served on its own, not one of the pages' (#392): TypeScript made JavaScript.
function compile(file: string, { minify = true } = {}): string {
const src = fs.readFileSync(path.resolve(here, file), 'utf8');
/// A script served on its own, not one of the pages' (#392): TypeScript made JavaScript. `before`
/// are files put ahead of it, sharing its scope as the pages' files do.
function compile(file: string, { minify = true } = {}, before: string[] = []): string {
const src = [...before, file].map(f => fs.readFileSync(path.resolve(here, f), 'utf8')).join('\n')
.replaceAll('/*__WIRE__*/{}', WIRE);
return swc.transformSync(src, {
filename: path.basename(file),
jsc: { parser: { syntax: 'typescript' }, target: 'es2022', minify: minify ? { compress: true, mangle: true } : undefined },
@@ -90,7 +113,7 @@ function compile(file: string, { minify = true } = {}): string {
}
/// The offline service worker (#389), at the top of the site.
export const buildWorker = (o?: { minify?: boolean }) => compile('sw/sw.ts', o);
export const buildWorker = (o?: { minify?: boolean }) => compile('sw/sw.ts', o, ['src/wire.ts']);
/// The directory's one script (#392), as crates/directory/src/site.js holds it: readable, since it
/// is committed, and saying where it comes from.
export const buildDirectoryScript = () =>
@@ -108,7 +131,8 @@ export function buildPage(name: string, { minify = !coverageMap } = {}) {
const src = parts.map(p => p.text).join('\n')
.replaceAll('__HLS_JS__', HLS_URL)
.replaceAll('__ICONS__', ICONS_URL)
.replaceAll('__WEB_VERSION__', WEB_VERSION);
.replaceAll('__WEB_VERSION__', WEB_VERSION)
.replaceAll('/*__WIRE__*/{}', WIRE);
const js = swc.transformSync(src, {
filename: name + '.ts',
jsc: {

View File

@@ -46,11 +46,12 @@
<div class="wrap" id="content"></div>
</div>
<div id="scrim" hidden></div>
<section id="nowsheet" aria-label="Now Playing" hidden></section>
</div>
<div id="status"><span id="count"></span></div>
<div id="player">
<div id="pnow">
<div id="pnow" role="button" tabindex="0" aria-expanded="false" aria-controls="nowsheet" title="Now Playing">
<div id="partwrap"></div>
<div class="txt"><b><span class="eq" aria-hidden="true"><i></i><i></i><i></i></span><span id="ptitle"></span></b><small id="pfeed"></small></div>
</div>
@@ -59,6 +60,7 @@
<button class="iconbtn" id="pback" title="Back 15 seconds (←)" aria-label="Back 15 seconds" data-icon="back"></button>
<button class="iconbtn" id="pplay" title="Play or pause (space)" aria-label="Play or pause" data-icon="play"></button>
<button class="iconbtn" id="pfwd" title="Forward 30 seconds (→)" aria-label="Forward 30 seconds" data-icon="fwd"></button>
<button class="iconbtn" id="pnext" hidden title="Play the next in Up Next" aria-label="Play the next in Up Next" data-icon="next"></button>
</div>
<div id="seekrow">
<span id="pcur">0:00</span>

View File

@@ -191,7 +191,7 @@ async function drawDirectoryAdmin(){
try{
if(b.dataset.a === 'drop'){
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;
if(!await ask(`Drop ${name}'s feeds and counts from the directory? They come back the next time ${name} shares.`, 'Drop')) return;
await api(`/api/directory-instances/${encodeURIComponent(name)}`, {method: 'DELETE'});
toast(`Dropped ${name}'s snapshot`);
}else if(b.dataset.a === 'unblock'){
@@ -235,8 +235,8 @@ async function drawAccounts(){
const u = users.find(x => String(x.id) === row.dataset.id)!;
$('[data-a="admin"]', row).onchange = (e: Event) =>
change(u, {method: 'PATCH', body: JSON.stringify({admin: (e.target as HTMLInputElement).checked})});
$('[data-a="rm"]', row).onclick = () => {
if(confirm(`Remove ${u.name}? Their subscriptions and read state go with them. Downloaded files stay.`))
$('[data-a="rm"]', row).onclick = async () => {
if(await ask(`Remove ${u.name}? Their subscriptions and read state go with them. Downloaded files stay.`, 'Remove'))
change(u, {method: 'DELETE'});
};
}

View File

@@ -108,7 +108,7 @@ let dirShow: string|null=null;
// Apple's or one an admin typed, neither of which starts with a colon.
const EVERY=':every', OTHER=':other';
const NAME=(p: {title: string|null, id: string})=>(p.title||p.id);
const byName=(a: DirFeed,b: DirFeed)=>NAME(a).localeCompare(NAME(b),undefined,{sensitivity:'base',numeric:true});
const byName=(a: DirFeed,b: DirFeed)=>nameOrder(NAME(a),NAME(b));
const bySubs=(a: DirFeed,b: DirFeed)=>b.subscribers-a.subscribers||byName(a,b);
/// The grid's orders. It opens A to Z, as the server sends it.
const DIR_SORTS: Record<string,[string,(a: DirFeed,b: DirFeed)=>number]>={
@@ -269,7 +269,7 @@ async function fillShow(box: HTMLElement,p: DirFeed){
catch(e){ toast(why(e),true); }
};
$('[data-a="dremove"]',acts).onclick=async()=>{
if(!confirm(`Remove ${NAME(p)} from the directory? It is blocked, so no server's snapshot brings it back. Admin, Directory can unblock it.`)) return;
if(!await ask(`Remove ${NAME(p)} from the directory? It is blocked, so no server's snapshot brings it back. Admin, Directory can unblock it.`, 'Remove')) return;
try{ await api(`/api/directory/${encodeURIComponent(p.id)}`,{method:'DELETE'}); }
catch(e){ return toast(why(e),true); }
toast(`Removed ${NAME(p)} from the directory`);
@@ -310,6 +310,7 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb
await renderDirectory(v.url!,$('#directory'),n=>{ if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'feed')}`; });
return;
}
if(v===VIEWS[':podcasts']){ drawShelf(box); return; }
$<HTMLInputElement>('#epSearch').setAttribute('aria-label','Search items');
box.innerHTML=`
<div class="fhead slim">
@@ -318,11 +319,31 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb
</div>
<div class="childlist" id="listening"></div>`;
$('#count').textContent=v.title;
if(v===VIEWS[':upnext']){ drawUpNext(); return; }
// The search box looks through these too, title and text, as it does a feed's items (#127).
await renderListening(S.q?`${v.url}&q=${encodeURIComponent(S.q)}`:v.url!,$('#listening',box),
n=>{ if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'episode')}`; });
}
/// The Podcasts shelf (#474): every feed with audio or video, as its artwork, with how many of its
/// episodes are new. A tap opens it. The search box narrows it by name.
function drawShelf(box: HTMLElement){
$<HTMLInputElement>('#epSearch').setAttribute('aria-label','Search podcasts');
const q=S.q.trim().toLowerCase();
const shows=S.feeds.filter(f=>f.podcast&&(!q||(f.title||f.id).toLowerCase().includes(q)));
$('#count').textContent=`Podcasts: ${plural(shows.length,'podcast')}`;
box.innerHTML=shows.length?'<div class="shelf"></div>'
:`<p class="hint">${q?`No podcast is called “${esc(S.q)}”.`:'No podcasts yet. Add a feed with episodes in it, and it shows here.'}</p>`;
const shelf=$('.shelf',box);
for(const f of shows){
const name=f.title||f.id, b=document.createElement('button');
b.type='button'; b.className='show';
b.innerHTML=`${artHTML(f.image,name)}<b>${esc(name)}</b><small>${f.unread?`${f.unread} new`:''}</small>`;
b.onclick=()=>selectFeed(f.id);
shelf.appendChild(b);
}
}
/// Currently Listening: episodes you started and have not finished, across every feed you
/// subscribe to. A row resumes the episode in the player bar on click -- a shortcut back to
/// where you left off, not another way to browse. The one in the player pauses instead.
@@ -342,22 +363,25 @@ async function renderListening(url: string,box: HTMLElement,counted: (n: number)
function drawListening(box: HTMLElement,rows: Entry[]){
box.innerHTML=rows.length?'':S.q?`<p class="hint">Nothing you are listening to mentions “${esc(S.q)}”.</p>`
:'<p class="hint">Nothing in progress. Episodes you start and do not finish show up here.</p>';
for(const e of rows){
// Carries its episode, for paintListenRow to repaint as the player moves.
const el: HTMLDivElement & {entry?: Entry}=document.createElement('div');
el.className='childrow';
el.entry=e;
el.innerHTML=artHTML(e.image||feedArt(e.feed_id),e.title||'')+
`<div class="txt"><b>${EQ}<span>${esc(entryName(e).text)}</span></b>`+
`<small><span class="fd">${esc(feedName(e.feed_id))}</span><span class="left"></span></small></div>`+
`<button class="iconbtn" data-a="play"></button>`+
`<button class="iconbtn" data-a="remove" title="Remove from Currently Listening" aria-label="Remove from Currently Listening">${ICON.close}</button>`+
`<div class="rail"><i></i></div>`;
el.onclick=ev=>(ev.target as Element).closest('[data-a=remove]')?forget(e)
:el.classList.contains('now')&&!audio.paused?audio.pause():play(e);
paintListenRow(el);
box.appendChild(el);
}
for(const e of rows) box.appendChild(listenRow(e,'Remove from Currently Listening',()=>forget(e)));
}
/// An episode's row in Currently Listening and Up Next: its art, how far in, play, and a button
/// to take it out of the list, which `remove` does.
function listenRow(e: Entry,removeLabel: string,remove: ()=>void){
// Carries its episode, for paintListenRow to repaint as the player moves.
const el: HTMLDivElement & {entry?: Entry}=document.createElement('div');
el.className='childrow';
el.entry=e;
el.innerHTML=artHTML(e.image||feedArt(e.feed_id),e.title||'')+
`<div class="txt"><b>${EQ}<span>${esc(entryName(e).text)}</span></b>`+
`<small><span class="fd">${esc(feedName(e.feed_id))}</span><span class="left"></span></small></div>`+
`<button class="iconbtn" data-a="play"></button>`+
`<button class="iconbtn" data-a="remove" title="${removeLabel}" aria-label="${removeLabel}">${ICON.close}</button>`+
`<div class="rail"><i></i></div>`;
el.onclick=ev=>(ev.target as Element).closest('[data-a=remove]')?remove()
:el.classList.contains('now')&&!audio.paused?audio.pause():play(e);
paintListenRow(el);
return el;
}
/// One row's time left, progress and play button, taken from the player when it is the one in it.
@@ -377,7 +401,7 @@ function paintListenRow(el: HTMLElement & {entry?: Entry}){
}
/// Keeps the list in step with the player. Only a row that is, or was, the one in it changes.
function syncListening(){
for(const el of $$<HTMLElement & {entry?: Entry}>('#listening .childrow'))
for(const el of $$<HTMLElement & {entry?: Entry}>('#listening .childrow, #nowqueue .childrow'))
if(el.entry&&(el.classList.contains('now')||inPlayer(el.entry))) paintListenRow(el);
}
@@ -406,7 +430,7 @@ $<HTMLInputElement>('#epSearch').oninput=(ev: Event)=>{ clearTimeout(searchT);
// server (#126, #127).
searchT=setTimeout(()=>{ S.q=(ev.target as HTMLInputElement).value; S.offset=0;
if(S.feed===':directory'){ dirShow=null; drawDirectory(); }
else if(S.feed===':listening') renderListed(VIEWS[':listening']);
else if(S.feed===':listening'||S.feed===':podcasts') renderListed(VIEWS[S.feed]);
else loadEntries(); },250); };
// Crossing the phone breakpoint moves the files between their pane and the text.
window.matchMedia?.('(max-width:820px)')?.addEventListener?.('change',()=>{ const e=cur(); if(e) showDetail(e); });
@@ -531,11 +555,11 @@ async function prefsModal(){
renderFeeds();
}catch(err){ toast(why(err),true); }
};
$<HTMLInputElement>('#ssigon').onchange=(e: Event)=>{
$<HTMLInputElement>('#ssigon').onchange=async(e: Event)=>{
const on=(e.target as HTMLInputElement).checked;
if(on){ $('#ssigkey').hidden=false; $<HTMLInputElement>('#stskey').focus(); return; }
if(!S.me?.typesafe_key_set){ $('#ssigkey').hidden=true; return; }
if(confirm('Turn Signals off and forget your TypeSafe key? Your signals are kept for when you turn them on again.')) saveKey(null);
if(await ask('Turn Signals off and forget your TypeSafe key? Your signals are kept for when you turn them on again.', 'Turn off')) saveKey(null);
else (e.target as HTMLInputElement).checked=true;
};
$<HTMLInputElement>('#stskey').onchange=(e: Event)=>{ const k=(e.target as HTMLInputElement).value.trim(); if(k) saveKey(k); };

View File

@@ -38,6 +38,11 @@ function connect(){
// Said only for a file on screen, as one downloaded by hand is: the scheduled downloads of
// everyone's feeds used to announce themselves to everyone.
if(bar){ bar.classList.remove('live'); toast('Downloaded '+ev.path.split('/').pop()); }
// On iPX now, in what this page holds too, so the open file's box says so at once rather
// than after the list comes again; and, asked for on this device, its copy here follows (#457).
for(const e of S.entries) for(const x of e.enclosures) if(x.id===ev.enclosure){ x.path=ev.path; x.state='done'; }
if(wanted.has(ev.enclosure)) followWanted({id: ev.enclosure, path: ev.path});
else syncKeepButtons();
refreshEntries();
}
// A copy finished: the episode's "Cutting dead air…" becomes how much shorter it is.
@@ -50,6 +55,7 @@ function connect(){
else if(ev.ev==='download_error'){
const bar=document.querySelector(`.dlbar[data-bar="${ev.enclosure}"]`);
if(bar) bar.classList.remove('live');
unwant(ev.enclosure);
// Which item, and what to do: the reason (ev.msg) is in the daemon's log (#304).
const e=S.entries.find(x=>x.enclosures.some(n=>n.id===ev.enclosure));
toast(`Unable to download ${e?`"${entryName(e).text}"`:'a file'}. Try again with its download button.`,true); refreshEntries();
@@ -132,3 +138,5 @@ function offerReload(){
}
connect();
loadFeeds().then(preloadLists).catch(()=>{});
loadUpNext();
loadPlaylists();

View File

@@ -23,6 +23,9 @@ function renderFeed(){
const v=VIEWS[S.feed ?? ''];
if(v&&v.url) return renderListed(v);
if(S.feed===SIGNALS) return renderSignals();
if(S.feed===PLAYLISTS) return renderPlaylists();
const pl=playlistOf(S.feed);
if(pl) return renderPlaylist(pl);
const f=v?null:S.feeds.find(x=>x.id===S.feed);
const sg=signalOf(S.feed);
$<HTMLButtonElement>('#tbRemove').disabled=!f;
@@ -96,22 +99,28 @@ function renderFeed(){
renderFeed(); loadEntries();
});
if(f) wireFailBanner(box,f);
// An OPML's page is many podcasts' episodes together, their seasons each their own.
if(f&&!kids.length) loadSeasons(f);
}
/// The item table's headings, each a button that sorts by its column. The first click goes the
/// natural way round (A to Z; newest, largest and kept first) and the next one reverses it.
const COLS=[['kept','Pinned',ICON.pin],['title','Title'],['feed','Feed'],['type','File'],['size','Size'],['published','Published']];
function sortHead(){
const now=sortFor(S.feed ?? '');
return '<div class="ephead"><span></span>'+COLS.map(([k,label,icon])=>{
const on=S.sort.col===k;
const on=now.col===k;
return `<button class="hs${on?' on':''}${k==='feed'?' h-fd':''}${icon?' h-ic':''}" data-sort="${k}"`+
` title="Sort by ${label.toLowerCase()}" aria-label="Sort by ${label.toLowerCase()}">${icon||label}`+
`${on?`<span class="arr ${S.sort.dir}">${ICON.caret}</span>`:''}</button>`;
`${on?`<span class="arr ${now.dir}">${ICON.caret}</span>`:''}</button>`;
}).join('')+'<span></span></div>';
}
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};
// From a seasoned podcast's own order (#482), the first click is that column's first way round.
const now=sortFor(S.feed ?? '');
S.sort={col,dir:now.col===col?(now.dir==='asc'?'desc':'asc'):first};
sortPicked=true;
try{ localStorage.setItem('ipx.sort',JSON.stringify(S.sort)); }catch{}
S.offset=0; renderFeed(); loadEntries();
}
@@ -187,7 +196,7 @@ async function allAction(a: string){
const n=S.feeds.reduce((k,x)=>k+(x.unread||0),0);
if(!n){ toast('Nothing unread'); return; }
// One click across every feed is a lot to take back, so this one asks first.
if(!confirm(`Mark all ${n} unread item${n===1?'':'s'} read, in every feed you subscribe to?`)) return;
if(!await ask(`Mark all ${n} unread item${n===1?'':'s'} read, in every feed you subscribe to?`, 'Mark all read')) return;
try{
const r=await api('/api/read-all',{method:'POST'});
haptic('done'); toast(`Marked ${r.marked} read`); await loadFeeds(true); renderFeed(); loadEntries();

View File

@@ -20,12 +20,12 @@ async function loadFeeds(keepSel?: boolean){
// All Subscriptions rather than picking one alphabetically. Nothing to land on at all (a
// brand new account) leaves S.feed alone, so the empty state's own message shows instead.
if(!keepSel && S.feeds.length){
const known = S.feed && (VIEWS[S.feed] || S.feed===SIGNALS || signalOf(S.feed) || S.feeds.some(f=>f.id===S.feed));
const known = S.feed && (VIEWS[S.feed] || S.feed===SIGNALS || signalOf(S.feed) || S.feed===PLAYLISTS || playlistOf(S.feed) || S.feeds.some(f=>f.id===S.feed));
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.
// list's order by name (renderFeeds) still holds within each half.
const unreadFirst=(a: Feed,b: Feed)=>Number(b.unread>0)-Number(a.unread>0);
// The original's source list opened with these, above the feeds. They are places, not feeds:
// an id starting with ':' can never be a feed's, since feed ids are slugs.
@@ -34,6 +34,10 @@ const VIEWS: Record<string,{title: string, icon: string, url?: string, blurb?: s
':directory':{title:'Directory',icon:ICON.directory,url:'/api/directory'},
':listening':{title:'Currently Listening',icon:ICON.audio,url:'/api/entries?filter=in_progress&limit=50',
blurb:'Episodes you started and have not finished, across every feed you subscribe to. Pick one up where you left off.'},
':upnext':{title:'Up Next',icon:ICON.queue,url:'/api/queue',
blurb:'Episodes lined up to play, in order. Each one plays when the one before it ends.'},
// Drawn from the feed list the page already has; the address is only what marks it a place.
':podcasts':{title:'Podcasts',icon:ICON.podcasts,url:'/api/feeds'},
':all':{title:'All Subscriptions',icon:ICON.all},
};
/// Whether a feed's items are in All Subscriptions, or in Signals: not when it, or the OPML or
@@ -91,6 +95,9 @@ function spinEnd(done?: {only: string|null, forced: boolean}){
}
function renderFeeds(){
// By name, not the server's order, which is by id: a slug of the title, so The Rest Is Science
// was under T (#481). Here, so a feed a live update adds or renames takes its place too.
S.feeds.sort((a,b)=>nameOrder(a.title||a.id,b.title||b.id));
const q=$<HTMLInputElement>('#feedFilter').value.trim().toLowerCase();
const list=$('#feedlist'); const top=list.scrollTop;
// Every row is replaced, so put the keyboard back on the row, or the triangle, it was on.
@@ -116,7 +123,8 @@ function renderFeeds(){
el.className='place'+(S.feed===id?' sel':'');
el.tabIndex=0; el.dataset.id=id;
el.innerHTML=`<span class="ico">${v.icon}</span><b>${v.title}</b>`+(id===':all'
?`<span class="badge${unreadAll?'':' zero'}" title="${unreadAll} unread">${unreadAll>999?'999+':unreadAll}</span>`:'');
?`<span class="badge${unreadAll?'':' zero'}" title="${unreadAll} unread">${unreadAll>999?'999+':unreadAll}</span>`
:id===':upnext'&&upNext.length?`<span class="badge" title="${plural(upNext.length,'episode')}">${upNext.length}</span>`:'');
asLink(el,S.feed===id);
el.onclick=()=>{ selectFeed(id); nav(false); };
el.onpointerenter=el.ontouchstart=()=>prefetch(id);
@@ -124,6 +132,7 @@ function renderFeeds(){
}
list.appendChild(places);
signalFolder(list,q);
playlistFolder(list,q);
const shown=S.feeds.filter(f=>!q||(f.title||f.id).toLowerCase().includes(q));
if(!shown.length){ list.insertAdjacentHTML('beforeend','<p class="empty" style="padding:20px 8px">No feeds.</p>'); return done(); }
@@ -193,7 +202,7 @@ function renderFeeds(){
done();
}
function selectFeed(id: string){
S.feed=id; S.offset=0; S.sel=null; S.q=''; $<HTMLInputElement>('#epSearch').value='';
S.feed=id; S.offset=0; S.sel=null; S.q=''; S.season=''; sortPicked=false; $<HTMLInputElement>('#epSearch').value='';
try{ localStorage.setItem('ipx.feed',id); }catch{}
renderFeeds(); renderFeed(); loadEntries();
}

View File

@@ -118,6 +118,7 @@ function beside(dx: number){
/// beside it with it.
function slide(dx: number, ms = 160){
const d = $('#detail'); if(!d) return;
slidAt = Date.now();
dx = Math.round(dx); // whole pixels, or the seam between the reader and its neighbour blurs
const w = d.clientWidth || 1, tr = ms ? `transform ${ms}ms ease-out, opacity ${ms}ms ease-out` : 'none';
d.style.transition = tr;
@@ -148,7 +149,31 @@ function slideOn(dx: number, go: () => void){
const to = dir * (w + (beside(dx).className === 'dim' ? 0 : GAP));
const ms = still() ? 0 : Math.round(Math.max(120, 250 * (1 - Math.abs(dx) / (w || 1))));
slide(to, ms);
setTimeout(() => { go(); slide(0, 0); }, ms);
// The preview stays over the reader until the new item's pictures are drawn (#471): swapped at
// once, its text came a frame before the picture above it, and flashed where the picture would be.
setTimeout(() => { go(); drawn($('#detail'), 300).then(() => { if(!touch) slide(0, 0); }); }, ms);
}
/// The pictures of the items either side of the one open, fetched and decoded ahead (#471): the
/// preview a swipe draws is built as the drag begins, and its picture loaded only then came in
/// after its text, flashing and pushing the text down under the finger. Held here, so the browser
/// keeps them decoded; a few each, since only the top of an item shows in the preview.
let warm: HTMLImageElement[] = [];
function warmNeighbours(){
if(!narrow()) return;
const i = S.entries.findIndex(x => entryKey(x) === S.sel);
const html = [S.entries[i - 1], S.entries[i + 1]].filter(e => e).map(e => textOf(e!)).join('');
// Parsed, not put in the page: a document from DOMParser loads none of its pictures.
const srcs = [...new DOMParser().parseFromString(html, 'text/html').images].slice(0, 6).map(i => i.src);
warm = srcs.map(src => { const im = new Image(); im.src = src; im.decode().catch(() => {}); return im; });
}
/// When the pictures in `el` are decoded and ready to draw, or `max` ms, whichever is sooner, so a
/// slow picture never holds up the page.
function drawn(el: HTMLElement | null, max: number): Promise<unknown> {
const pending = [...el?.querySelectorAll('img') ?? []].filter(i => !i.complete || !i.naturalWidth);
if(!pending.length) return Promise.resolve();
return Promise.race([Promise.all(pending.map(i => i.decode().catch(() => {}))), new Promise(r => setTimeout(r, max))]);
}
document.addEventListener('touchend', () => {
@@ -181,7 +206,11 @@ document.addEventListener('touchcancel', () => { if(touch?.pane === 'list') pull
/// way, after which it has not moved. Watched by where the finger is, not by what it landed on,
/// so something lying over the reader is caught too, and named. Reported with what could hold it,
/// since the cause of the one in #383 was never found.
let drag: {x: number, y: number, top: number, on: string} | null = null, shownAt = Date.now();
// What #450's three reports could not say (#450): where the finger began, whether the page saw it
// move at all (none means the browser kept the drag for itself), whether the page cancelled the
// touch, and how long since the reader was last slid across, the one thing a swipe changes on it.
let drag: {x: number, y: number, top: number, on: string, moves: number, cancelled: boolean} | null = null,
shownAt = Date.now(), slidAt = 0;
document.addEventListener('visibilitychange', () => { if(!document.hidden) shownAt = Date.now(); });
const named = (el: Element | null) => !el ? 'nothing'
: el.id ? '#' + el.id : el.tagName.toLowerCase() + (typeof el.className === 'string' && el.className ? '.' + el.className.split(' ')[0] : '');
@@ -196,8 +225,11 @@ document.addEventListener('touchstart', ev => {
if(ev.touches.length !== 1 || !d || !S.sel) return;
const r = d.getBoundingClientRect();
if(t.clientX < r.left || t.clientX > r.right || t.clientY < r.top || t.clientY > r.bottom) return;
drag = {x: t.clientX, y: t.clientY, top: d.scrollTop, on: named(ev.target as Element)};
drag = {x: t.clientX, y: t.clientY, top: d.scrollTop, on: named(ev.target as Element), moves: 0, cancelled: false};
// After the swipe's own touchstart, which may cancel it, has run.
queueMicrotask(() => { if(drag) drag.cancelled = ev.defaultPrevented; });
}, {passive: true});
document.addEventListener('touchmove', () => { if(drag) drag.moves++; }, {passive: true});
document.addEventListener('touchend', ev => {
const d = $('#detail'), t = ev.changedTouches[0], g = drag;
drag = null;
@@ -211,5 +243,7 @@ document.addEventListener('touchend', ev => {
`inert ${inert || 'none'}`, `dialog ${$('#modal')?.classList.contains('on') ? 'open' : 'closed'}`,
`transform ${d.style.transform || 'none'}`, `peek ${$('#dpeek') ? 'left behind' : 'gone'}`,
`overflow ${getComputedStyle(d).overflowY}`, `reading ${document.body.classList.contains('reading')}`,
`shown ${Math.round((Date.now() - shownAt) / 1000)}s ago`, `${S.entries.length} loaded`].join(', ')});
`shown ${Math.round((Date.now() - shownAt) / 1000)}s ago`, `${S.entries.length} loaded`,
`from x ${Math.round(g.x)}`, `${g.moves} moves seen`, `touch ${g.cancelled ? 'cancelled' : 'left alone'}`,
`slid ${slidAt ? Math.round((Date.now() - slidAt) / 1000) + 's ago' : 'never'}`].join(', ')});
});

View File

@@ -14,10 +14,13 @@ const lists=new Map<string,ListPage>();
const LISTS_KEPT=40;
/// Lists on their way, so a click on one already being fetched ahead waits for that answer.
const fetching=new Map<string,Promise<ListPage>>();
const listKey=(feed: string, filter=S.filter)=>[feed,filter,S.sort.col,S.sort.dir,S.q].join('\n');
// A season is of the podcast open (#482): another feed's list, fetched ahead, is of every season.
const seasonFor=(feed: string)=>feed===S.feed?S.season:'';
const listKey=(feed: string, filter=S.filter)=>[feed,filter,sortFor(feed).col,sortFor(feed).dir,S.q,seasonFor(feed)].join('\n');
function listUrl(feed: string, filter=S.filter, offset=0){
const p=new URLSearchParams({offset:String(offset),limit:String(LIMIT),filter,sort:S.sort.col,dir:S.sort.dir});
const p=new URLSearchParams({offset:String(offset),limit:String(LIMIT),filter,sort:sortFor(feed).col,dir:sortFor(feed).dir});
if(S.q) p.set('q',S.q);
if(seasonFor(feed)) p.set('season',seasonFor(feed));
const sg=signalId(feed);
return feed===':all' ? `/api/entries?${p}`
: sg!==null ? `/api/signals/${sg}/entries?${p}`
@@ -78,7 +81,7 @@ function preloadLists(){
/// `quiet` for a refresh nobody asked for (a live update): not a wait anyone sees, so not timed.
async function loadEntries(append?: boolean, quiet?: boolean){
// The Directory lists feeds, and Currently Listening draws its own episodes.
if(!S.feed || VIEWS[S.feed]?.url || S.feed===SIGNALS) return;
if(!S.feed || VIEWS[S.feed]?.url || S.feed===SIGNALS || S.feed===PLAYLISTS || playlistOf(S.feed)) return;
const feed=S.feed, key=listKey(feed), asked=performance.now(), seq=++loadSeq;
// From asking to the list drawn: what someone waits for after a click, under that click's trace
// (#246). Once, when the list first shows: from what is kept, at once.
@@ -129,6 +132,7 @@ function showList(r: ListPage, append: boolean, asked: number){
const back=append ? null : takeReopen();
if(back && !entries.some(e=>entryKey(e)===entryKey(back))) entries=[back,...entries];
S.entries = entries;
followWantedIn(entries);
renderEntries();
if(back){ const e=S.entries.find(x=>entryKey(x)===entryKey(back)); if(e) selectEntry(e); }
}
@@ -142,7 +146,7 @@ function renderEntries(){
const f=S.feeds.find(x=>x.id===S.feed), v=VIEWS[S.feed ?? ''], sg=signalOf(S.feed);
// An OPML's own row counts nothing: its shows do.
const kids=f?S.feeds.filter(c=>c.group===f.id):[];
const unread=kids.length?kids.reduce((n,x)=>n+x.unread,0):f?f.unread:sg?sg.unread:S.feeds.reduce((n,x)=>n+(x.unread||0),0);
const unread=kids.length?kids.reduce((n,x)=>n+x.unread,0):f?(seasonUnread(f.id)??f.unread):sg?sg.unread:S.feeds.reduce((n,x)=>n+(x.unread||0),0);
$('#count').textContent=
`${f?(f.title||f.id):sg?sg.name:v?v.title:''}: ${S.total} item${S.total===1?'':'s'}, ${unread} unread`;
const pane=$('#list'), top=pane?pane.scrollTop:0;
@@ -154,7 +158,14 @@ function renderEntries(){
else if(sg&&S.filter==='all') box.innerHTML='<p class="empty">Nothing has come through yet. New items are read as your feeds are checked.</p>';
return;
}
for(const e of S.entries) box.appendChild(epEl(e));
const breaks=seasonBreaks();
let last: number|null|undefined;
S.entries.forEach((e,i)=>{
if(breaks&&(i===0||(e.season??null)!==(last??null)))
box.insertAdjacentHTML('beforeend',`<div class="sdiv" role="heading" aria-level="3">${seasonName(e.season)}</div>`);
last=e.season;
box.appendChild(epEl(e));
});
syncPlayButtons();
if(pane) pane.scrollTop=top;
if(hasMore()){
@@ -206,6 +217,7 @@ function epEl(e: Entry){
<span class="size">${enc?mb(enc.length):''}</span>
<span class="date">${dateOf(e.published)}</span>
<div class="rowacts">
${enc&&playsKind(enc)?queueButton(e):''}
${playable?`<button class="iconbtn" data-a="play" title="Play" aria-label="Play">${ICON.play}</button>`:
(enc&&!has?`<button class="iconbtn" data-a="get" title="Download this ${
enc.state==='skipped'?kindOf(enc):'file'}">${ICON.download}</button>`:'')}
@@ -219,7 +231,10 @@ function epEl(e: Entry){
/// blog feeds put article images in enclosures, and an <audio> element pointed at a JPEG
/// is just a broken player.
function isPlayable(x: Enclosure|undefined){
if(!x || !x.path) return false;
return !!x && !!x.path && playsKind(x);
}
/// Whether a file is audio or video, wherever it is: one not downloaded yet too.
function playsKind(x: {mime?: string|null, path?: string|null, url?: string}){
const m=(x.mime||'').toLowerCase();
if(m.startsWith('audio/')||m.startsWith('video/')) return true;
if(m) return false;
@@ -331,6 +346,7 @@ function selectEntry(e: Entry,turning=false){
showDetail(e);
const d=$('#detail'); if(d) d.scrollTop=0;
if(turning) loadAhead();
warmNeighbours();
}
/// Where the next page starts. On the Unread tab the items read here are no longer unread on the
@@ -434,6 +450,7 @@ function detailHtml(e: Entry){
aria-label="Mark ${e.read?'unread':'read'}" aria-pressed="${!!e.read}">${e.read?ICON.check:ICON.unread}</button>
<button class="btn ico" data-a="flag" title="${e.flagged?'Pinned: never deleted. Unpin':'Pin, so it is never deleted'}"
aria-label="${e.flagged?'Unpin':'Pin'}" aria-pressed="${!!e.flagged}">${e.flagged?ICON.pinOn:ICON.pin}</button>
${e.enclosures.some(playsKind)?queueButton(e,'btn ico'):''}
${webUrl(e.link)?`<a class="btn ico" href="${esc(webUrl(e.link))}" target="_blank" rel="noopener noreferrer"
title="Open the original" aria-label="Open the original">${ICON.open}</a>
<button class="btn ico" data-a="share" title="Share" aria-label="Share">${ICON.share}</button>`:''}</span>`;
@@ -467,59 +484,88 @@ function textOf(e: Entry){
return (e.description&&e.description.trim())||'<em>No show notes.</em>';
}
/// One enclosure: a play button when the file is here, otherwise what it is and a way to get it.
/// Where a file is, in the words its box says it in (#457): the publisher's alone, on its way to
/// iPX, on iPX, on this device as well.
function whereText(x: Enclosure){
const here=isKept(x), busy=keeping.has(keepUrl(x));
if(!x.path){
if(here) return 'On this device';
if(wanted.has(x.id)) return 'Downloading to iPX, then this device';
if(x.state==='pending') return 'Queued for iPX';
if(x.state==='error') return 'iPX could not download it';
return 'Publisher only';
}
return here ? 'On iPX and this device' : busy ? 'On iPX, downloading to this device' : 'On iPX';
}
/// Whether ⬇ ends on this device: a phone or the app, where the file is wanted in the hand, for a
/// file this device can play offline. A computer's ⬇ has iPX fetch it and saves a copy.
const toDevice=(x: Enclosure)=>canKeep() && playsKind(x)
&& (!!ipxHost || !!window.matchMedia?.('(max-width:820px)')?.matches);
/// One enclosure (#457): what it is, where it is, and one button that brings it to where you are.
/// Everything else, rarer and two of it destructive, is under ⋯.
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);
const shared=f&&f.subscribers>1;
// Icons, with the words in the tooltip and for screen readers.
const delLabel=shared
? `Delete for everyone (shared with ${f.subscribers-1} other ${f.subscribers===2?'person':'people'} reading this feed)`
: 'Delete file';
const delBtn=`<button class="btn ico danger" data-a="del" data-enc="${x.id}" title="${delLabel}" aria-label="${delLabel}">${ICON.trash}</button>`;
const btn=(a: string, label: string, icon: string, extra='')=>
`<button class="btn ico" data-a="${a}" data-enc="${x.id}" title="${label}" aria-label="${label}"${extra}>${icon}</button>`;
// Played without its dead air, so saved without it too (#186).
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)){
// On disk, but not audio or video: view it, keep it, or remove it -- no player.
return `<div class="encbox">
${kindIcon(x)}
<span class="meta" style="flex:1">${size}</span>
<a class="btn ico" href="/media/${x.id}" target="_blank" rel="noopener noreferrer" title="View in a new tab" aria-label="View in a new tab">${ICON.open}</a>
${saveBtn}
${shareBtn}
${delBtn}
</div>`;
}
if(x.path){
// One player, the bar at the bottom. This pane had an <audio> of its own, and playing it
// started the bar as well, so the same file played twice at once.
return `<div class="encbox">
${kindIcon(x)}
<span class="meta" style="flex:1">${size}</span>
<button class="btn ico" data-a="play" data-enc="${x.id}" title="Play" aria-label="Play">${ICON.play}</button>
${keepBtn(x)}
${saveBtn}
${shareBtn}
${delBtn}
</div>`;
}
// Nothing on disk. For an image or a PDF you usually just want to look at it, so link
// straight to the publisher's copy in a new tab -- no download, and nothing proxied
// through here, which would make ipx a fetch-anything relay.
const viewable = !!webUrl(x.url) && !isPlayable(x) && x.state !== 'pending' && x.state !== 'held';
let get='';
if(toDevice(x)){
const url=keepUrl(x);
get=isKept(x) ? btn('more', 'On this device. More', ICON.kept, ' aria-pressed="true"')
: keeping.has(url) ? btn('offline', 'Downloading to this device', ICON.download, ` data-url="${url}" aria-busy="true"`)
: wanted.has(x.id) ? btn('want', 'Downloading to iPX, then this device', ICON.download, ' aria-busy="true"')
: x.path ? btn('offline', 'Download to this device', ICON.download, ` data-url="${url}"`)
: btn('want', 'Download to this device', ICON.download);
}else if(x.path){
const label=dead?'Save a copy to this computer, without its dead air':'Save a copy to this computer';
get=`<a class="btn ico" href="/media/${x.id}${dead?'/deadair':''}" download title="${label}" aria-label="${label}">${ICON.download}</a>`;
}else if(x.state!=='pending') get=btn('get', 'Download to iPX', ICON.download);
// Nothing on disk, an image or a PDF: you usually just want to look at it, so the publisher's
// copy in a new tab, nothing proxied through here, which would make ipx a fetch-anything relay.
const view=x.path && !isPlayable(x) ? `/media/${x.id}`
: !x.path && !!webUrl(x.url) && !isPlayable(x) && x.state!=='pending' && x.state!=='held' ? x.url : '';
// One player, the bar at the bottom. This pane had an <audio> of its own, and playing it
// started the bar as well, so the same file played twice at once.
return `<div class="encbox">
${kindIcon(x)}
<span class="meta" style="flex:1">${size}</span>
${x.state==='error'&&x.last_error?`<span class="err">${esc(x.last_error)}</span>`:''}
${viewable?`<a class="btn ico" href="${esc(x.url)}" target="_blank" rel="noopener noreferrer" title="View in a new tab" aria-label="View in a new tab">${ICON.open}</a>`:''}
${shareBtn}
<button class="btn ico" data-a="get" data-enc="${x.id}" title="Download to the server" aria-label="Download to the server">${ICON.download}</button>
</div>`;
${kindIcon(x)}
<span class="meta" style="flex:1">${[size, whereText(x)].filter(Boolean).join(' · ')}</span>
${x.state==='error'&&x.last_error&&!x.path?`<span class="err">${esc(x.last_error)}</span>`:''}
${x.path&&isPlayable(x)?btn('play', 'Play', ICON.play):''}
${view?`<a class="btn ico" href="${esc(view)}" target="_blank" rel="noopener noreferrer" title="View in a new tab" aria-label="View in a new tab">${ICON.open}</a>`:''}
${get}
${/* The publisher's address, not this server's copy, which only someone signed in here can open. */''}
${btn('share', 'Share the file', ICON.share)}
${fileMenuItems(x).length?btn('more', 'More', ICON.more):''}
</div>`;
}
/// What ⋯ offers for a file: whatever its one button does not.
function fileMenuItems(x: Enclosure): [string, string, string][]{
const items: [string, string, string][]=[];
const device=toDevice(x);
if(isKept(x)) items.push(['offline', 'Remove from this device', '']);
else if(!device && canKeep() && isPlayable(x) && x.path && !keeping.has(keepUrl(x)))
items.push(['offline', 'Download to this device, to play offline', '']);
if(device && !x.path && x.state!=='pending' && !wanted.has(x.id)) items.push(['get', 'Download to iPX only', '']);
if(x.path){
// 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);
items.push(['del', f&&f.subscribers>1
? `Delete from iPX, for everyone (shared with ${f.subscribers-1} other ${f.subscribers===2?'person':'people'} reading this feed)`
: 'Delete from iPX', ' danger']);
}
return items;
}
function fileMenu(e: Entry, x: Enclosure){
openModal(`<button class="iconbtn cardx" onclick="closeModal()" title="Close" aria-label="Close">${ICON.close}</button>
<h3>${esc(entryName(e).text)}</h3><p class="hint">${esc(whereText(x))}</p>
<div class="sharemenu">${fileMenuItems(x).map(([a,label,cls])=>
`<button class="btn${cls}" data-m="${a}">${esc(label)}</button>`).join('')}</div>`);
$$<HTMLButtonElement>('#modalCard [data-m]').forEach(b=>b.onclick=()=>{ closeModal(); epAction(b.dataset.m!, e, null, x.id); });
}
/// A shared link that starts at a time (#447): ipx-play's page reads `?t=` in seconds. Under five
@@ -561,7 +607,7 @@ async function shareEpisode(e: Entry, encId: number|null){
const at=!link.url ? 0 : player.guid===e.guid && player.feed===e.feed_id ? audio.currentTime : e.position;
// A menu rather than the share sheet at once, for the item's own address too: the sheet needs a
// press of its own, and the request above has used up the one that opened this (#452). The
// warning is written here, not asked with confirm(), which the iOS app answers Cancel (#453).
// warning is written here, not asked first, since it is in the menu anyway.
openModal(`<button class="iconbtn cardx" onclick="closeModal()" title="Close" aria-label="Close">${ICON.close}</button>
<h3>Share</h3><p class="hint">${esc(name)}</p>
${link.url ? '' : noLinkNote(link.why, url)}
@@ -592,28 +638,34 @@ async function epAction(a: string, e: Entry, el: HTMLElement|null, encId?: numbe
try{
if(a==='play'){ haptic('tap'); play(e, encId!=null ? enc : undefined); }
if(a==='offline' && enc) await toggleKept(enc, entryName(e).text);
if(a==='queue'||a==='playnext'){ haptic('tap'); await toggleQueued(e, a==='playnext'); }
if(a==='share') await shareEpisode(e, encId??null);
if(a==='flag'){ e.flagged=!e.flagged; await api(path+'/flags',{method:'POST',body:JSON.stringify({flagged:e.flagged})}); haptic('tap'); redraw(); }
if(a==='read'){ await setRead(e,!e.read); haptic(e.read?'done':'tap'); redraw(); }
if(a==='get'){
if(a==='more' && enc) fileMenu(e, enc);
if(a==='get' || a==='want'){
if(!enc) return;
await api(`/api/enclosures/${enc.id}/download`,{method:'POST'});
toast('Queued: '+entryName(e).text);
enc.state='pending';
// Wanted here too: the device's copy follows once iPX has the file (#457).
if(a==='want'){ want(enc.id, entryName(e).text); toast('Downloading: '+entryName(e).text+'. It comes to this device once iPX has it.'); }
else toast('Queued: '+entryName(e).text);
redraw();
}
if(a==='del'){
const f=S.feeds.find(x=>x.id===e.feed_id);
const shared=f&&f.subscribers>1;
if(!confirm(shared
? `Delete this file?\n\nThere is one copy, shared with ${f.subscribers-1} other `
if(!await ask(shared
? `Delete this file? There is one copy, shared with ${f.subscribers-1} other `
+`${f.subscribers===2?'person':'people'} reading this feed. The item stays listed `
+`and will not be downloaded again automatically.`
: 'Delete the downloaded file?\n\nThe item stays listed and will not be downloaded again automatically.')) return;
: 'Delete the downloaded file? The item stays listed and will not be downloaded again automatically.', 'Delete')) return;
try{
await api(`/api/enclosures/${enc.id}`,{method:'DELETE'});
}catch(err){
// 409: somebody else has it starred or unplayed. Their reason, their words.
if(!/one copy of this file/.test(why(err))) throw err;
if(!confirm(why(err)+'\n\nDelete it anyway?')) return;
if(!await ask(why(err), 'Delete it anyway')) return;
await api(`/api/enclosures/${enc.id}?force=true`,{method:'DELETE'});
}
toast('Deleted'); loadEntries(); loadFeeds(true);

View File

@@ -115,6 +115,14 @@ function wireDeviceSettings(){
$<HTMLButtonElement>('#sptokenclear').onclick=()=>host({t:'clearToken'});
}
/// An episode as the phone's player takes it, to play now (`load`) or after this one (`next`).
function hostItem(e: Entry|null, enc: {id: number}, url: string){
return {url, enc:enc.id, feedId:e?.feed_id ?? player.feed, guid:e?.guid ?? player.guid,
title:e ? entryName(e).text : '', feedTitle:feedName(e?.feed_id ?? player.feed),
artwork:(e && e.image) || feedArt(e?.feed_id ?? player.feed) || null,
position:(e && e.position) || 0, duration:(e && e.duration) || null};
}
function installNativePlayback(){
const post = ipxHost!;
const M = HTMLMediaElement.prototype;
@@ -165,15 +173,10 @@ function installNativePlayback(){
realPause.call(audio);
realRemoveAttribute('src');
realLoad.call(audio);
const e = player.entry, f = player.feed;
post({t:'load', url:v, enc:player.enc, feedId:f, guid:player.guid,
title:e ? entryName(e).text : '', feedTitle:feedName(f),
artwork:(e && e.image) || feedArt(f) || null,
// Where the host starts is not this: the seek to where you left off is player.ts's, on
// loadedmetadata, so one piece of code decides it. This is for the host's now-playing
// display before the file has loaded.
position:(e && e.position) || 0, duration:(e && e.duration) || null,
rate:audio.playbackRate, volume:audio.volume});
// Where the host starts is not the position in it: the seek to where you left off is
// player.ts's, on loadedmetadata, so one piece of code decides it. That is for the host's
// now-playing display before the file has loaded.
post({t:'load', ...hostItem(player.entry, {id:player.enc!}, v), rate:audio.playbackRate, volume:audio.volume});
},
});
@@ -222,6 +225,9 @@ function installNativePlayback(){
// Not moved: nothing here played it, so there is no place of the page's own to save.
player.guid=m.guid; player.feed=m.feedId; player.entry=e; player.enc=m.enc;
player.src=enc?mediaSrc(enc):undefined; player.moved=false; player.marked=false; player.saveAt=m.cur||0;
// The phone went on to the next in Up Next by itself (#473): it is under way, so out of it.
const was=upNext.find(x=>x.guid===m.guid&&x.feed_id===m.feedId);
if(was){ player.entry=e||was; startedPlaying(was); }
$('#partwrap').innerHTML=artHTML(m.artwork||feedArt(m.feedId),feedName(m.feedId));
$('#ptitle').textContent=m.title||'';
$('#pfeed').textContent=m.feedTitle||'';
@@ -235,6 +241,7 @@ function installNativePlayback(){
fire(m.playing ? 'play' : 'pause');
renderEntries();
syncListening();
drawNow();
}
function stop(){
@@ -262,7 +269,7 @@ function installNativePlayback(){
// Not playback's, so not gated on it: the app says what it keeps whether or not it plays.
if(m.t==='kept'||m.t==='keepFailed'){ hostKept(m); return; }
// Sent at ready, so a page newer than the app offers only what the app can do.
if(m.t==='host'){ hostCan.clear(); for(const c of m.can||[]) hostCan.add(c); paintRoute(); return; }
if(m.t==='host'){ hostCan.clear(); for(const c of m.can||[]) hostCan.add(c); paintRoute(); hostNext(); return; }
if(m.t==='sleep'||m.t==='slept'){ hostSleep(m); return; }
if(m.t==='push'){ hostPush(m); return; }
if(m.t==='appSettings'){ hostAppSettings(m); return; }

46
web/src/nowplaying.ts Normal file
View File

@@ -0,0 +1,46 @@
/* ---------------- Now Playing ---------------- */
/// Now Playing (#475): what is playing, opened from the player bar. Its artwork large, the
/// podcast it is from, its show notes and what follows in Up Next. The bar stays below it with
/// the controls, so there is one set of them, not a second to keep in step.
const nowSheet=$('#nowsheet');
const nowOpen=()=>!nowSheet.hidden;
function openNow(){
if(!player.guid) return;
nowSheet.hidden=false;
$('#pnow').setAttribute('aria-expanded','true');
drawNow();
$<HTMLButtonElement>('#nowclose').focus();
}
function closeNow(){
if(!nowOpen()) return;
nowSheet.hidden=true;
$('#pnow').setAttribute('aria-expanded','false');
$('#pnow').focus();
}
/// Drawn again whenever what plays or what follows changes, while it is open.
function drawNow(){
const e=player.entry;
if(!nowOpen()) return;
if(!e||!player.guid){ closeNow(); return; }
const name=entryName(e).text, show=feedName(e.feed_id);
nowSheet.innerHTML=`
<button class="iconbtn" id="nowclose" title="Close Now Playing (Esc)" aria-label="Close Now Playing">${ICON.close}</button>
<div class="nowhead">
${artHTML(e.image||feedArt(e.feed_id),show,'nowart')}
<div class="nowmeta">
<h2>${esc(name)}</h2>
<button type="button" class="nowshow">${esc(show)}</button>
<small>${[dateOf(e.published),e.duration?clock(e.duration):''].filter(Boolean).join(', ')}</small>
</div>
</div>
${upNext.length?`<h3>Up Next</h3><div class="childlist" id="nowqueue"></div>`:''}
<h3>Show notes</h3>
<div class="dbody">${textOf(e)}</div>`;
$<HTMLButtonElement>('#nowclose').onclick=closeNow;
$<HTMLButtonElement>('.nowshow',nowSheet).onclick=()=>{ closeNow(); selectFeed(e.feed_id); };
const q=$('#nowqueue');
for(const x of upNext) q?.appendChild(listenRow(x,'Remove from Up Next',()=>saveUpNext(upNext.filter(y=>entryKey(y)!==entryKey(x)))));
}
$('#pnow').onclick=()=>nowOpen()?closeNow():openNow();
$('#pnow').onkeydown=(ev: KeyboardEvent)=>{ if(ev.key==='Enter'||ev.key===' '){ ev.preventDefault(); $('#pnow').click(); } };

View File

@@ -46,24 +46,41 @@ if(worker) (async()=>{
try{ for(const k of await (await caches.open(KEPT)).keys()) kept.add(new URL(k.url).pathname); }catch{}
if(kept.size) syncKeepButtons();
})();
/// The open item's files say where each is, and its button what it does next (#457): drawn again
/// in place, keeping the reader where it was.
function syncKeepButtons(){
document.querySelectorAll<HTMLButtonElement>('[data-a="offline"]').forEach(b=>{
const k=kept.has(b.dataset.url!);
b.setAttribute('aria-pressed',String(k));
b.setAttribute('aria-busy',String(keeping.has(b.dataset.url!)));
b.innerHTML=k?ICON.kept:ICON.keep;
const label=k?'Kept on this device to play offline. Remove it':'Keep on this device to play offline';
b.title=label; b.setAttribute('aria-label',label);
}); // A row says whether its item is kept; redrawn only where that has changed.
const e=cur();
if(e && $('#files .encbox, #detail .encbox')){
const box=$('#detail'), top=box?.scrollTop??0;
showDetail(e);
if(box) box.scrollTop=top;
}
// A row says whether its item is kept; redrawn only where that has changed.
for(const e of S.entries)
if(e.enclosures.some(isKept)!==!!$(`#eps .ep[data-key="${CSS.escape(entryKey(e))}"] .kept`)) swapRow(e);
}
/// The button for a file on the server that plays; none without a worker, or an app, to play it
/// offline.
function keepBtn(x: Enclosure){
if(!worker&&!ipxHost) return '';
const k=isKept(x), label=k?'Kept on this device to play offline. Remove it':'Keep on this device to play offline';
return `<button class="btn ico" data-a="offline" data-enc="${x.id}" data-url="${keepUrl(x)}" aria-pressed="${k}" aria-busy="${keeping.has(keepUrl(x))}" title="${label}" aria-label="${label}">${k?ICON.kept:ICON.keep}</button>`;
/// Whether this device can keep a file to play offline: a worker to keep it, or the app.
const canKeep=()=>!!worker||!!ipxHost;
/* Files asked for on this device before iPX had them (#457): iPX fetches each, and its copy here
follows once iPX says it is done, or, when the page was closed meanwhile, the next time a list
shows it with its file. Kept in localStorage, so a closed app still remembers. */
const wanted=new Map<number,string>();
try{ for(const [id,name] of JSON.parse(localStorage.getItem('ipx.wanted')||'[]') as [number,string][]) wanted.set(id,name); }catch{}
function saveWanted(){ try{ localStorage.setItem('ipx.wanted',JSON.stringify([...wanted])); }catch{} }
function want(id: number, name: string){ wanted.set(id,name); saveWanted(); }
function unwant(id: number){ if(wanted.delete(id)) saveWanted(); }
/// iPX has the file now: this device's copy follows. The copy without dead air comes later, if it
/// does, so the file itself is what is kept.
function followWanted(x: {id: number, path?: string|null, deadair?: number|null}){
const name=wanted.get(x.id);
if(name==null || !x.path) return;
unwant(x.id);
if(!isKept(x)) void toggleKept(x as Enclosure, name);
}
/// Those of `entries` iPX fetched while this page was not looking.
function followWantedIn(entries: Entry[]){
if(!wanted.size) return;
for(const e of entries) for(const x of e.enclosures) if(x.path && wanted.has(x.id)) followWanted(x);
}
async function toggleKept(x: Enclosure, name: string){
const url=keepUrl(x);

View File

@@ -72,6 +72,7 @@ function play(e: Entry,enc=e.enclosures.find(isPlayable)){
let wait: Promise<void>|null=null;
if(!resuming){
player.guid=e.guid; player.feed=e.feed_id; player.entry=e; player.enc=enc.id; player.moved=false;
playingFrom=null;
document.body.classList.toggle('has-video', kindOf(enc)==='video');
wait=setSrc(player.src=mediaSrc(enc));
audio.currentTime=0;
@@ -85,6 +86,9 @@ function play(e: Entry,enc=e.enclosures.find(isPlayable)){
mediaSession(e,f);
player.marked=false;
paintDead();
startedPlaying(e);
hostNext();
drawNow();
}
const go=()=>audio.play().catch(playFailed);
if(wait) wait.then(go,playFailed); else go();
@@ -97,7 +101,7 @@ function mediaSession(e: Entry,f: Feed|undefined){
artwork:(e.image||(f&&f.image))?[{src:artSrc((e.image||f?.image)!),sizes:'512x512'}]:[],
});
const h: Record<string,()=>void>={play:()=>audio.play(),pause:()=>audio.pause(),
seekbackward:()=>audio.currentTime-=15,seekforward:()=>audio.currentTime+=30};
seekbackward:()=>audio.currentTime-=15,seekforward:()=>audio.currentTime+=30,nexttrack:playNext};
for(const k in h){ try{navigator.mediaSession.setActionHandler(k as MediaSessionAction,h[k])}catch{} }
}
audio.addEventListener('timeupdate',()=>{
@@ -136,7 +140,7 @@ function savePos(){
deadair:player.src?.includes('/deadair')?player.enc:undefined})],{type:'application/json'}));
}
audio.addEventListener('pause',savePos);
audio.addEventListener('ended',()=>{savePos();markPlayed();$<HTMLButtonElement>('#pplay').innerHTML=ICON.play});
audio.addEventListener('ended',()=>{savePos();markPlayed();$<HTMLButtonElement>('#pplay').innerHTML=ICON.play;playNext()});
// body.playing is what sets the EQ bars moving.
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'); });
@@ -175,6 +179,7 @@ audio.addEventListener('error',()=>{ if(audio.error) report('player_error',{msg:
$<HTMLButtonElement>('#pplay').onclick=()=>{haptic('tap');audio.paused?audio.play():audio.pause()};
$<HTMLButtonElement>('#pback').onclick=()=>audio.currentTime-=15;
$<HTMLButtonElement>('#pfwd').onclick=()=>audio.currentTime+=30;
$<HTMLButtonElement>('#pnext').onclick=()=>{ if(!playNext()) toast('Nothing in Up Next is ready to play.'); };
$<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)};
/// What the app said it can do itself (`{t:'host', can}`, native.ts): empty in a browser, and in
@@ -276,7 +281,7 @@ async function switchVersion(){
if(was) (wait||Promise.resolve()).then(()=>audio.play()).catch(()=>{});
return true;
}
$<HTMLButtonElement>('#pclose').onclick=()=>{if(sleepAt)sleepIn(0);savePos();audio.pause();dropHls();audio.removeAttribute('src');player.guid=null;$('#player').classList.remove('on');document.body.classList.remove('has-video');renderEntries();
$<HTMLButtonElement>('#pclose').onclick=()=>{closeNow();if(sleepAt)sleepIn(0);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(){
@@ -288,7 +293,7 @@ $<HTMLButtonElement>('#pclose').onclick=()=>{if(sleepAt)sleepIn(0);savePos();aud
document.addEventListener('keydown',ev=>{
// Escape leaves a dialog even from inside one of its boxes. It used to sit below the check
// that follows, so Add feed, which opens with the cursor in its URL box, ignored it.
if(ev.key==='Escape'){closeModal();nav(false);return}
if(ev.key==='Escape'){closeModal();nav(false);closeNow();return}
// The rest are single keys that would otherwise eat what you type.
if(/^(INPUT|TEXTAREA|SELECT)$/.test((ev.target as Element).tagName)) return;
if(ev.key===' '&&player.guid){ev.preventDefault();audio.paused?audio.play():audio.pause()}
@@ -301,7 +306,7 @@ document.addEventListener('keydown',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: Record<string,string>={a:':all',d:':directory',l:':listening'};
const GO: Record<string,string>={a:':all',d:':directory',l:':listening',u:':upnext'};
let gAt=0;
function stepEntry(by: number){
if(VIEWS[S.feed ?? '']?.url||!S.entries.length) return;
@@ -318,10 +323,12 @@ function stepFeed(by: number){
}
const KEYS: Record<string,()=>void>={
j:()=>stepEntry(1), n:()=>stepEntry(1), k:()=>stepEntry(-1), p:()=>stepEntry(-1),
J:()=>stepFeed(1), K:()=>stepFeed(-1),
J:()=>stepFeed(1), K:()=>stepFeed(-1), N:()=>$<HTMLButtonElement>('#pnext').click(),
// The toolbar's own buttons, so a key does exactly what the click does, and nothing while
// they are disabled.
o:()=>$<HTMLButtonElement>('#tbPlay').click(), m:()=>$<HTMLButtonElement>('#tbRead').click(), s:()=>$<HTMLButtonElement>('#tbFlag').click(),
o:()=>$<HTMLButtonElement>('#tbPlay').click(),
q:()=>{ const e=cur(); if(e) epAction('queue',e,null); }, Q:()=>{ const e=cur(); if(e) epAction('playnext',e,null); },
m:()=>$<HTMLButtonElement>('#tbRead').click(), s:()=>$<HTMLButtonElement>('#tbFlag').click(),
v:()=>{ const u=webUrl(cur()?.link); if(u) window.open(u,'_blank','noopener'); },
A:()=>$('#content .fhead [data-a="read"], #content .fhead [data-a="readall"]')?.click(),
r:async()=>{ await loadFeeds(true); if(S.feed){ renderFeed(); loadEntries(); } },
@@ -343,17 +350,17 @@ function keysModal(){
const rows=[
['Go to'],
[g('a'),'All Subscriptions'],[g('d'),'Directory'],
[g('l'),'Currently Listening'],[g('s'),'Settings'],
[g('u'),'Up Next'],[g('l'),'Currently Listening'],[g('s'),'Settings'],
[k('Shift')+' '+k('J'),'Next feed'],[k('Shift')+' '+k('K'),'Previous feed'],
[k('/'),'Search items, Currently Listening or the Directory'],[k('r'),'Refresh'],[k('['),'Show or hide the feed list'],
['Items'],
[k('j')+' or '+k('n'),'Next item'],[k('k')+' or '+k('p'),'Previous item'],
[k('Shift')+' '+k('A'),'Mark all read'],
['The selected item'],
[k('o'),'Play it'],[k('m'),'Mark it read or unread'],[k('s'),'Pin it, or unpin it'],
[k('o'),'Play it'],[k('q'),'Add it to Up Next, or take it out'],[k('Shift')+' '+k('Q'),'Play it next'],[k('m'),'Mark it read or unread'],[k('s'),'Pin it, or unpin it'],
[k('v'),'Open the original in a new tab'],
['The player'],
[k('Space'),'Play or pause'],[k('←')+' '+k('→'),'Back 15 seconds, forward 30'],
[k('Space'),'Play or pause'],[k('←')+' '+k('→'),'Back 15 seconds, forward 30'],[k('Shift')+' '+k('N'),'Play the next in Up Next'],
['Anywhere'],
[k('?'),'This list'],[k('Esc'),'Close a dialog'],
];

163
web/src/playlists.ts Normal file
View File

@@ -0,0 +1,163 @@
/* ---------------- smart playlists ---------------- */
/// Smart playlists (#476): the episodes of the podcasts chosen, those marked to play first ahead of
/// the rest, newest or oldest first, unplayed only or all. A playlist is a place, `:playlist:<id>`,
/// in a folder of their own in the feed list, as Signals are.
const PLAYLISTS=':playlists';
let playlists: Playlist[]=[];
/// The playlist the episode playing was started from, which goes on to its next when it ends, once
/// Up Next has nothing.
let playingFrom: Entry[]|null=null;
function playlistOf(view: string|null){
const m=/^:playlist:(\d+)$/.exec(view||'');
return m ? playlists.find(p=>p.id===Number(m[1])) : undefined;
}
function loadPlaylists(){
return api('/api/playlists').then((r: Playlist[])=>{ playlists=r; renderFeeds(); }).catch(()=>{});
}
/// The playlist's own art: its podcasts' artwork, four together, as a folder's is.
const playlistArt=(p: Playlist)=>folderArt({id:'',title:p.name,image:null} as Feed,S.feeds.filter(f=>p.feeds.includes(f.id)));
function playlistFolder(list: HTMLElement, q: string){
const mine=playlists.filter(p=>!q||p.name.toLowerCase().includes(q));
if(q&&!mine.length) return;
const open=expanded.has(PLAYLISTS)||!!q;
list.appendChild(feedRow(PLAYLISTS,'plists',
`<button class="chev" aria-expanded="${open}" title="Show or hide your playlists" aria-label="Show or hide your playlists">${ICON.caret}</button>`+
`<span class="fart"><div class="art">${ICON.queue}</div></span><div class="txt"><b>Playlists</b><small>${playlists.length?plural(playlists.length,'playlist'):'Episodes from the podcasts you choose'}</small></div>`,
()=>selectFeed(PLAYLISTS)));
$('.chev',list.lastElementChild!).onclick=(ev: Event)=>{ ev.stopPropagation(); toggleGroup(PLAYLISTS); };
if(!open) return;
for(const p of mine)
list.appendChild(feedRow(':playlist:'+p.id,'child',
`<span class="fart">${playlistArt(p)}</span><div class="txt"><b>${esc(p.name)}</b><small>${plural(p.feeds.length,'podcast')}</small></div>`+badgeHTML(p.items),
()=>selectFeed(':playlist:'+p.id)));
}
/// The folder's page: every playlist, and New playlist.
function renderPlaylists(){
$('#count').textContent=`Playlists: ${plural(playlists.length,'playlist')}`;
$<HTMLButtonElement>('#tbRemove').disabled=true;
syncTools(null);
const box=$('#content');
box.classList.add('plain');
box.innerHTML=`
<div class="fhead slim">
<div class="art">${ICON.queue}</div>
<div class="meta"><h2>Playlists</h2><div class="sub">Episodes from the podcasts you choose, kept up to date as new ones come.</div></div>
<div class="acts"><button class="btn ico" data-a="new" title="New playlist" aria-label="New playlist">${ICON.plus}</button></div>
</div>
<div class="childlist" id="plists"></div>`;
$<HTMLButtonElement>('#content .acts [data-a="new"]').onclick=()=>playlistModal();
const list=$('#plists');
if(!playlists.length){ list.innerHTML='<p class="empty">No playlists yet. Make one from the podcasts you want to hear in a row.</p>'; return; }
for(const p of playlists){
const el=document.createElement('div');
el.className='childrow';
el.innerHTML=playlistArt(p)+`<div class="txt"><b>${esc(p.name)}</b><small class="meta">${plural(p.feeds.length,'podcast')}</small></div>`+badgeHTML(p.items);
el.onclick=()=>selectFeed(':playlist:'+p.id);
list.appendChild(el);
}
}
/// A playlist's page: its episodes in its order. Play goes on through it; the cross marks one
/// played, which takes it out of an unplayed-only playlist.
async function renderPlaylist(p: Playlist){
$<HTMLButtonElement>('#tbRemove').disabled=true;
syncTools(null);
const box=$('#content');
box.classList.add('plain');
const how=[p.only_unplayed?'Unplayed episodes':'Every episode',p.oldest_first?'oldest first':'newest first',
p.priority.length?`${plural(p.priority.length,'podcast')} first`:''].filter(Boolean).join(', ');
box.innerHTML=`
<div class="fhead slim">
${playlistArt(p)}
<div class="meta"><h2>${esc(p.name)}</h2><div class="sub">${how}, from ${plural(p.feeds.length,'podcast')}</div></div>
<div class="acts">
<button class="btn ico" data-a="edit" title="Edit this playlist" aria-label="Edit this playlist">${ICON.settings}</button>
<button class="btn ico danger" data-a="rm" title="Delete this playlist" aria-label="Delete this playlist">${ICON.trash}</button>
</div>
</div>
<div class="childlist" id="listening"></div>`;
$<HTMLButtonElement>('#content .acts [data-a="edit"]').onclick=()=>playlistModal(p);
$<HTMLButtonElement>('#content .acts [data-a="rm"]').onclick=async()=>{
if(!await ask(`Delete the playlist ${p.name}? Its episodes stay in their podcasts.`,'Delete')) return;
try{ await api(`/api/playlists/${p.id}`,{method:'DELETE'}); toast('Deleted'); await loadPlaylists(); selectFeed(PLAYLISTS); }
catch(e){ toast(why(e),true); }
};
const list=$('#listening');
listLoading(list);
let rows: Entry[];
// shortcut: the first 200 only, with no Load more; page it as feeds do if a playlist is listened
// through that far.
try{ rows=(await api(`/api/playlists/${p.id}/entries?limit=200`) as ListPage).entries; }
catch(e){ list.innerHTML=`<p class="hint">${esc(why(e))}</p>`; return; }
if(!list.isConnected) return;
$('#count').textContent=`${p.name}: ${plural(p.items,'episode')}`;
list.innerHTML=rows.length?'':'<p class="hint">Nothing here yet. Episodes show up as your podcasts publish them.</p>';
for(const e of rows){
const el=listenRow(e,'Mark played',async()=>{ try{ await setRead(e,true); }catch(err){ toast(why(err),true); } renderPlaylist(p); loadPlaylists(); });
el.onclick=ev=>{
if((ev.target as Element).closest('[data-a=remove]')) return;
if(el.classList.contains('now')&&!audio.paused){ audio.pause(); return; }
playFrom(rows,e);
};
list.appendChild(el);
}
}
/// Plays an episode of a list that goes on to the list's next.
function playFrom(list: Entry[],e: Entry){
play(e);
// After play, which forgets the list it came from, and has painted Next and told the phone
// what follows without it.
if(inPlayer(e)){ playingFrom=list; hostNext(); }
}
/// The next in the playlist after the one playing, if it was started from one.
function nextInPlaylist(){
if(!playingFrom) return undefined;
const i=playingFrom.findIndex(inPlayer);
return i<0 ? undefined : nextUp(playingFrom.slice(i+1),null);
}
/// Making a playlist, or changing one: a name, the podcasts in it and which play first, and which
/// of their episodes.
function playlistModal(p?: Playlist){
const shows=S.feeds.filter(f=>f.podcast);
const row=(f: Feed)=>{
const id=esc(f.id), inIt=!!p?.feeds.includes(f.id), first=!!p?.priority.includes(f.id);
return `<div class="plshow">${artHTML(f.image,f.title||f.id)}
<label class="check"><input type="checkbox" data-in="${id}"${inIt?' checked':''}> ${esc(f.title||f.id)}</label>
<label class="check first"><input type="checkbox" data-first="${id}"${first?' checked':''}${inIt?'':' disabled'}> Play first</label></div>`;
};
openModal(`<h3>${p?'Edit playlist':'New playlist'}</h3>
<div class="field"><label for="plname">Name</label>
<input type="text" id="plname" value="${esc(p?.name||'')}" placeholder="Morning commute"></div>
<div class="field"><label>Podcasts</label>
${shows.length?`<div class="plshows">${shows.map(row).join('')}</div>`:'<p class="hint">Subscribe to a podcast first.</p>'}
<span class="hint">Episodes of those set to play first come before the rest.</span></div>
<div class="field">
<label class="check"><input type="checkbox" id="plunplayed"${p?.only_unplayed??true?' checked':''}> Only episodes you have not played</label>
<label class="check"><input type="checkbox" id="ploldest"${p?.oldest_first?' checked':''}> Oldest first</label></div>
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Cancel" aria-label="Cancel">${ICON.close}</button>
<button class="btn ico primary" id="plsave" title="${p?'Save':'Make playlist'}" aria-label="${p?'Save':'Make playlist'}">${p?ICON.check:ICON.plus}</button></div>`);
// Play first means something only for a podcast in the playlist.
for(const box of $$<HTMLInputElement>('[data-in]')) box.onchange=()=>{
const first=$<HTMLInputElement>(`[data-first="${CSS.escape(box.dataset.in!)}"]`);
first.disabled=!box.checked; if(!box.checked) first.checked=false;
};
$<HTMLInputElement>('#plname').focus();
$<HTMLButtonElement>('#plsave').onclick=async()=>{
const name=$<HTMLInputElement>('#plname').value.trim();
const feeds=$$<HTMLInputElement>('[data-in]').filter(b=>b.checked).map(b=>b.dataset.in!);
if(!name){ $<HTMLInputElement>('#plname').focus(); return; }
if(!feeds.length){ toast('Choose at least one podcast.',true); return; }
const body=JSON.stringify({name,feeds,priority:$$<HTMLInputElement>('[data-first]').filter(b=>b.checked).map(b=>b.dataset.first!),
only_unplayed:$<HTMLInputElement>('#plunplayed').checked,oldest_first:$<HTMLInputElement>('#ploldest').checked});
try{
const r=p ? await api(`/api/playlists/${p.id}`,{method:'PATCH',body}) : await api('/api/playlists',{method:'POST',body});
closeModal(); toast(p?'Saved':'Playlist made');
if(!expanded.has(PLAYLISTS)) toggleGroup(PLAYLISTS);
await loadPlaylists(); selectFeed(':playlist:'+(p?p.id:r.id));
}catch(e){ toast(why(e),true); }
};
}

92
web/src/seasons.ts Normal file
View File

@@ -0,0 +1,92 @@
/* ---------------- seasons (#482) ---------------- */
/// A podcast's seasons, by feed id, as its page last fetched them, so going back to it draws its
/// picker at once while the counts are asked for again.
const seasonsOf=new Map<string,SeasonCount[]>();
/// Whether a podcast is told in seasons: two or more of them, holding most of its episodes. A few
/// numbered among hundreds (The Vintage RPG Podcast's 2 of 366), or years given as seasons on a
/// quarter of them (Ken and Robin's), are no seasons worth a picker.
function seasonsShown(list: SeasonCount[]|undefined): boolean{
if(!list) return false;
const numbered=list.filter(s=>s.season!=null);
const inOne=numbered.reduce((n,s)=>n+s.episodes,0), all=list.reduce((n,s)=>n+s.episodes,0);
return numbered.length>=2 && inOne*2>=all;
}
/// What the picker sends for a season: its number, or `none` for the episodes that name none.
const seasonKey=(s: SeasonCount)=>s.season==null?'none':String(s.season);
const seasonName=(s: number|null|undefined)=>s==null?'Other episodes':`Season ${s}`;
/// The picker, under the tabs: every season, one of them, or the episodes naming none.
function seasonsHTML(list: SeasonCount[]): string{
const chip=(key: string,label: string,title: string)=>
`<button data-season="${key}" class="${S.season===key?'on':''}" aria-pressed="${S.season===key}" title="${title}">${label}</button>`;
return `<div class="tabs seasons" role="group" aria-label="Seasons">${chip('','All seasons','Every season')}${
list.map(s=>chip(seasonKey(s),s.season==null?'Other':`Season ${s.season}`,
`${plural(s.episodes,'episode')}, ${s.unread} unread`)).join('')}</div>`;
}
function drawSeasons(f: Feed, list: SeasonCount[]|undefined){
const bar=$('#content .toolbar'); if(!bar||S.feed!==f.id) return;
bar.querySelector('.seasonrow')?.remove();
if(!list||!seasonsShown(list)) return;
// The download beside the picker, on its row: on a phone, on a row of its own, it cost a line.
const picked=list.find(s=>seasonKey(s)===S.season);
bar.insertAdjacentHTML('beforeend',`<div class="seasonrow">${seasonsHTML(list)}${picked?`<button class="btn ico seasondl"
title="Download ${esc(seasonName(picked.season))}" aria-label="Download ${esc(seasonName(picked.season))}">${ICON.download}</button>`:''}</div>`);
bar.querySelector<HTMLButtonElement>('.seasondl')?.addEventListener('click',()=>downloadSeason(f));
// The one picked in view: on a phone Season 3 of six is past the edge, and the picker looked as
// if every season were still showing.
const track=bar.querySelector<HTMLElement>('.seasons'), on=track?.querySelector<HTMLElement>('.on');
if(track&&on) track.scrollLeft+=on.getBoundingClientRect().left-track.getBoundingClientRect().left-(track.clientWidth-on.offsetWidth)/2;
$$<HTMLButtonElement>('.seasons button',bar).forEach(b=>b.onclick=()=>{
S.season=b.dataset.season!; S.offset=0;
renderFeed(); loadEntries();
});
// The dividers in the list wait on knowing the podcast is told in seasons.
if(S.entries.length) renderEntries();
}
/// A podcast's seasons onto its page: kept ones at once, then the server's. Told in seasons only
/// once the answer came, its list is asked for again in its own order.
async function loadSeasons(f: Feed){
const had=seasonsShown(seasonsOf.get(f.id));
drawSeasons(f,seasonsOf.get(f.id));
try{
const got: SeasonCount[]=await api(`/api/feeds/${encodeURIComponent(f.id)}/seasons`);
seasonsOf.set(f.id,got);
drawSeasons(f,got);
// Drawn again, so the headings say the order too.
if(!had&&seasonsShown(got)&&!sortPicked&&S.feed===f.id){ S.offset=0; renderFeed(); loadEntries(); }
}catch{}
}
/// Whether a heading was clicked to sort the podcast open: until one is, a podcast told in
/// seasons runs in its own order, season 1 episode 1 first, not by date (#482).
let sortPicked=false;
/// The order a list is asked for in: the page's, or a seasoned podcast's own.
function sortFor(feed: string): {col: string, dir: 'asc'|'desc'}{
return feed===S.feed&&!sortPicked&&seasonsShown(seasonsOf.get(feed)) ? {col:'episode',dir:'asc'} : S.sort;
}
/// The unread of the season picked, for the count under the list; null for every season.
function seasonUnread(feed: string): number|null{
if(!S.season) return null;
return seasonsOf.get(feed)?.find(s=>seasonKey(s)===S.season)?.unread ?? null;
}
/// Where a season starts in the list, said above its first episode: only for every season at
/// once, newest or oldest first, where the episodes run season by season.
function seasonBreaks(): boolean{
const feed=S.feed ?? '', col=sortFor(feed).col;
return !S.season && (col==='episode'||col==='published') && seasonsShown(seasonsOf.get(feed));
}
/// Every episode of the season picked onto iPX, after asking: a season can be a few gigabytes.
function downloadSeason(f: Feed){
const s=seasonsOf.get(f.id)?.find(x=>seasonKey(x)===S.season); if(!s) return;
const name=seasonName(s.season);
openModal(`<h3>Download ${esc(name)}?</h3>
<p style="color:var(--dim)">Every episode of ${esc(name)} of <b>${esc(f.title||f.id)}</b> not on iPX yet, ${
plural(s.episodes,'episode')} in all, is downloaded in order, the first episode first.</p>
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Cancel" aria-label="Cancel">${ICON.close}</button>
<button class="btn ico primary" id="sgo" title="Download ${esc(name)}" aria-label="Download ${esc(name)}">${ICON.download}</button></div>`);
$<HTMLButtonElement>('#sgo').onclick=async()=>{
try{
const r=await api(`/api/feeds/${encodeURIComponent(f.id)}/download-latest`,{method:'POST',body:JSON.stringify({season:S.season})});
closeModal();
toast(r.queued?`Downloading ${plural(r.queued,'episode')} of ${name}`:`All of ${name} is on iPX already`);
}catch(e){ toast(why(e),true); }
};
}

View File

@@ -126,7 +126,7 @@ function signalHead(sg: Signal){
async function signalAction(a: string, sg: Signal){
if(a==='settings') signalModal(sg);
if(a==='rm'){
if(!confirm(`Delete the signal ${sg.name}? The items stay in their own feeds.`)) return;
if(!await ask(`Delete the signal ${sg.name}? The items stay in their own feeds.`, 'Delete')) return;
try{
await api(`/api/signals/${sg.id}`,{method:'DELETE'});
toast('Deleted'); await loadFeeds(true); selectFeed(':all');

View File

@@ -43,6 +43,8 @@ interface Feed {
hide_from_signals: boolean;
private: boolean;
private_by_address: boolean;
/** Has an audio or video file: on the Podcasts shelf (#474). */
podcast: boolean;
}
/// An item, in a page of `/api/entries` (db.rs EntryRow).
@@ -139,6 +141,9 @@ interface State {
/// Whether the server has more after the last page it sent, by that answer's own numbers.
more: boolean;
filter: string;
/// One season of the open podcast (#482): its number, `none` for the episodes naming none, or
/// empty for every season.
season: string;
q: string;
/// The selected item's guid.
sel: string | null;
@@ -146,6 +151,26 @@ interface State {
sort: {col: string, dir: 'asc' | 'desc'};
}
/// One season of a podcast, `/api/feeds/{id}/seasons` (db.rs SeasonCount, #482). No season is
/// the episodes that name none.
interface SeasonCount {
season?: number | null;
episodes: number;
unread: number;
}
/// A smart playlist, `/api/playlists` (db.rs PlaylistRow, #476).
interface Playlist {
id: number;
name: string;
feeds: string[];
priority: string[];
only_unplayed: boolean;
oldest_first: boolean;
/** How many episodes it holds now. */
items: number;
}
/// An account, `/api/users` (web.rs list_users).
interface Account {
id: number;

125
web/src/upnext.ts Normal file
View File

@@ -0,0 +1,125 @@
/* ---------------- Up Next ---------------- */
/// Up Next (#473): the episodes lined up to play, kept on the server so the phone and the browser
/// share one. What is playing is not in it: an episode leaves Up Next as it starts, as Overcast's
/// does, so the first one in it is always the one that follows.
let upNext: Entry[]=[];
/// The next one in the list that can play now, the one playing aside. One not downloaded yet is
/// passed over, to wait in the list until it is.
const nextUp=(list: Entry[], playing: string|null)=>list.find(e=>entryKey(e)!==playing&&e.enclosures.some(isPlayable));
const queued=(e: Entry)=>upNext.some(x=>entryKey(x)===entryKey(e));
function loadUpNext(){
api('/api/queue').then((r: ListPage)=>{ upNext=r.entries; upNextChanged(); }).catch(()=>{});
}
/// Saves Up Next in this order and takes the server's answer, which leaves out what was not
/// yours to queue. Drawn at once from what was asked, so a drag lands where it was dropped.
async function saveUpNext(list: Entry[]){
upNext=list; upNextChanged();
try{
const r: ListPage=await api('/api/queue',{method:'PUT',body:JSON.stringify(list.map(e=>({feed_id:e.feed_id,guid:e.guid})))});
upNext=r.entries;
}catch(err){ toast(why(err),true); loadUpNext(); return; }
upNextChanged();
}
function upNextChanged(){
renderFeeds();
if(S.feed===':upnext') drawUpNext();
drawNow();
// The rows' and the reader's buttons say whether each is in it.
for(const b of $$<HTMLButtonElement>('[data-a=queue]')) paintQueueButton(b);
hostNext();
}
/// Adds an episode at the end, or first with `next`, or takes it out if it is in already and
/// neither was asked. A file still on the feed's server is fetched now, so it is here by its turn.
async function toggleQueued(e: Entry, next=false){
const rest=upNext.filter(x=>entryKey(x)!==entryKey(e));
if(queued(e)&&!next){ await saveUpNext(rest); toast('Removed from Up Next'); return; }
const enc=e.enclosures.find(isPlayable)||e.enclosures.find(playsKind);
if(!enc){ toast('There is nothing to play in this item.',true); return; }
await saveUpNext(next?[e,...rest]:[...rest,e]);
if(!enc.path){
await api(`/api/enclosures/${enc.id}/download`,{method:'POST'}).catch(()=>{});
enc.state='pending';
}
toast((next?'Plays next':'Added to Up Next')+(enc.path?'':'. Downloading it first.'));
}
function paintQueueButton(b: HTMLButtonElement){
const key=b.dataset.key, on=!!key&&upNext.some(x=>entryKey(x)===key);
const label=on?'Remove from Up Next':'Add to Up Next';
b.setAttribute('aria-pressed',String(on)); b.title=label; b.setAttribute('aria-label',label);
b.innerHTML=on?ICON.queued:ICON.queue;
}
/// The toggle on a row or in the reader, drawn with its state.
const queueButton=(e: Entry,cls='iconbtn')=>`<button class="${cls}" data-a="queue" data-key="${esc(entryKey(e))}" aria-pressed="${queued(e)}"
title="${queued(e)?'Remove from Up Next':'Add to Up Next'}" aria-label="${queued(e)?'Remove from Up Next':'Add to Up Next'}">${queued(e)?ICON.queued:ICON.queue}</button>`;
/// What plays after this one ends, or the next button is pressed.
/// Up Next first; with nothing in it, the next in the playlist the one playing came from.
function playNext(){
const e=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null);
if(e){ play(e); return true; }
const n=nextInPlaylist();
if(n&&playingFrom){ playFrom(playingFrom,n); return true; }
return false;
}
/// Playing takes an episode out of Up Next: it is under way, and Currently Listening has it now.
function startedPlaying(e: Entry){
if(queued(e)) saveUpNext(upNext.filter(x=>entryKey(x)!==entryKey(e)));
}
/// The phone's player is told what follows (#473), so with the screen locked, when the page is
/// frozen and cannot answer the end of an episode, it goes on to the next by itself.
function hostNext(){
const next=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null)??nextInPlaylist();
$<HTMLButtonElement>('#pnext').hidden=!next;
try{
if(!ipxHost||!hostCan.has('next')) return;
const e=next, enc=e?.enclosures.find(isPlayable);
ipxHost(e&&enc?{t:'next',...hostItem(e,enc,mediaSrc(enc))}:{t:'next'});
}catch{}
}
/// Up Next's place: the list, a handle on each row to drag it up or down (or its arrow keys),
/// and a button to take it out.
function drawUpNext(){
const box=$('#listening'); if(!box) return;
$('#count').textContent=`Up Next: ${plural(upNext.length,'episode')}`;
box.innerHTML=upNext.length?'':'<p class="hint">Nothing lined up. Add an episode with its Up Next button, and it plays when the one before it ends.</p>';
for(const e of upNext){
const el=listenRow(e,'Remove from Up Next',()=>saveUpNext(upNext.filter(x=>entryKey(x)!==entryKey(e))));
el.insertAdjacentHTML('afterbegin',`<button class="iconbtn grip" title="Drag to move, or use the arrow keys" aria-label="Move ${esc(entryName(e).text)}">${ICON.grip}</button>`);
box.appendChild(el);
}
for(const g of $$<HTMLButtonElement>('.grip',box)) grip(g,box);
}
/// One row's handle. A drag moves the row among the others as the pointer goes, and saves where
/// it is let go; Up and Down move it one place, for a keyboard.
function grip(g: HTMLButtonElement,box: HTMLElement){
const row=g.closest<HTMLElement>('.childrow')!;
const save=()=>{
const list=$$<HTMLElement & {entry?: Entry}>('.childrow',box).map(r=>r.entry!);
if(list.some((e,i)=>e!==upNext[i])) saveUpNext(list);
};
g.onclick=ev=>ev.stopPropagation();
g.onkeydown=ev=>{
const [up,down]=[row.previousElementSibling,row.nextElementSibling];
if(ev.key==='ArrowUp'&&up) box.insertBefore(row,up);
else if(ev.key==='ArrowDown'&&down) box.insertBefore(down,row);
else return;
ev.preventDefault(); g.focus(); save();
};
g.onpointerdown=ev=>{
ev.preventDefault(); ev.stopPropagation();
g.setPointerCapture(ev.pointerId);
row.classList.add('dragging');
g.onpointermove=m=>{
const over=$$<HTMLElement>('.childrow',box).find(r=>r!==row&&m.clientY<r.getBoundingClientRect().bottom);
if(over&&m.clientY>over.getBoundingClientRect().top+over.offsetHeight/2) box.insertBefore(row,over.nextElementSibling);
else if(over) box.insertBefore(row,over);
else box.appendChild(row);
};
g.onpointerup=g.onpointercancel=()=>{ g.onpointermove=null; row.classList.remove('dragging'); save(); };
};
}

View File

@@ -4,6 +4,11 @@
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.
/// Two names in the order a shelf files them: a leading "The", "A" or "An" aside, so The Rest Is
/// Science is under R (#481), with case and accents aside and 2 before 10.
const ARTICLE=/^(the|an?)\s+/i;
const nameOrder = (a: string, b: string): number =>
a.replace(ARTICLE,'').localeCompare(b.replace(ARTICLE,''),undefined,{sensitivity:'base',numeric:true});
const why = (e: unknown): string => e instanceof Error ? e.message : String(e);
/// A row that opens a feed, a place or a show (the feed list, the Directory): a link to a screen
/// reader, named by what it shows, the open one marked current. Not a button, whose contents a
@@ -18,6 +23,26 @@ function asLink(el: HTMLElement, current: boolean){
}
const ESCAPED: Record<string,string> ={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};
const esc = (s: string|null|undefined) => (s??'').replace(/[&<>"']/g,c=>ESCAPED[c]);
/// Asks before something hard to take back, in a dialog of the page's own. Not confirm(): the iOS
/// app answered that Cancel without showing it, so nothing that asked first went ahead there
/// (#453, #462). A <dialog> of its own, in the top layer, so it opens over a dialog already up and
/// leaves it as it was; Escape or a tap on Cancel answers no.
function ask(text: string, yes: string): Promise<boolean>{
const d=document.createElement('dialog');
d.className='card ask';
d.innerHTML=`<p></p><div class="cardacts"><button type="button" class="btn" value="">Cancel</button>
<button type="button" class="btn danger" value="y"></button></div>`;
d.querySelector('p')!.textContent=text;
d.querySelector('[value="y"]')!.textContent=yes;
document.body.append(d);
return new Promise(done=>{
d.onclick=(e: MouseEvent)=>{ const b=(e.target as Element).closest('button'); if(b) d.close(b.value); };
// Escape answers this dialog alone, not the one under it too.
d.onkeydown=(e: KeyboardEvent)=>{ if(e.key==='Escape') e.stopPropagation(); };
d.onclose=()=>{ d.remove(); done(d.returnValue==='y'); };
d.showModal();
});
}
// A feed's link, only if it is a web address: esc() keeps a javascript: or data: one working (#326).
const webUrl = (u: string|null|undefined): string|null => /^https?:\/\//i.test(u??'') ? u! : null;
// Icons: Font Awesome Free 7.3.1 by @fontawesome - https://fontawesome.com
@@ -28,6 +53,7 @@ const fa=(box: string,body: string)=>`<svg class="i" viewBox="${box}" aria-hidde
/// An app-icon tile (web/signals.svg, deadair-on.svg, ...) in the mode's own variant, as the logo is.
const tile=(name: string)=>`<img class="tile onlight" src="/${name}.svg" alt=""><img class="tile ondark" src="/${name}-dark.svg" alt="">`;
const ICON: Record<string,string>={
more:fa('0 0 448 512','<path fill="currentColor" d="M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"/>'), // solid/ellipsis, for a file's other actions (#457)
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
@@ -69,6 +95,14 @@ const ICON: Record<string,string>={
left:fa('0 0 512 512','<path fill="currentColor" d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 288 480 288c17.7 0 32-14.3 32-32s-14.3-32-32-32l-370.7 0 105.4-105.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/>'), // solid/arrow-left
// Drawn here: Font Awesome's free set has no AirPlay. A screen with a triangle under it, as Apple's.
airplay:fa('0 0 512 512','<path fill="currentColor" d="M64 48l384 0c26.5 0 48 21.5 48 48l0 256c0 26.5-21.5 48-48 48l-56 0 0-56 48 0 0-240-368 0 0 240 48 0 0 56-56 0c-26.5 0-48-21.5-48-48L16 96c0-26.5 21.5-48 48-48zM256 288l144 176-288 0z"/>'),
// Up Next (#473): a list, with a plus to add to it or a tick once in it, the state in the
// shape. Drawn here, so the two are the same list and differ only in that mark.
queue:fa('0 0 512 512','<path fill="currentColor" d="M32 96a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm0 160a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm32 128h160a32 32 0 0 1 0 64H64a32 32 0 0 1 0-64zm320-64a32 32 0 0 1 32 32v48h48a32 32 0 0 1 0 64h-48v48a32 32 0 0 1-64 0v-48h-48a32 32 0 0 1 0-64h48v-48a32 32 0 0 1 32-32z"/>'),
queued:fa('0 0 512 512','<path fill="currentColor" d="M32 96a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm0 160a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm32 128h160a32 32 0 0 1 0 64H64a32 32 0 0 1 0-64z"/><path fill="none" stroke="currentColor" stroke-width="60" stroke-linecap="round" stroke-linejoin="round" d="M300 404l54 54 116-116"/>'),
// Font Awesome's podcast, for the Podcasts shelf (#474).
podcasts:fa('0 0 448 512','<path fill="currentColor" d="M319.4 372c48.5-31.3 80.6-85.9 80.6-148 0-97.2-78.8-176-176-176S48 126.8 48 224c0 62.1 32.1 116.6 80.6 148 1.2 17.3 4 38 7.2 57.1l.2 1C56 395.8 0 316.5 0 224 0 100.3 100.3 0 224 0S448 100.3 448 224c0 92.5-56 171.9-136 206.1l.2-1.1c3.1-19.2 6-39.8 7.2-57zm-2.3-38.1c-1.6-5.7-3.9-11.1-7-16.2-5.8-9.7-13.5-17-21.9-22.4 19.5-17.6 31.8-43 31.8-71.3 0-53-43-96-96-96s-96 43-96 96c0 28.3 12.3 53.8 31.8 71.3-8.4 5.4-16.1 12.7-21.9 22.4-3.1 5.1-5.4 10.5-7 16.2C99.8 307.5 80 268 80 224c0-79.5 64.5-144 144-144s144 64.5 144 144c0 44-19.8 83.5-50.9 109.9zM224 312c32.9 0 64 8.6 64 43.8 0 33-12.9 104.1-20.6 132.9-5.1 19-24.5 23.4-43.4 23.4s-38.2-4.4-43.4-23.4c-7.8-28.5-20.6-99.7-20.6-132.8 0-35.1 31.1-43.8 64-43.8zm0-144a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"/>'),
next:fa('0 0 320 512','<path fill="currentColor" d="M52.5 440.6c-9.5 7.9-22.8 9.7-34.1 4.4S0 428.4 0 416V96c0-12.4 7.2-23.7 18.4-29s24.5-3.6 34.1 4.4l192 160L256 241V96c0-17.7 14.3-32 32-32s32 14.3 32 32v320c0 17.7-14.3 32-32 32s-32-14.3-32-32V271l-11.5 9.6-192 160z"/>'),
grip:fa('0 0 320 512','<path fill="currentColor" d="M40 352a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80zM40 216a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80zM40 80a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80z"/>'),
subbed:fa('0 0 512 512','<path fill="currentColor" d="M256 512a256 256 0 1 1 0-512 256 256 0 1 1 0 512zM374 145.7c-10.7-7.8-25.7-5.4-33.5 5.3L221.1 315.2 169 263.1c-9.4-9.4-24.6-9.4-33.9 0s-9.4 24.6 0 33.9l72 72c5 5 11.8 7.5 18.8 7s13.4-4.1 17.5-9.8L379.3 179.2c7.8-10.7 5.4-25.7-5.3-33.5z"/>'), // solid/circle-check
};
// What is playing, as the icon's EQ bars; the stylesheet moves them.
@@ -158,7 +192,8 @@ async function api(url: string, opts?: RequestInit): Promise<any>{
const tp=traceparent(), mine=traceId;
const taps=!!rootKind&&(tapBusy>0||Date.now()-Math.max(rootAt,answeredAt)<2000);
if(taps) tapBusy++;
const r = await fetch(url,{headers:{'Content-Type':'application/json',traceparent:tp},...opts})
// Answers in protobuf where ipx has them (#470), JSON where not; wire.ts reads either the same.
const r = await fetch(url,{headers:{'Content-Type':'application/json',Accept:'application/x-protobuf, application/json',traceparent:tp},...opts})
.catch(()=>{ throw new Error('Unable to reach iPX. Check your connection and try again.'); })
.finally(()=>{ if(taps&&mine===traceId) tapBusy--; });
// The tap lasts until the last answer to what it set off.
@@ -172,6 +207,8 @@ async function api(url: string, opts?: RequestInit): Promise<any>{
throw new Error(r.status===500 ? 'iPX could not do that just now. Try again in a minute.'
: said || 'Unable to reach iPX just now. Try again in a minute.');
}
const pb=wireType(r.headers.get('Content-Type'));
if(pb) return wireDecode(pb,new Uint8Array(await r.arrayBuffer()));
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
@@ -212,7 +249,7 @@ async function copyText(text: string,btn?: HTMLElement){
/// 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?: HTMLElement){
if(carriesAccess(url) && !confirm(ACCESS_WARNING+'\n\nShare it anyway?')) return;
if(carriesAccess(url) && !await ask(ACCESS_WARNING, 'Share it anyway')) return;
await sendLink(title, url, btn);
}
@@ -308,7 +345,7 @@ const S: State = {
feed:(()=>{ try{ return localStorage.getItem('ipx.feed'); }catch{ return null; } })(),
entries:[], total:0, offset:0, more:false,
filter:(()=>{ try{ return localStorage.getItem('ipx.filter'); }catch{ return null; } })()||'all',
q:'', sel:null, me:null,
season:'', 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')??'null'); }catch{ return null; } })()
||{col:'published',dir:'desc'},

67
web/src/wire.ts Normal file
View File

@@ -0,0 +1,67 @@
// ipx's answers in protobuf (#470): the page asks for them, and this reads one into the same object
// its JSON would have been, so nothing past api() knows the difference. The messages come from
// crates/wire/proto, which web/build.mts reads into WIRE when it builds the page and the offline
// worker, both of which take this file. No library: the encoding is a few rules, and a decoder
// library was larger than everything protobuf saves the page.
/// A field: its number, its name, its type (s string, b bool, i signed, u unsigned, d double, or a
/// message's full name), whether repeated, whether optional.
type WireField = readonly [number, string, string, 0 | 1, 0 | 1];
const WIRE = /*__WIRE__*/{} as Record<string, readonly WireField[]>;
/// Message `type` from `buf`, as its JSON would have read: an absent optional or message is null, a
/// list message (only `repeated items`) is its array, 64-bit numbers are numbers.
function wireDecode(type: string, buf: Uint8Array): any {
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
let pos = 0;
const text = new TextDecoder();
// Low and high 32 bits, as protobufjs reads them: a JS number's bit operations stop at 32.
// Each length is read before `pos` is used: `pos += varint()[0]` adds to the old `pos`.
const varint = (): [number, number] => {
let lo = 0, hi = 0, b = 0;
for (let i = 0; i < 4; i++) { b = buf[pos++]!; lo |= (b & 127) << (i * 7); if (b < 128) return [lo >>> 0, 0]; }
b = buf[pos++]!; lo |= (b & 127) << 28; hi |= (b & 127) >> 4; if (b < 128) return [lo >>> 0, hi >>> 0];
for (let i = 0; i < 5; i++) { b = buf[pos++]!; hi |= (b & 127) << (i * 7 + 3); if (b < 128) return [lo >>> 0, hi >>> 0]; }
throw new Error('a varint longer than ten bytes');
};
const num = ([lo, hi]: [number, number], signed: boolean) =>
signed && hi >= 0x80000000 ? -((~hi >>> 0) * 4294967296 + (~lo >>> 0) + 1) : hi * 4294967296 + lo;
const skip = (wt: number) => {
if (wt === 0) varint(); else if (wt === 1) pos += 8; else if (wt === 2) { const len = varint()[0]; pos += len; } else if (wt === 5) pos += 4;
else throw new Error(`wire type ${wt}`);
};
const scalar = (t: string): unknown => {
if (t === 'd') { const v = view.getFloat64(pos, true); pos += 8; return v; }
const v = varint();
return t === 'b' ? (v[0] | v[1]) !== 0 : num(v, t === 'i');
};
const message = (type: string, end: number): any => {
const fields = WIRE[type];
if (!fields) throw new Error(`no message ${type} in the page`);
const o: Record<string, unknown> = {};
for (const [, name, t, rep, opt] of fields) {
o[name] = rep ? [] : opt || t.length > 1 ? null : t === 's' ? '' : t === 'b' ? false : 0;
}
while (pos < end) {
const [tag] = varint();
const f = fields.find(x => x[0] === tag >>> 3), wt = tag & 7;
if (!f) { skip(wt); continue; }
const [, name, t, rep] = f;
let v: unknown;
if (t.length > 1) { const len = varint()[0]; v = WIRE[t] ? message(t, pos + len) : (pos += len, null); }
else if (t === 's') { const len = varint()[0]; v = text.decode(buf.subarray(pos, pos + len)); pos += len; }
// Packed: proto3 sends a repeated number as one run of them.
else if (rep && wt === 2) { const len = varint()[0], e = pos + len; while (pos < e) (o[name] as unknown[]).push(scalar(t)); continue; }
else v = scalar(t);
if (rep) (o[name] as unknown[]).push(v); else o[name] = v;
}
const only = fields.length === 1 ? fields[0] : undefined;
return only && only[1] === 'items' && only[3] ? o.items : o;
};
return message(type, buf.length);
}
/// The message an answer is in, from its Content-Type, or undefined for one that is not protobuf.
const wireType = (contentType: string | null) =>
/^application\/x-protobuf;\s*messageType=([\w.]+)/.exec(contentType || '')?.[1];

View File

@@ -48,7 +48,7 @@ sw.addEventListener('fetch', e => {
}
if (req.mode === 'navigate') e.respondWith(page(req));
// Named by a hash of their contents: what is kept is what the network would send.
else if (url.searchParams.has('v') && !url.pathname.startsWith('/api/')) e.respondWith(hashed(req));
else if (url.searchParams.has('v') && !url.pathname.startsWith('/api/')) e.respondWith(hashed(req, e.clientId));
else e.respondWith(networkFirst(req, url.pathname.startsWith('/api/') ? API : PAGE));
});
@@ -70,12 +70,21 @@ async function page(req: Request): Promise<Response> {
}
}
async function hashed(req: Request): Promise<Response> {
async function hashed(req: Request, client: string): Promise<Response> {
const kept = await caches.match(req, { cacheName: PAGE });
if (kept) return kept;
const r = await fetch(req);
if (r.ok) {
const c = await caches.open(PAGE), path = new URL(req.url).pathname;
const url = new URL(req.url);
// The server sends what it has now, whatever version the name asks for. A page kept from
// before a deploy, shown on waking before the network was back, got the new script under its
// old name, died at the first element it lacked (#449), and the new script was kept under the
// old name. Such a page is stale: it is loaded again, from the network, and not given the file.
if (await sha12(await r.clone().arrayBuffer()) !== url.searchParams.get('v')) {
void reloadStale(client);
return Response.error();
}
const c = await caches.open(PAGE), path = url.pathname;
// The version before this one is no use once this one is here.
for (const k of await c.keys()) if (new URL(k.url).pathname === path) await c.delete(k);
await c.put(req, r.clone());
@@ -83,6 +92,23 @@ async function hashed(req: Request): Promise<Response> {
return r;
}
/// What web/build.mts names a file by: the first 12 hex digits of its SHA-256.
async function sha12(body: ArrayBuffer): Promise<string> {
const d = new Uint8Array(await crypto.subtle.digest('SHA-256', body));
return Array.from(d.slice(0, 6), b => b.toString(16).padStart(2, '0')).join('');
}
// Once in a while at most: if the page itself still cannot be had from the network, the kept one
// comes back, asks for its old files again, and would be reloaded round and round.
let reloadedAt = 0;
async function reloadStale(id: string) {
if (Date.now() - reloadedAt < 30_000) return;
const c = await sw.clients.get(id);
if (!c || !('navigate' in c)) return;
reloadedAt = Date.now();
await (c as WindowClient).navigate(c.url);
}
async function networkFirst(req: Request, name: string): Promise<Response> {
try {
const r = await fetch(req);
@@ -107,10 +133,13 @@ async function withQueuedReads(kept: Response): Promise<Response> {
const read: unknown = (JSON.parse(w.body || '{}') as {read?: unknown}).read;
if (typeof read === 'boolean') reads.set(decodeURIComponent(m[1]!) + '\n' + decodeURIComponent(m[2]!), read);
}
if (!reads.size || !(kept.headers.get('Content-Type') || '').includes('json')) return kept;
// Only the fields read here: a page of items, or one item, as the API sends them.
const type = kept.headers.get('Content-Type') || '', pb = wireType(type);
if (!reads.size || !(type.includes('json') || pb)) return kept;
// Only the fields read here: a page of items, or one item, as the API sends them. One kept in
// protobuf (#470) goes back as JSON, which the page reads as well.
type Item = {feed_id: string, guid: string, read: boolean};
const body = await kept.clone().json().catch((): null => null) as {entries?: Item[]} & Partial<Item> | null;
const body = await (pb ? kept.clone().arrayBuffer().then(b => wireDecode(pb, new Uint8Array(b)))
: kept.clone().json()).catch((): null => null) as {entries?: Item[]} & Partial<Item> | null;
const mark = (e: Partial<Item>) => { const r = reads.get(e.feed_id + '\n' + e.guid); if (r !== undefined) e.read = r; };
if (Array.isArray(body?.entries)) body.entries.forEach(mark);
else if (body?.guid) mark(body);