33 Commits

Author SHA1 Message Date
1794a4c944 An item row's date is short and smaller (#508)
"Dec 3, 2026" at 15px took a third of a phone row and cut the title short.
Now the time today, "Nov 20" this year, "May 2025" before, at 13px; the
full date stays in the tooltip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-12-03 12:38:43 -05:00
3de955c52a Dimmed buttons say why; the directory fits at 200% zoom (#507)
Checked against the style guide's design half:

- Dimmed, not removed: the page already dims rather than hides, but a
  dimmed toolbar button kept its usual tooltip, so it looked broken.
  dim() sets the reason (Choose an item first, Open a feed to
  unsubscribe from it, Nothing to play in this item) and gives the
  usual tooltip back. The player's play-button sync leaves a dimmed one
  alone, and syncTools asks it to repaint so a playing item still says
  Pause. The admin page's Save says nothing has changed yet.
- 200% zoom on a 320 px screen (160 CSS px): the app and admin page fit;
  the directory scrolled sideways, its name on one line, its header form
  beside it, its category grid at a 180 px minimum and the chart's words.
  Now its name wraps, the form takes its own line, the grid's minimum is
  the width, and long words break.
- Tap targets at 320 px: the directory's tabs, chips, button and search
  box were 35-39 px, now 40; the page's checkbox rows were 26 px, now
  40. The admin switches are iOS's 51x31 inside a taller row.
- The directory's hovers sit inside (hover:hover).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-12-02 12:22:22 -05:00
19f9790eef The page follows the style guide's design half (#507)
Measured at 390 px with touch: the toolbar's buttons were 36 px wide and
the tabs 36 px tall, under the guide's 40 for a dense row; both are 40
now. A chapter's hover sat outside (hover:hover) and stuck after a tap.
An item row's pin and its download button had a tooltip and no
aria-label. Gaps of 5, 7 and 9 px are on the scale's 4, 6 and 8. The
guide said 25 palettes where there are 24; it now says every palette.

Left as they are: the folder triangle, 18 px wide by design (#486,
#491), and an episode's title button, inside a row that is the tap
target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-12-02 12:03:36 -05:00
a9f4fa51e6 The style guide covers design as well as writing (#507)
Principles, layout and the visual system (the 820 px breakpoint, the
spacing scale, colour roles, icons, touch targets), controls, dialogs,
commands, keyboard, feedback and timing, safety and an accessibility
checklist, each rule from what the page already does where it is
consistent, with a decision log for the points the historic guides
disagree on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-12-02 11:48:51 -05:00
8261e52484 The interface's words follow the style guide (#507)
docs/STYLE-GUIDE.md sets the rules: sentence case, "Unable to ..." and
what to do for a failure, podcast not show, address not URL, check not
scan, no dashes or symbols for words, buttons that start with a verb.
The page, admin, sign-in and the app's alert now follow it: the copy
failure, the download and sharing states, the feed's error label, the
DeadAir lines, the search boxes' clear buttons (which said only "Clear"),
the icon picker's Auto and Initials, the r key's "Refresh" (it reloads
the lists), the admin log's Scans tab. "add it in Settings" stays in
lower case: it is a link inside a sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-12-02 11:35:17 -05:00
0bb7437541 The iOS app opens offline: the page is kept however it was loaded (#506)
The phone in airplane mode opened to "Cannot reach ipodderx.sdf1.net".
The service worker kept the page only when a navigation passed through
it, and the app's own load from Swift may not, so it had no page to
answer with. The page now asks the worker to keep / on every load, and
the app, when a load fails for want of a connection, tries once more
from the web view's cache (returnCacheDataDontLoad) before the alert.
The Swift is not compiled here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-29 13:27:56 -05:00
99ce2dbc03 A feed is the same as last time by its items, not its bytes (#503)
The quiet rule (#242) hashed the raw body, so feeds rewritten at every
read with nothing new (Substack's lastBuildDate, Patreon's signed file
links) never matched and stayed hourly: 792 fetches a day for one Patreon
creator's shows, about 240 MB for five blogs. The hash is now of the
feed's title, artwork without its query, description and ttl, and each
item's guid, title, date and file addresses without their queries. An
OPML still hashes its bytes. The stored hashes are all of the old kind,
so every feed is read once after the deploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-29 07:41:15 -05:00
e2e8105880 An untitled item is named as it is stored, not by the page each time (#502)
The page named an item its feed gave no title (the first 120 characters of
its text, else its file's name) every time it drew one, so the iOS
widget, CarPlay, search and Signals never saw a name, and the list had to
carry each item's whole text to name the untitled ones (#501).

The feed parser now names them the same way as it reads a feed, for ipx
and the directory alike, and ipx names the untitled items already stored
once, in batches, before making search text, which the name goes into.
The reader and the directory's preview leave off a title that is only the
opening of the text below it, as they did for an untitled item.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-28 10:49:32 -05:00
467ac138e3 A database step's trace says how long it waited and how long Postgres took (#501)
All Subscriptions' Unread page spends 170-210 ms in its 'page' step one
time in ten, where the query itself takes 24-31 ms on production and the
pool's wait metric stays under 5 ms. The step now carries wait_ms and
query_ms, the same split #367's metrics make, so a slow trace names which.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-27 23:24:26 -05:00
19262bd788 A phone's episode row leaves out the length, keeping one line (#500)
The length under the title gave podcast rows a second line the
articles around them do not have, and looked out of place however it
was aligned. The reader shows it; wider screens keep it in the row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-27 17:29:07 -05:00
9e3ffd80c1 The reader rebuilds its scroller when an item opens on a phone (#450)
Every scroll_stuck report since the added fields was a short drag over
text in a reader whose content had just been swapped, with nothing over
it, nothing inert and the touch left alone by the page: iOS kept the drag
and did not scroll. That fits WebKit keeping an overflow box's scroller
sized for what was there before. Overflow is taken away for two frames
after each open, and after a stuck drag is caught, so the scroller is
built again; the report now says how long since the last one, which tells
whether this freed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-27 17:26:41 -05:00
1f4ad44da8 Changelog: no blank line inside the Fixed list (#500)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-27 17:23:42 -05:00
809f0ddf14 A phone row's second line starts under the title, its date on the title's line (#500)
The line under an unread title (an episode's length) started under the
unread dot, and the date was centred on the row, so a two-line row's date
sat between its lines, off line with every other row's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-27 17:23:35 -05:00
cfd740de43 All Subscriptions' footer counts what is in it (#499)
The count under the list summed every feed's unread, feeds hidden from
All Subscriptions (#288) included, and said 95 where the header and the
list said 23. It uses unreadInAll, as the header does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-26 16:57:56 -05:00
38a0d2fc71 An item without a title is set in bold like the rest of the list (#498)
The opening words that stand in for a missing title (#116) were set at
weight 400, so an unread list of Scripting News beside other feeds read
as half bold, half not, and looked broken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-26 16:19:03 -05:00
9ef9359fe6 A playlist row's X marks the episode played (#497)
renderPlaylist set an onclick of its own over listenRow's, to play on
through the playlist, and returned early for a click on the X instead of
calling its remove, so Mark played never ran. listenRow now takes what a
play click does, and the playlist passes playFrom instead of replacing the
handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 18:30:01 -05:00
5786a0cb1c NZB enclosures through SABnzbd, as torrents go through qBittorrent (#496)
An episode published as an .nzb was downloaded as if it were the episode:
ipx filed the NZB's XML in the feed's folder. NZBs now go to SABnzbd's API
the way torrents go to qBittorrent since #494, down the same path in scan
(download::Via says which), in the same two slots, counted with torrents.

ipx fetches the .nzb itself through the guarded client, under a 20 MB cap,
and adds it under the [nzb] category as nzb-<enclosure>, the name it finds
the job by again after a restart (#410). Progress is the queue's MB; the
stall clock stops while the history says it is verifying or unpacking, since
a large repair is slow. SABnzbd takes no folder per job, only per category,
so the category's folder has to be inside download_dir: the finished job is
renamed into the episode's own folder (save_path maps SABnzbd's view of the
mount onto ipx's) and taken out of the history, so nothing is left for a
delete to clean up, unlike #495.

Every parameter goes in the request body, the key included: reqwest's
errors print the URL, and a key in the query would have reached the log and
the episode's error. A wrong key comes back as 200 with status false, read
as a refusal.

Off, or with no SABnzbd or key, NZBs are skipped as "NZBs disabled", which
like "torrents disabled" no filter change overturns. An .nzb body behind a
lying MIME type is sniffed and handed on too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 15:11:14 -05:00
8469db6fa2 An episode deleted takes its torrent out of qBittorrent (#495)
Since #494 qBittorrent seeds a torrent after ipx has it. When the reaper
or Delete removed the episode's folder first, the torrent stayed in
qBittorrent as missing files until someone removed it there by hand.

Both delete paths now ask qBittorrent for the torrent by its ipx-<id> tag
and remove it, files kept (they are already gone). Only for a path that
is the enclosure's own torrent-<id> folder, only when torrents are on,
and in the reaper only once the folder is really gone, so one that would
not delete keeps seeding. Best effort: a qBittorrent not answering is a
warning, never a failed delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 14:47:58 -05:00
c4d7b497fa Torrents through qBittorrent instead of librqbit (#494)
ipx ran a BitTorrent session of its own: it bound 6881, joined the DHT and
seeded, and librqbit brought over a thousand lines of Cargo.lock with it,
ringbuf's advisory (#281) and a second path to chrono (#493) among them.
Tower already runs qBittorrent, so torrents go there through its Web API.

ipx still fetches the .torrent itself, through the guarded client and under
the 10 MB cap (#320, #330), and adds it with the enclosure's own folder as
the save path (#318, #331), the files straight into it (NoSubfolder), the
seed limits, and a tag ipx-<enclosure> to find it by, since a magnet has no
hash until its metadata comes. A torrent already tagged when ipx starts
again is taken up where qBittorrent has it (#410). It is polled to the end
under the stall limit; a qBittorrent not answering counts as no progress
rather than a failure. qBittorrent seeds to the limits; with none, ipx
removes the torrent from it at the end, files kept.

The session cookie is whatever qBittorrent sets with SID in its name:
5.x calls it QBT_SID_<port>. torrents/info by POST with a tag was checked
against Tower's 5.2.3.

The ringbuf ignore leaves deny.toml; chrono's stays, for rss and
atom_syndication alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 14:29:20 -05:00
2c8b4d925e SQLite past RUSTSEC-2026-0459 with sqlx 0.9.1, and url 2.5.9 (#467, #492, #493)
sqlx-sqlite 0.9.1 (2026-11-18) takes libsqlite3-sys up to 0.40, where
0.9.0 pinned it below 0.38, so the SQLite fix #467 waited on is in:
libsqlite3-sys 0.37.0 -> 0.40.0, and its ignore leaves deny.toml.

cargo deny then failed on two advisories published since:
RUSTSEC-2026-0592, url 2.5.8's Url::origin() overflowing the stack on a
URL nested in blob: thousands of times, fixed in 2.5.9 (#492); and
RUSTSEC-2026-0543, chrono unmaintained, no fixed release and no known
vulnerability. rss, atom_syndication and librqbit-dht depend on chrono,
so ipx's own uses moving off it would not take it out of Cargo.lock: it
is recorded in deny.toml as assessed and #493 stays open for when they do.

All six crates' tests pass, ipx's on Postgres and on SQLite, and the
browser suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 12:36:18 -05:00
6028202129 Episodes already out get their chapters at the next scan (#477)
Adding entries.chapters left stored items without theirs until their
feed next changed, so the episodes out now, the likeliest to be played,
had none. The migration now also forgets each feed's etag, Last-Modified
and body hash, as adding feeds.description did, so the next scan reads
every feed whole and changed_items fills the column. It runs after the
body_hash migration, which adds a column it clears.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 12:17:30 -05:00
4fccb59f44 A folder's triangle is back on the far left, in a narrower margin (#491)
#486 moved it to the row's end to take back the 16 px left margin it
hung in. It belongs first. It hangs in the list's margin again, now
10 px, and is as wide as that margin and the row's padding, up to the
art, so every row's art still lines up with the places above: 20 px
from the list's edge, against 26 before #486.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 12:17:30 -05:00
4aeb5c510f The app's wire code has the chapters' messages (#477)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 12:02:49 -05:00
882cd5f03c Now Playing lists an episode's chapters, and a tap plays from there (#477)
Where they come from, in order: the chapters file an item names
(<podcast:chapters url>, the Podcasting 2.0 namespace's JSON), stored on
the item as entries.chapters and read when someone opens Now Playing; else
the downloaded file's own chapters (ID3 CHAP frames, MP4 chapters), which
ffprobe reads as it does for DeadAir. A chapter with toc false is only
there to change the artwork and is left out.

GET /api/enclosures/{id}/chapters answers for a file, since a file is what
plays. With ?deadair=true the starts are moved into DeadAir's shortened
clock with to_copy, as positions are, or a chapter would start late by
every silence cut before it. A chapters file that cannot be read is an
empty list: the player plays on without them, and the step's span says why.

Items already stored get their chapters address when a scan next finds
them told differently; feeds that answer 304 add it with their next items.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 12:02:22 -05:00
f633f3d692 Opening a list moves the feed list's highlight instead of redrawing it (#490)
Profiled on production's lists at an iPhone 13's size with the CPU slowed
4x, opening four lists twice: selectFeed rebuilt every feed row (about
300 ms of the run) only to move .sel and aria-current, and dateOf made a
new Intl.DateTimeFormat for every row through toLocaleDateString with
options (about 155 ms). With markSelected and one shared formatter the
run's CPU time fell from 2.3-2.5 s to 1.25-1.65 s; dateOf from 157 ms to
12 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 11:26:09 -05:00
33b595973a Counting the files waiting to download reads an index of them alone (#489)
Db::counts counted enclosures WHERE state = 'pending' with no index to
use: a parallel sequential scan of all ~690,000 rows in production, 92 ms
and 32,397 buffers, every 30 s for /metrics and on each /api/status, to
find a handful. It was the slowest route at p95 and once 1.1 s. A partial
index on the pending rows makes it an index-only count of those few, as
enclosures_on_disk already does for the downloaded count beside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 08:54:42 -05:00
8afa79b022 A stuck scroll's report checks again, and knows when a swipe last moved the reader (#488, #450)
All three scroll_stuck reports since 9035306 said "slid 0s ago". The swipe
code's touchend runs before the stuck-scroll watcher's and calls slide(0)
on every touch in the reader that is not a swipe, and slide set slidAt
whatever dx was. It is now set only for a move across.

The watcher read scrollTop on touchend. iOS scrolls off the main thread,
and two of the three reports were fast flicks of 2-4 touchmoves, which can
end before the page knows the new position. It looks again 300 ms later
and reports only a reader that still has not moved, with the drag's time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
2026-11-22 08:38:54 -05:00
520c8bf8ff The feed list spends no margin on folders; a lone header button keeps its row (#486, #487)
#feedlist was padded 16px on the left and 8 on the right so a folder's
triangle could hang in the margin, and every feed and place moved in with
it. The triangle is drawn at a folder's row end now, before the count, by
flex order, so the keyboard still meets it first, and the list is padded
alike on both sides.

On a phone a header's buttons take a row of their own, right for a
podcast's seven; one button, Playlists' and Signals' +, stays beside the
title, its description given way to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-20 11:08:24 -05:00
eab2f75862 A page of its own starts its header where a podcast's does (#485)
Currently Listening, Up Next, Playlists and Signals are #content.plain,
which pads itself, and their header took #content>.fhead's padding on
top: 28px in on a phone where a podcast's header is at 14, 42px on a
desktop, with as much again above it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 11:08:44 -05:00
fb6bb79feb On a phone, an episode's title starts at the row's edge (#484)
The read dot's column and the pin button took 77px of a 390px row
before the title, the first of them empty once an episode was read. On
a phone the row has neither now: unread is a dot before the title,
named for a screen reader, and pinned a pin in the line under it, both
changed from the reader's floating actions. The hairline between rows
starts with the text. A desktop's rows are as they were.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 10:58:58 -05:00
419299f912 The #483 fix is ipx's alone: no line for the page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 10:47:42 -05:00
8386aa609b Downloading a season takes back what retention removed (#483)
Time For Chaos's Season 1 had all 20 files downloaded and since reaped.
Download Season 1 queued nothing and said all of it was on iPX, because
Db::undownloaded left out reaped files, as Download latest wants: there
they would only come back to be reaped again. A season asked for by name
is wanted whole, so its reaped files are queued; a fresh download is new
again to the quota and age sweeps, which order by when it was
downloaded. A file already downloading is no longer queued a second time,
for either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
2026-11-19 10:45:59 -05:00
55382478af Merge branch 'seasons' 2026-11-19 09:34:18 -05:00
60 changed files with 2442 additions and 1595 deletions

View File

@@ -420,7 +420,7 @@ ms in ipx, the difference being new connections, 80-330 ms each to open (#241).
Comments explain **why**, not what. If a line looks odd, the comment says what went wrong without
it. No emoji, no exclamation marks, no "obviously". Prose in the UI and docs is plain English and
addressed to the person using it.
addressed to the person using it. The words in the interface follow [docs/STYLE-GUIDE.md](docs/STYLE-GUIDE.md).
Every change gets one line under `## [Unreleased]` in the changelog of the service it changes, in
its [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) group: Added, Changed, Deprecated,

1223
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -26,7 +26,6 @@ chrono = { version = "0.4.45", default-features = false, features = ["std", "clo
clap = { version = "4.6.6", features = ["derive"] }
futures-util = { version = "0.3.34", default-features = false, features = ["std"] }
jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] }
librqbit = { version = "9.0.1", default-features = false, features = ["rust-tls", "http-api-client"] }
opentelemetry = { version = "0.33", default-features = false, features = ["trace"] }
opentelemetry-otlp = { version = "0.33", default-features = false, features = ["trace", "http-proto", "reqwest-blocking-client", "gzip-http"] }
opentelemetry_sdk = { version = "0.33", default-features = false, features = ["trace"] }
@@ -42,7 +41,7 @@ http = "1.5.0"
hyper-util = { version = "0.1.20", features = ["client-legacy"] }
percent-encoding = "2.3.2"
quick-xml = { version = "0.42.0", features = ["escape-html"] }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2", "gzip", "brotli", "zstd", "stream", "json", "charset", "system-proxy"] }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2", "gzip", "brotli", "zstd", "stream", "json", "form", "multipart", "charset", "system-proxy"] }
rss = "2.1.1"
sea-orm = { version = "2.0.3", default-features = false, features = ["sqlx-sqlite", "sqlx-postgres", "runtime-tokio-rustls", "macros", "with-json", "sqlite-use-returning-for-3_35"] }
serde = { version = "1.0.229", features = ["derive"] }

View File

@@ -19,7 +19,7 @@ behind iPodderX (2004-2008, Ray Slakinski & August Trometer).
- **Scanning.** Feeds are checked on a schedule, globally or per feed, and a feed's own TTL is
honoured. Keyword, explicit-content and media-type filters decide what is downloaded, with a limit
on how many of a feed's newest episodes are downloaded.
- **Downloads.** Files come over HTTP or BitTorrent and are filed into a folder per feed.
- **Downloads.** Files come over HTTP, BitTorrent through qBittorrent, or Usenet through SABnzbd, and are filed into a folder per feed.
Retention deletes the oldest files to stay under a disk quota or an age limit, and never touches
an item someone has pinned.
- **OPML.** You can import and export your own subscriptions. You can also subscribe to an OPML
@@ -37,8 +37,8 @@ docker compose up -d
`docker-compose.yml` is a sample: ipx, with its database in SQLite and its three volumes
(`/config`, `/data` and `/downloads`) in folders beside the file, and ipx-web, the page, served by
Caddy in front of it. Change them to suit. The UI is on port 8099. BitTorrent uses 6881
over TCP and UDP. Files are written as `PUID`/`PGID`, 99:100 by default.
Caddy in front of it. Change them to suit. The UI is on port 8099. Torrents need a qBittorrent
of your own, set in `[torrent]`, and NZBs a SABnzbd, set in `[nzb]` (docs/configuration.md). Files are written as `PUID`/`PGID`, 99:100 by default.
From source:

View File

@@ -19,6 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- On a phone the directory's pages fit at 200% zoom without scrolling sideways, its tabs, buttons and search box are 40 px to tap, and a link does not stay underlined after a tap (#507).
- An episode its feed gives no title is named by the opening of its text or else its file's name, where it had none (#502).
- Its checks of YouTube channels go one at a time, two seconds apart, since YouTube refuses many asked together (#386).
- Its JSON log lines no longer carry their span, once on its own and again in a list, which said nothing the line's own fields did not (#363).
@@ -28,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
- Built with SQLite 3.54 (libsqlite3-sys 0.40, through sqlx 0.9.1), past an advisory on opening a crafted database (RUSTSEC-2026-0459, #467), and url 2.5.9, which a web address nested thousands of times in `blob:` can no longer crash (RUSTSEC-2026-0592, #492).
- 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

View File

@@ -6,7 +6,7 @@
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
@media (hover:hover){a:hover{text-decoration:underline}}
a:focus-visible,button:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
header{display:flex;align-items:center;gap:16px;padding:12px 20px;background:var(--panel);border-bottom:1px solid var(--line);position:sticky;top:0;z-index:1}
.brand{display:flex;align-items:center;gap:10px;color:var(--fg);font-weight:700;font-size:17px;white-space:nowrap}
@@ -29,21 +29,21 @@ h3{font-size:17px;margin:28px 0 8px}
/* A grid item is as wide as its content unless told otherwise, and a long title then runs off the page. */
.chart li,.tile{min-width:0}
.chart a{display:flex;align-items:center;gap:12px;padding:8px;border-radius:10px;color:var(--fg)}
.chart a:hover{background:var(--panel);text-decoration:none}
@media (hover:hover){.chart a:hover{background:var(--panel);text-decoration:none}}
.no{width:22px;text-align:right;color:var(--faint);font-variant-numeric:tabular-nums;flex:none}
.txt{display:flex;flex-direction:column;min-width:0}
.txt b,.tile b{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
small{color:var(--dim);font-size:13px}
.cats{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px}
.cats{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(180px,100%),1fr));gap:12px}
.cat{display:flex;flex-direction:column;gap:2px;padding:14px 16px;border-radius:12px;background:var(--panel);border:1px solid var(--line);color:var(--fg)}
.cat:hover{border-color:var(--accent);text-decoration:none}
@media (hover:hover){.cat:hover{border-color:var(--accent);text-decoration:none}}
.tabs,.pills{display:flex;gap:6px;flex-wrap:wrap;margin:0 0 12px}
.tabs a,.pills a{padding:6px 14px;border-radius:999px;background:var(--panel);border:1px solid var(--line);color:var(--fg);font-size:14px}
.tabs a[aria-current],.pills a[aria-current]{background:var(--accent);border-color:var(--accent);color:var(--ink)}
.pills a[aria-current] small{color:inherit}
.tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:18px 14px}
.tile{display:flex;flex-direction:column;gap:4px;min-width:0;color:var(--fg)}
.tile:hover{text-decoration:none}.tile:hover b{text-decoration:underline}
@media (hover:hover){.tile:hover{text-decoration:none}.tile:hover b{text-decoration:underline}}
.show{display:flex;gap:24px;align-items:flex-end;margin-top:8px}
.meta{display:flex;flex-direction:column;gap:6px;min-width:0;flex:1}
.meta h2{margin:0;font-size:28px;line-height:1.15;overflow-wrap:anywhere}
@@ -58,9 +58,17 @@ button{font:inherit;font-weight:600;padding:8px 16px;border-radius:10px;border:0
article{padding:12px 0;border-bottom:1px solid var(--line);max-width:80ch}
article p{margin:4px 0;color:var(--dim)}
@media (max-width:600px){
header{padding:10px 16px;gap:10px}
header{padding:10px 16px;gap:10px;flex-wrap:wrap}
/* Under the name rather than squeezed beside it: at 200% zoom the two did not fit (#507). */
header form{flex:1 1 100%}
/* 40 px to tap, as the style guide asks of a phone (#507). */
.tabs a,.pills a{padding:9px 14px}
button,input{padding-top:10px;padding-bottom:10px}
.brand span,.brand{font-size:15px}
main{padding:16px}
/* Its name may take two lines: on one, it ran past the edge at 200% zoom (#507). */
.brand{white-space:normal}
/* A word too long for the line breaks rather than pushing the page sideways at 200% zoom (#507). */
main{padding:16px;overflow-wrap:anywhere}
.show{flex-direction:column;align-items:flex-start;gap:14px}
.art.lg{width:140px}
.tiles{grid-template-columns:repeat(auto-fill,minmax(104px,1fr));gap:14px 10px}

View File

@@ -14,6 +14,7 @@ chrono.workspace = true
http.workspace = true
hyper-util.workspace = true
opml.workspace = true
percent-encoding.workspace = true
pulldown-cmark.workspace = true
quick-xml.workspace = true
reqwest.workspace = true

View File

@@ -21,7 +21,7 @@ pub use failure::{Failure, explain_failure, failure_kind, is_temporary_lookup_fa
pub use fetch::{FEED_SILENCE, FEED_TIMEOUT, FETCHED_BYTES, FETCHES, Fetched, fetch, is_youtube_feed};
pub use jev::{JEV_URL, classify};
pub use outlines::{collect_outlines, is_opml, opml_title, parse_opml, read_opml};
pub use parse::{Enclosure, Entry, ParsedFeed, markdown_html, parse, same_file_key};
pub use parse::{Enclosure, Entry, ParsedFeed, markdown_html, parse, same_file_key, untitled_name};
pub use patreon::{is_patreon_creator, patreon_shows, same_feed};
pub use privacy::{redact, redact_text, url_looks_private};

View File

@@ -46,6 +46,9 @@ pub struct Entry {
pub duration: Option<i64>,
pub episode: Option<i64>,
pub season: Option<i64>,
/// Where its chapters are, `<podcast:chapters url>`: a JSON file of the Podcasting 2.0
/// namespace's, read when someone plays it (#477).
pub chapters: Option<String>,
pub enclosures: Vec<Enclosure>,
}
@@ -59,9 +62,53 @@ pub struct Enclosure {
pub length: Option<i64>,
}
/// RSS first, then Atom -- the same split the original made on `parsedFeed.version`.
/// RSS first, then Atom -- the same split the original made on `parsedFeed.version`. An item
/// without a title is named here, once, for everything that shows it (#502).
#[tracing::instrument(skip_all, fields(bytes = bytes.len()))]
pub fn parse(bytes: &[u8]) -> Result<ParsedFeed> {
let mut feed = parse_any(bytes)?;
for e in &mut feed.entries {
if e.title.is_none() {
e.title = untitled_name(e.description.as_deref(), e.enclosures.first().map(|x| x.url.as_str()));
}
}
Ok(feed)
}
/// A name for an item its feed gave no title: the first words of its text, cut at a word near
/// 120 characters, or else its file's name without the extension. What the page worked out each
/// time it drew one, until the iOS widget, CarPlay and search, which never saw it, needed it too.
pub fn untitled_name(description: Option<&str>, file: Option<&str>) -> Option<String> {
// Entities decoded, spaces made single; a tag is a space, so "2010)</p><p>Recorded" stays apart.
let words = description
.and_then(|d| title_text(Some(&text_of(d).split_whitespace().collect::<Vec<_>>().join(" "))))
.unwrap_or_default();
if !words.is_empty() {
let mut chars = words.chars();
let head: String = chars.by_ref().take(120).collect();
if chars.next().is_none() {
return Some(words);
}
// The word the cut fell in is dropped whole, as the page's /\s+\S*$/ did.
let cut = head.rfind(char::is_whitespace).map_or(head.as_str(), |at| head[..at].trim_end());
return Some(format!("{cut}\u{2026}"));
}
let path = file?.split(['?', '#']).next()?;
let last = path.rsplit('/').next().filter(|s| !s.is_empty())?;
let stem = match last.rsplit_once('.') {
Some((stem, ext))
if !stem.is_empty() && (1..=5).contains(&ext.len()) && ext.chars().all(|c| c.is_ascii_alphanumeric()) =>
{
stem
}
_ => last,
};
let name =
percent_encoding::percent_decode_str(stem).decode_utf8().map_or_else(|_| stem.to_owned(), |d| d.into_owned());
non_empty(Some(&name))
}
fn parse_any(bytes: &[u8]) -> Result<ParsedFeed> {
if bytes.trim_ascii_start().starts_with(b"[")
&& let Ok(posts) = serde_json::from_slice::<Vec<serde_json::Value>>(bytes)
{
@@ -283,6 +330,7 @@ pub(crate) fn from_rss(ch: rss::Channel, bytes: &[u8]) -> ParsedFeed {
duration: it.and_then(|i| i.duration()).and_then(parse_duration),
episode: it.and_then(|i| i.episode()).and_then(|e| e.trim().parse().ok()),
season: it.and_then(|i| i.season()).and_then(|e| e.trim().parse().ok()),
chapters: podcast_chapters(item),
enclosures,
})
})
@@ -348,6 +396,7 @@ pub(crate) fn from_atom(feed: atom_syndication::Feed) -> ParsedFeed {
duration: None,
episode: None,
season: None,
chapters: None,
enclosures,
})
})
@@ -460,6 +509,12 @@ pub(crate) fn notes(content: Option<&str>, description: Option<&str>, markdown:
///
/// shortcut: found by the `source` prefix the namespace's own docs and feeds use; a feed binding
/// it to another prefix is not read, until one turns up.
/// `<podcast:chapters url="..." type="application/json+chapters">`, by the prefix feeds give it.
fn podcast_chapters(item: &rss::Item) -> Option<String> {
let url = item.extensions().get("podcast")?.get("chapters")?.first()?.attrs().get("url")?.trim();
(url.starts_with("http://") || url.starts_with("https://")).then(|| url.to_owned())
}
pub(crate) fn source_markdown(item: &rss::Item) -> Option<&str> {
item.extensions().get("source")?.get("markdown")?.first()?.value()
}
@@ -602,6 +657,37 @@ mod tests {
use super::*;
use crate::failure;
#[test]
fn an_untitled_item_is_named_by_its_words_or_its_file() {
// Short text whole, decoded, the blocks kept apart.
assert_eq!(
untitled_name(Some("<p>Fish &amp; chips (2010)</p><p>Recorded</p>"), None).as_deref(),
Some("Fish & chips (2010) Recorded")
);
// Long text cut at the last whole word inside 120 characters.
let long = "word ".repeat(40);
let name = untitled_name(Some(&long), None).unwrap();
assert_eq!(name, format!("{}\u{2026}", "word ".repeat(24).trim_end()));
assert!(name.chars().count() <= 121);
// No text: the file's name, its query and extension gone, its escapes decoded.
assert_eq!(
untitled_name(Some("<img src=x>"), Some("https://x.example/a/Ep%2042.mp3?t=1")).as_deref(),
Some("Ep 42")
);
assert_eq!(untitled_name(None, Some("https://x.example/")), None);
assert_eq!(untitled_name(None, None), None);
// Through parse: the feed's own title is kept, and only a missing one is made.
let feed = parse(
br#"<rss version="2.0"><channel><title>t</title>
<item><guid>a</guid><description>Hello there</description></item>
<item><guid>b</guid><title>Kept</title><description>Not this</description></item>
</channel></rss>"#,
)
.unwrap();
let titles: Vec<_> = feed.entries.iter().map(|e| e.title.as_deref()).collect();
assert_eq!(titles, [Some("Hello there"), Some("Kept")]);
}
#[test]
fn parses_rss_with_itunes_extensions() {
let bytes = include_bytes!("../../../tests/data/rss2.xml");
@@ -899,6 +985,21 @@ Some **bold** and [a link](https://x.example/).</description></item>
assert_eq!((p1.season, p1.episode), (Some(8), Some(1)));
}
#[test]
fn an_items_chapters_are_where_podcast_chapters_says() {
let xml = br#"<?xml version="1.0"?>
<rss version="2.0" xmlns:podcast="https://podcastindex.org/namespace/1.0">
<channel><title>Show</title><link>https://x</link><description>d</description>
<item><title>A</title><guid>a</guid>
<podcast:chapters url=" https://x/a.json " type="application/json+chapters"/></item>
<item><title>B</title><guid>b</guid><podcast:chapters url="file:///etc/passwd"/></item>
<item><title>C</title><guid>c</guid></item>
</channel></rss>"#;
let feed = parse(xml).unwrap();
let got: Vec<_> = feed.entries.iter().map(|e| e.chapters.as_deref()).collect();
assert_eq!(got, [Some("https://x/a.json"), None, None], "only a web address, trimmed");
}
#[test]
fn an_item_may_carry_several_enclosures() {
// The rss crate keeps only one per item -- the last -- so these come from the XML.

View File

@@ -14,6 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Episodes published as NZBs download through SABnzbd, set in `[nzb]`, as torrents do through qBittorrent; with none set they are held back instead of filed as the episode (#496).
- An episode's chapters, from the chapters file its feed names (`<podcast:chapters>`) or else from the downloaded file itself, at `GET /api/enclosures/{id}/chapters`, in the clock of DeadAir's shortened copy when that is what plays; episodes already out pick theirs up at the next scan (#477).
- `GET /api/feeds/{id}/seasons` gives a podcast's seasons with how many episodes and unread each has, and a podcast's episodes can be asked for one season at a time, or for those naming none (`season=none`), and in its own order (`sort=episode`), season by season and episode by episode. `download-latest` takes a `season` to download all of it, first episode first (#482).
- Smart playlists: `GET` and `POST /api/playlists`, `PATCH` and `DELETE /api/playlists/{id}`, and `GET /api/playlists/{id}/entries`, the episodes of the podcasts chosen in the playlist's order, those set to play first ahead of the rest (#476).
- A feed in `/api/feeds` says whether it has audio or video (`podcast`), for the page's Podcasts shelf (#474).
@@ -29,6 +31,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- A feed whose items have not changed is checked less often even when its server rewrites it at every read, as Substack's build time and Patreon's signed file links do: it is judged by its items, not its bytes. An item's text edited with nothing else changed shows at the next full read, at most four hours on (#503).
- An item its feed gives no title is named as it is stored, by the opening of its text or else its file's name, so search, Signals, the iOS widget and CarPlay show the same name the page does; the untitled items already stored are named once at start (#502).
- Torrents go to qBittorrent through its Web API, set in `[torrent]` (`qbittorrent_url`, `username`, `password`, `save_path`), which downloads and seeds them until the episode is deleted; ipx no longer runs a BitTorrent client of its own or listens on 6881, and `port_range` is gone. Without a qBittorrent set, torrents are held back as when they are turned off (#494, #495).
- The server's command is `ipxd`, not `ipx`: `ipxd daemon`, `ipxd status`, `ipxd user add` and the rest, in the container as `docker exec iPX ipxd ...`. `ipx` is now the reader in a terminal (#437).
- The log no longer has a line for every request that went well, over half its size: `/metrics` counts each request and its time by route and status as `ipx_http_request_duration_seconds`, a request that failed keeps its warning, and the admin page's log view still shows them all (#364).
@@ -36,6 +41,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Counting the files waiting to download, which the status and the metrics do every 30 seconds, reads only those files instead of every one ipx knows of: about 1 ms instead of 90 (#489).
- Downloading a season takes back the files of it retention removed, rather than queuing nothing, and no file on its way already is queued twice (#483).
- A feed an OPML stops listing leaves All Subscriptions with it, rather than its items staying there with no feed name beside them: the scan no longer reads it again after the list drops it, and its subscriptions go with it, as they do when a feed is removed with `ipx rm`. Any left from before are removed when ipx starts (#478).
- Searching All Subscriptions answers in a fraction of a second, not five: a search reads each item's title and text without its markup, indexed on Postgres, and still finds part of a word. It no longer matches words inside the HTML's tags, such as a link's address. Text past the first 4,000 characters of a very long post is not searched (#459, #472).
- Artwork that cannot be shown is asked for again a day later rather than every hour: one too large is refused on its stated size before it is read, and a refusal from the publisher or one ipx makes (too large, not an image) is remembered for a day; JPEG XL pictures sent without a type are shown (#448).
@@ -49,6 +56,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
- Built with SQLite 3.54 (libsqlite3-sys 0.40, through sqlx 0.9.1), past an advisory on opening a crafted database (RUSTSEC-2026-0459, #467), and url 2.5.9, which a web address nested thousands of times in `blob:` can no longer crash (RUSTSEC-2026-0592, #492).
- Show notes are cleaned with ammonia 4.2.5, which no longer lets SVG or MathML in a feed's HTML carry script past it (RUSTSEC-2026-0533); Markdown items are read with pulldown-cmark 0.13.6, and compressed feeds and answers with zstd 0.14.4 and zstd-safe 8.3, each closing published advisories (#467).
- Ten wrong passwords from one address in a quarter hour hold that address off sign-in for the rest of it, answered `429` with how long to wait; before, a guesser could try as fast as the server checked. The address is the one a trusted proxy names last in `X-Forwarded-For`, or the peer's (#409).

View File

@@ -27,7 +27,6 @@ chrono.workspace = true
clap.workspace = true
futures-util.workspace = true
jsonwebtoken.workspace = true
librqbit.workspace = true
opentelemetry.workspace = true
opentelemetry_sdk.workspace = true
opml.workspace = true

112
crates/ipx/src/chapters.rs Normal file
View File

@@ -0,0 +1,112 @@
//! An episode's chapters (#477): from the JSON file its item names (`<podcast:chapters>`, the
//! Podcasting 2.0 namespace's), or else from the file itself once downloaded (ID3 `CHAP` frames,
//! MP4 chapters), which ffprobe reads as it does for DeadAir.
use anyhow::{Context, Result};
use serde::Serialize;
use std::path::Path;
#[derive(Debug, PartialEq, Serialize)]
pub struct Chapter {
/// Seconds from the start of the original.
pub start: f64,
pub title: String,
}
/// More than any list of chapters needs: a chapters file is a few KB.
const MAX: usize = 1 << 20;
/// The namespace's chapters file: `{"chapters": [{"startTime": 0, "title": "..", "toc": false}]}`.
/// One with `toc` false is there to change the artwork, not to be listed.
pub fn from_json(body: &[u8]) -> Result<Vec<Chapter>> {
let v: serde_json::Value = serde_json::from_slice(body).context("reading the chapters file")?;
let list = v["chapters"].as_array().context("no chapters in the chapters file")?;
Ok(sorted(
list.iter()
.filter(|c| c["toc"] != false)
.filter_map(|c| Some(Chapter { start: c["startTime"].as_f64()?, title: text(&c["title"]) }))
.collect(),
))
}
/// ffprobe's `-show_chapters -of json`: `{"chapters": [{"start_time": "0.000000", "tags": {"title": ".."}}]}`.
pub fn from_ffprobe(out: &str) -> Result<Vec<Chapter>> {
let v: serde_json::Value = serde_json::from_str(out).context("reading ffprobe")?;
Ok(sorted(
v["chapters"]
.as_array()
.into_iter()
.flatten()
.filter_map(|c| {
Some(Chapter { start: c["start_time"].as_str()?.parse().ok()?, title: text(&c["tags"]["title"]) })
})
.collect(),
))
}
fn text(v: &serde_json::Value) -> String {
v.as_str().unwrap_or("").trim().to_owned()
}
/// In order, and none before the start: the namespace does not promise either.
fn sorted(mut list: Vec<Chapter>) -> Vec<Chapter> {
list.retain(|c| c.start.is_finite() && c.start >= 0.0);
list.sort_by(|a, b| a.start.total_cmp(&b.start));
list
}
// ponytail: fetched each time someone opens Now Playing on an episode, which the page then keeps;
// keep them in the database if a chapters host turns out slow or many people play one episode.
pub async fn fetch(client: &reqwest::Client, url: &str) -> Result<Vec<Chapter>> {
let mut r = client.get(url).timeout(crate::feed::FEED_TIMEOUT).send().await?.error_for_status()?;
anyhow::ensure!(r.content_length().is_none_or(|n| n <= MAX as u64), "larger than {MAX} bytes");
let mut body = Vec::new();
while let Some(c) = r.chunk().await? {
body.extend_from_slice(&c);
anyhow::ensure!(body.len() <= MAX, "larger than {MAX} bytes");
}
from_json(&body)
}
pub async fn in_file(path: &Path) -> Result<Vec<Chapter>> {
let path = path.display().to_string();
from_ffprobe(&crate::deadair::run_out("ffprobe", &["-v", "error", "-show_chapters", "-of", "json", &path]).await?)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_namespaces_file_is_read_in_order_without_its_artwork_only_chapters() {
let body = br#"{"version":"1.2.0","chapters":[
{"startTime":95.5,"title":" Second "},
{"startTime":0,"title":"Intro"},
{"startTime":40,"img":"https://x/a.jpg","toc":false},
{"title":"no start"},
{"startTime":200}]}"#;
let got = from_json(body).unwrap();
assert_eq!(
got,
[
Chapter { start: 0.0, title: "Intro".into() },
Chapter { start: 95.5, title: "Second".into() },
Chapter { start: 200.0, title: "".into() },
]
);
assert!(from_json(b"<html>").is_err(), "a web page is not a chapters file");
}
#[test]
fn ffprobes_chapters_are_read_and_a_file_with_none_has_none() {
let out = r#"{"chapters":[
{"id":1,"start_time":"61.250000","end_time":"120.000000","tags":{"title":"Two"}},
{"id":0,"start_time":"0.000000","end_time":"61.250000","tags":{"title":"One"}}]}"#;
assert_eq!(
from_ffprobe(out).unwrap(),
[Chapter { start: 0.0, title: "One".into() }, Chapter { start: 61.25, title: "Two".into() }]
);
assert_eq!(from_ffprobe(r#"{"chapters":[]}"#).unwrap(), []);
assert_eq!(from_ffprobe("{}").unwrap(), []);
}
}

View File

@@ -14,6 +14,8 @@ pub struct Config {
#[serde(default)]
pub torrent: Torrent,
#[serde(default)]
pub nzb: Nzb,
#[serde(default)]
pub web: Web,
#[serde(default)]
pub push: Push,
@@ -112,14 +114,58 @@ impl Push {
#[serde(default)]
pub struct Torrent {
pub enabled: bool,
/// Stop seeding at this ratio, or after seed_time_mins, whichever comes first.
/// qBittorrent's Web UI, which does the downloading and seeding (#494), e.g.
/// "http://qbittorrent:8080". Empty: torrents are held back, as when not enabled.
pub qbittorrent_url: String,
/// Empty when qBittorrent lets ipx's address in without signing in.
pub username: String,
pub password: String,
/// Where qBittorrent sees `download_dir`, when its mount is not at the same path as ipx's.
pub save_path: String,
/// qBittorrent stops seeding at this ratio, or after seed_time_mins, whichever comes first.
pub seed_ratio: f64,
pub seed_time_mins: u64,
pub port_range: String,
/// Drop a torrent that has made no progress for this long.
pub stall_mins: u64,
}
/// NZB enclosures, sent to SABnzbd (#496) as torrents are to qBittorrent.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct Nzb {
pub enabled: bool,
/// SABnzbd's web address, e.g. "http://sabnzbd:8080". Empty: NZBs are held back.
pub sabnzbd_url: String,
pub api_key: String,
/// The category jobs are added under. Its folder in SABnzbd has to be inside `download_dir`,
/// where ipx can move the finished job from.
pub category: String,
/// Where SABnzbd sees `download_dir`, when its mount is not at the same path as ipx's.
pub save_path: String,
/// Drop an NZB that has made no progress for this long.
pub stall_mins: u64,
}
impl Default for Nzb {
fn default() -> Self {
Self {
enabled: true,
sabnzbd_url: String::new(),
api_key: String::new(),
category: "ipx".into(),
save_path: String::new(),
stall_mins: 30,
}
}
}
impl Nzb {
/// NZBs are fetched only with somewhere to send them.
pub fn on(&self) -> bool {
self.enabled && !self.sabnzbd_url.trim().is_empty() && !self.api_key.is_empty()
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct Web {
@@ -265,7 +311,16 @@ impl Default for General {
impl Default for Torrent {
fn default() -> Self {
Self { enabled: true, seed_ratio: 1.0, seed_time_mins: 60, port_range: "6881-6889".into(), stall_mins: 30 }
Self {
enabled: true,
qbittorrent_url: String::new(),
username: String::new(),
password: String::new(),
save_path: String::new(),
seed_ratio: 1.0,
seed_time_mins: 60,
stall_mins: 30,
}
}
}
@@ -313,16 +368,9 @@ pub fn parse_interval(s: &str) -> Option<u64> {
}
impl Torrent {
/// Inclusive listen port range. Falls back to the BitTorrent default on garbage input.
pub fn ports(&self) -> (u16, u16) {
let parse = || -> Option<(u16, u16)> {
let (lo, hi) = self.port_range.split_once('-')?;
Some((lo.trim().parse().ok()?, hi.trim().parse().ok()?))
};
match parse() {
Some((lo, hi)) if lo <= hi => (lo, hi),
_ => (6881, 6889),
}
/// Torrents are fetched only with somewhere to send them.
pub fn on(&self) -> bool {
self.enabled && !self.qbittorrent_url.trim().is_empty()
}
}
@@ -545,8 +593,8 @@ pub fn wanted_media(mime: Option<&str>, wanted: &[String]) -> bool {
return true;
};
let top = mime.split('/').next().unwrap_or(mime).to_ascii_lowercase();
// A .torrent is a container for media, not media itself; judge it once unpacked.
if mime.to_ascii_lowercase().contains("torrent") {
// A .torrent or an .nzb is a container for media, not media itself; judge it once unpacked.
if ["torrent", "nzb"].iter().any(|c| mime.to_ascii_lowercase().contains(c)) {
return true;
}
wanted.iter().any(|w| w.trim().eq_ignore_ascii_case(&top) || w.trim().eq_ignore_ascii_case(mime))
@@ -714,15 +762,13 @@ mod tests {
}
#[test]
fn port_range_falls_back_when_malformed() {
fn torrents_are_on_only_with_a_qbittorrent_to_send_them_to() {
let mut t = Torrent::default();
assert_eq!(t.ports(), (6881, 6889));
t.port_range = "51413-51420".into();
assert_eq!(t.ports(), (51413, 51420));
t.port_range = "nonsense".into();
assert_eq!(t.ports(), (6881, 6889));
t.port_range = "900-100".into();
assert_eq!(t.ports(), (6881, 6889), "reversed range is not a range");
assert!(!t.on(), "enabled, but nowhere to send them");
t.qbittorrent_url = "http://qbittorrent:8080".into();
assert!(t.on());
t.enabled = false;
assert!(!t.on());
}
#[test]
@@ -736,6 +782,7 @@ mod tests {
// A torrent is a container; what is inside is judged after unpacking.
assert!(wanted_media(Some("application/x-bittorrent"), &want));
assert!(wanted_media(Some("application/x-nzb"), &want));
// Unknown type: only discoverable by downloading, so do not refuse it outright.
assert!(wanted_media(None, &want));
assert!(wanted_media(Some(""), &want));

View File

@@ -29,15 +29,14 @@ pub struct Ctx {
/// that moved for good from one sent elsewhere for now.
pub feed_client: reqwest::Client,
pub out: Emitter,
/// Started on first use: a BitTorrent session binds ports and starts a DHT, which is
/// rude to do for a config that has never seen a torrent.
/// qBittorrent's client and session cookie, made on first use (#494).
pub torrents: OnceCell<torrent::Torrents>,
/// Caps how many torrents run at once when they are detached.
pub torrent_slots: Arc<Semaphore>,
/// Needed because a subscribed OPML rewrites the feed list as it syncs.
pub config_path: PathBuf,
/// Run torrents off the command worker. A torrent takes minutes to fetch metadata and
/// then seeds for up to an hour, and the worker is sequential -- inline, one torrent
/// more to download, and the worker is sequential -- inline, one torrent
/// stops every feed scan, every HTTP download and every status command behind it.
/// A one-shot CLI run keeps them inline, or the process would exit mid-download.
pub detach_torrents: bool,
@@ -208,9 +207,21 @@ impl Ctx {
self.directory_wake.notify_one();
}
pub(crate) async fn torrents(&self) -> Result<&torrent::Torrents> {
/// After an enclosure's files are deleted: its torrent, if it was one, out of qBittorrent too
/// (#495). Best effort; the files are gone whatever qBittorrent says.
pub(crate) async fn forget_torrent(&self, enclosure: i64, path: &str) {
let cfg = self.cfg();
self.torrents.get_or_try_init(|| torrent::Torrents::new(&cfg)).await
if !cfg.torrent.on() || !torrent::is_own_folder(std::path::Path::new(path), enclosure) {
return;
}
match self.torrents().await {
Ok(t) => t.forget(&cfg, enclosure).await,
Err(e) => tracing::warn!(error = %format!("{e:#}"), "no qBittorrent client"),
}
}
pub(crate) async fn torrents(&self) -> Result<&torrent::Torrents> {
self.torrents.get_or_try_init(|| async { torrent::Torrents::new() }).await
}
}

View File

@@ -84,6 +84,9 @@ async fn create_missing(orm: &DatabaseConnection) -> Result<()> {
// files through enclosures_entry read every file row of their feeds, 58 ms a feed list
// (#165). Also what the healthcheck's count and the Downloaded filter look for.
"CREATE INDEX IF NOT EXISTS enclosures_on_disk ON enclosures (feed_id, guid) WHERE path IS NOT NULL",
// The few files waiting to download, which the status counts every 30 s: without it, a
// scan of all 690,000 enclosures, 92 ms each time, to find a handful (#489).
"CREATE INDEX IF NOT EXISTS enclosures_pending ON enclosures (id) WHERE state = 'pending'",
"CREATE UNIQUE INDEX IF NOT EXISTS users_name_lower ON users (lower(name))",
// Every key and date an item list sorts by, so `entries_where` pages from the index alone
// and visits the table only for the rows it shows. Sorting All Subscriptions from the
@@ -123,6 +126,17 @@ async fn create_missing(orm: &DatabaseConnection) -> Result<()> {
orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?;
}
}
if orm.execute_unprepared("SELECT chapters FROM entries LIMIT 0").await.is_err() {
// Stored items get theirs as a scan finds them told differently, by this alone (#477);
// forgetting how each feed was last seen makes its next read a whole one, so the episodes
// out now have their chapters before their podcast next publishes.
for sql in [
"ALTER TABLE entries ADD COLUMN chapters TEXT",
"UPDATE feeds SET etag = NULL, last_modified = NULL, body_hash = NULL",
] {
orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?;
}
}
if orm.execute_unprepared("SELECT typesafe_key FROM users LIMIT 0").await.is_err() {
let sql = "ALTER TABLE users ADD COLUMN typesafe_key TEXT";
orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?;
@@ -313,7 +327,13 @@ thread_local! {
/// shortcut: half the queries, measured by difference; a wrapper on sqlx's pool would see all.
fn waited(started: std::time::Instant) {
if let Some(q) = LAST_QUERY.take() {
crate::metrics::DB_WAIT.observe("", started.elapsed().saturating_sub(q).as_secs_f64());
let wait = started.elapsed().saturating_sub(q);
crate::metrics::DB_WAIT.observe("", wait.as_secs_f64());
// On the step too, so a slow one in Tempo says whether it waited for a connection or for
// Postgres: the metric's spread could not say which of a page's queries it was.
let span = tracing::Span::current();
span.record("wait_ms", wait.as_millis() as u64);
span.record("query_ms", q.as_millis() as u64);
}
}
@@ -828,8 +848,8 @@ impl Db {
.exec(
"INSERT INTO entries
(feed_id, guid, title, link, published, description, first_seen,
image, duration, episode, season, markdown, search_text)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
image, duration, episode, season, markdown, search_text, chapters)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT DO NOTHING",
vec![
feed_id.into(),
@@ -845,6 +865,7 @@ impl Db {
e.season.into(),
e.markdown.clone().into(),
crate::search::search_text(e.title.as_deref(), e.description.as_deref()).into(),
e.chapters.clone().into(),
],
)
.await?;
@@ -858,6 +879,7 @@ impl Db {
episode = coalesce($7, episode),
season = coalesce($8, season),
markdown = coalesce($9, markdown),
chapters = coalesce($10, chapters),
-- 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)
@@ -874,6 +896,7 @@ impl Db {
e.episode.into(),
e.season.into(),
e.markdown.clone().into(),
e.chapters.clone().into(),
],
)
.await?;
@@ -1124,6 +1147,48 @@ impl Db {
.collect()
}
/// Up to `limit` items stored without a title, after the item `after` in (feed, guid) order:
/// feed, guid, description and first file, for naming them (#502). In order, not by
/// `title IS NULL` alone, because one with neither text nor file stays untitled and would be
/// read again forever.
pub async fn untitled(
&self,
after: (&str, &str),
limit: i64,
) -> Result<Vec<(String, String, Option<String>, Option<String>)>> {
self.rows(
"SELECT e.feed_id, e.guid, e.description,
(SELECT x.url FROM enclosures x WHERE x.feed_id = e.feed_id AND x.guid = e.guid
ORDER BY x.id LIMIT 1) AS file
FROM entries e
WHERE e.title IS NULL AND (e.feed_id > $1 OR (e.feed_id = $1 AND e.guid > $2))
ORDER BY e.feed_id, e.guid LIMIT $3",
vec![after.0.into(), after.1.into(), limit.into()],
)
.await?
.iter()
.map(|r| {
Ok((
r.try_get("", "feed_id")?,
r.try_get("", "guid")?,
r.try_get("", "description")?,
r.try_get("", "file")?,
))
})
.collect()
}
/// Names an untitled item, unless a scan has titled it meanwhile, and leaves its search text to
/// be made again with the name in it.
pub async fn name_untitled(&self, feed_id: &str, guid: &str, title: &str) -> Result<()> {
self.exec(
"UPDATE entries SET title = $3, search_text = NULL WHERE feed_id = $1 AND guid = $2 AND title IS NULL",
vec![feed_id.into(), guid.into(), title.into()],
)
.await?;
Ok(())
}
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",
@@ -2673,12 +2738,15 @@ impl Db {
/// The next N enclosures with no file, newest entry first -- what "download latest"
/// queues up.
/// 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.
/// Download latest, or Download this season, queues. Latest leaves out what retention removed,
/// which it would only fetch again; a season asked for by name is wanted whole, and leaving
/// those out said all of a season was on iPX when retention had taken every file (#483). One
/// on its way already is not asked for twice.
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::Any => ("AND x.state <> 'reaped'".into(), 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")),
};
@@ -2686,7 +2754,7 @@ impl Db {
&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}
WHERE x.feed_id = {feed} AND x.path IS NULL AND x.state <> 'downloading' {which}
ORDER BY {order}
LIMIT {limit}"
),
@@ -2698,6 +2766,14 @@ impl Db {
.collect()
}
/// Where an item's chapters are, when its feed says (#477).
pub async fn chapters_url(&self, feed_id: &str, guid: &str) -> Result<Option<String>> {
Ok(entries::Entity::find_by_id((feed_id.to_owned(), guid.to_owned()))
.one(&self.orm)
.await?
.and_then(|e| e.chapters))
}
pub async fn enclosure(&self, id: i64) -> Result<Option<EncRow>> {
Ok(enclosures::Entity::find_by_id(id).one(&self.orm).await?.map(EncRow::from))
}
@@ -2938,12 +3014,20 @@ impl Db {
let feed = a.p(feed_id);
let guids: Vec<String> = entries.iter().map(|e| a.p(e.guid.clone())).collect();
let sql = format!(
"SELECT guid, title, description, image, duration, episode, season, markdown FROM entries
"SELECT guid, title, description, image, duration, episode, season, markdown, chapters FROM entries
WHERE feed_id = {feed} AND guid IN ({})",
guids.join(", ")
);
type Stored =
(Option<String>, Option<String>, Option<String>, Option<i64>, Option<i64>, Option<i64>, Option<String>);
type Stored = (
Option<String>,
Option<String>,
Option<String>,
Option<i64>,
Option<i64>,
Option<i64>,
Option<String>,
Option<String>,
);
let mut stored = std::collections::HashMap::<String, Stored>::new();
for r in self.rows(&sql, a.0).await? {
stored.insert(
@@ -2956,6 +3040,7 @@ impl Db {
r.try_get("", "episode")?,
r.try_get("", "season")?,
r.try_get("", "markdown")?,
r.try_get("", "chapters")?,
),
);
}
@@ -2973,6 +3058,7 @@ impl Db {
|| differs(&e.episode, &s.4)
|| differs(&e.season, &s.5)
|| differs(&e.markdown, &s.6)
|| differs(&e.chapters, &s.7)
})
})
.map(|e| e.guid.clone())
@@ -2984,7 +3070,7 @@ impl Db {
self.rows(
"SELECT url, last_error FROM enclosures
WHERE feed_id = $1 AND state = 'skipped' AND last_error IS NOT NULL
AND last_error <> 'torrents disabled'",
AND last_error NOT IN ('torrents disabled', 'NZBs disabled')",
vec![feed_id.into()],
)
.await?
@@ -3036,7 +3122,11 @@ pub enum EntryFlag {
/// A span for one step of a request or a scan, and none outside one: the healthcheck and the page's
/// live updates run the same code, and every call there would be a trace of its own.
pub fn step(of: &'static str) -> tracing::Span {
if tracing::Span::current().is_none() { tracing::Span::none() } else { tracing::info_span!("step", of) }
if tracing::Span::current().is_none() {
tracing::Span::none()
} else {
tracing::info_span!("step", of, wait_ms = tracing::field::Empty, query_ms = tracing::field::Empty)
}
}
/// A file on disk with no DeadAir copy made since it was downloaded (issue #171).
@@ -3788,6 +3878,25 @@ mod tests {
assert_eq!(db.http_state("f").await.unwrap().etag.as_deref(), Some("\"b\""));
}
#[tokio::test]
async fn a_database_from_before_chapters_gains_them_and_reads_every_feed_whole() {
let db = Db::memory().await.unwrap();
db.record_feed("f", "https://x/f", Some("F"), None, None, None, None, None, None).await.unwrap();
db.set_body("f", "abc").await.unwrap();
// A database from before #477.
db.exec_for_test("ALTER TABLE entries DROP COLUMN chapters").await.unwrap();
create_missing(&db.orm).await.unwrap();
assert_eq!(db.http_state("f").await.unwrap().body_hash, None, "read whole, so stored items get theirs");
let e =
crate::feed::Entry { guid: "g".into(), chapters: Some("https://x/g.json".into()), ..Default::default() };
db.record_entry("f", &e).await.unwrap();
assert_eq!(db.chapters_url("f", "g").await.unwrap().as_deref(), Some("https://x/g.json"));
// Opened again with nothing missing, it forgets nothing.
db.set_body("f", "def").await.unwrap();
create_missing(&db.orm).await.unwrap();
assert_eq!(db.http_state("f").await.unwrap().body_hash.as_deref(), Some("def"));
}
#[tokio::test]
async fn a_database_from_before_body_hashes_gains_the_columns() {
let db = Db::memory().await.unwrap();
@@ -3860,6 +3969,42 @@ mod tests {
assert!(!order_sql("x'; --", "asc").contains("x'"));
}
#[tokio::test]
async fn items_stored_untitled_are_named_once_from_their_words_or_file() {
let db = Db::memory().await.unwrap();
db.exec_for_test(
"INSERT INTO entries (feed_id, guid, title, description, first_seen, search_text) VALUES
('f','words',NULL,'<p>Hello there</p>',1,'x'), ('f','file',NULL,NULL,2,'x'),
('f','none',NULL,NULL,3,'x'), ('f','kept','Mine','Other words',4,'x');
INSERT INTO enclosures (id, feed_id, guid, url, state) VALUES (1,'f','file','http://x/Ep%201.mp3','skipped');",
)
.await
.unwrap();
crate::search::name_untitled(&db).await.unwrap();
let rows = db.rows("SELECT guid, title, search_text FROM entries ORDER BY first_seen", vec![]).await.unwrap();
let got: Vec<(String, Option<String>, Option<String>)> = rows
.iter()
.map(|r| {
(r.try_get("", "guid").unwrap(), r.try_get("", "title").unwrap(), r.try_get("", "search_text").unwrap())
})
.collect();
let named = |g: &str, t: Option<&str>, search: Option<&str>| {
(g.to_owned(), t.map(str::to_owned), search.map(str::to_owned))
};
assert_eq!(
got,
[
named("words", Some("Hello there"), None),
named("file", Some("Ep 1"), None),
// Nothing to name it by: left alone, search text and all, and not looked at forever.
named("none", None, Some("x")),
named("kept", Some("Mine"), Some("x")),
]
);
// A second pass finds nothing more to do.
crate::search::name_untitled(&db).await.unwrap();
}
#[tokio::test]
async fn the_feed_list_in_one_go_matches_asking_feed_by_feed() {
let db = Db::memory().await.unwrap();
@@ -4240,6 +4385,18 @@ mod tests {
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"));
// A season asked for whole takes back what retention removed; Download latest does not,
// and nothing on its way already is asked for twice (#483).
db.exec_for_test(
"INSERT INTO enclosures (id, feed_id, guid, url, path, state) VALUES
(1, 'f', 'a', 'http://x/a.mp3', NULL, 'reaped'), (2, 'f', 'b', 'http://x/b.mp3', NULL, 'downloading'),
(3, 'f', 'c', 'http://x/c.mp3', NULL, 'pending');",
)
.await
.unwrap();
assert_eq!(db.undownloaded("f", Season::Of(1), 300).await.unwrap(), [1]);
assert_eq!(db.undownloaded("f", Season::Any, 5).await.unwrap(), [3]);
}
#[tokio::test]

View File

@@ -590,7 +590,7 @@ async fn ffmpeg(args: &[&str]) -> Result<String> {
Ok(log)
}
async fn run_out(prog: &str, args: &[&str]) -> Result<String> {
pub(crate) async fn run_out(prog: &str, args: &[&str]) -> Result<String> {
let out = command(prog).args(args).output().await.with_context(|| format!("running {prog}"))?;
if !out.status.success() {
bail!("{prog} failed: {}", String::from_utf8_lossy(&out.stderr).trim());

View File

@@ -114,8 +114,32 @@ fn disposition_filename(header: &str) -> Option<String> {
/// What the download turned out to be, once the bytes were on disk.
pub enum Kind {
File,
/// A .torrent body, whatever the advertised MIME said. Step 7 takes it from here.
/// A .torrent or an .nzb body, whatever the advertised MIME said: handed on, not filed.
Via(Via),
}
/// Where an enclosure goes instead of being downloaded here: a torrent to qBittorrent (#494), an
/// NZB to SABnzbd (#496).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Via {
Torrent,
Nzb,
}
impl Via {
pub fn on(self, cfg: &Config) -> bool {
match self {
Via::Torrent => cfg.torrent.on(),
Via::Nzb => cfg.nzb.on(),
}
}
/// The `last_error` of one held back while its kind is off, which no filter can overturn.
pub fn off(self) -> &'static str {
match self {
Via::Torrent => "torrents disabled",
Via::Nzb => "NZBs disabled",
}
}
}
pub struct Downloaded {
@@ -174,7 +198,8 @@ pub async fn download(
let _ = tokio::fs::remove_file(&tmp).await;
bail!("server returned an HTML page, not a media file");
}
Sniffed::Torrent => Kind::Torrent,
Sniffed::Torrent => Kind::Via(Via::Torrent),
Sniffed::Nzb => Kind::Via(Via::Nzb),
Sniffed::Other => Kind::File,
};
@@ -220,15 +245,23 @@ pub fn playable(path: &Path) -> PathBuf {
best.map_or_else(|| path.to_owned(), |(_, p)| p)
}
/// Advertised as a torrent, before spending any bandwidth on it.
pub fn looks_like_torrent(url: &str, mime: Option<&str>) -> bool {
mime.is_some_and(|m| m.to_ascii_lowercase().contains("torrent"))
|| url.split('?').next().unwrap_or(url).to_ascii_lowercase().ends_with(".torrent")
/// Advertised as a torrent or an NZB, before spending any bandwidth on it.
pub fn handed_on(url: &str, mime: Option<&str>) -> Option<Via> {
let mime = mime.unwrap_or("").to_ascii_lowercase();
let path = url.split('?').next().unwrap_or(url).to_ascii_lowercase();
if mime.contains("torrent") || path.ends_with(".torrent") {
Some(Via::Torrent)
} else if mime.contains("nzb") || path.ends_with(".nzb") {
Some(Via::Nzb)
} else {
None
}
}
enum Sniffed {
Html,
Torrent,
Nzb,
Other,
}
@@ -244,6 +277,12 @@ async fn sniff(path: &Path) -> Result<Sniffed> {
if lead.starts_with("<!doctype html") || lead.starts_with("<html") {
return Ok(Sniffed::Html);
}
if lead.starts_with("<!doctype nzb")
|| lead.starts_with("<nzb")
|| lead.starts_with("<?xml") && lead.contains("<nzb")
{
return Ok(Sniffed::Nzb);
}
Ok(Sniffed::Other)
}
@@ -423,6 +462,15 @@ mod tests {
assert_eq!(folder_for(&cfg, "id", &f, None), "etc/Show");
}
#[test]
fn torrents_and_nzbs_are_told_by_type_or_by_name() {
assert_eq!(handed_on("http://x/a.mp3", Some("application/x-bittorrent")), Some(Via::Torrent));
assert_eq!(handed_on("http://x/a.TORRENT?k=1", None), Some(Via::Torrent));
assert_eq!(handed_on("http://x/a", Some("application/x-nzb")), Some(Via::Nzb));
assert_eq!(handed_on("http://x/get.nzb?id=3", Some("")), Some(Via::Nzb));
assert_eq!(handed_on("http://x/a.mp3?f=.nzb", Some("audio/mpeg")), None, "the query is not the name");
}
#[test]
fn a_torrent_folder_plays_its_largest_file_and_deletes_whole() {
let d = std::env::temp_dir().join(format!("ipx-torrent-test-{}", std::process::id()));
@@ -464,6 +512,7 @@ mod tests {
.route("/ep.mp3", get(|| async { "ID3 an episode" }))
.route("/wall.mp3", get(|| async { "\n <!DOCTYPE html><html>Sign in</html>" }))
.route("/show.torrent", get(|| async { "d8:announce35:udp://tracker.example:80/announcee" }))
.route("/show.nzb", get(|| async { "<?xml version=\"1.0\"?>\n<!DOCTYPE nzb><nzb xmlns=\"x\"/>" }))
.route("/gone.mp3", get(|| async { axum::http::StatusCode::NOT_FOUND }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let at = listener.local_addr().unwrap();
@@ -500,7 +549,8 @@ mod tests {
assert!(format!("{wall:#}").contains("HTML page"), "{wall:#}");
assert!(!d.join(".ipx-incomplete/wall.mp3").exists(), "a login page is not kept");
assert!(matches!(get("/show.torrent").await.unwrap().kind, Kind::Torrent));
assert!(matches!(get("/show.torrent").await.unwrap().kind, Kind::Via(Via::Torrent)));
assert!(matches!(get("/show.nzb").await.unwrap().kind, Kind::Via(Via::Nzb)), "an NZB is not an episode (#496)");
assert!(format!("{:#}", get("/gone.mp3").await.err().unwrap()).contains("404"));
let _ = std::fs::remove_dir_all(&d);
}

View File

@@ -86,6 +86,9 @@ pub mod entries {
pub duration: Option<i64>,
pub episode: Option<i64>,
pub season: Option<i64>,
/// Where its chapters are, from `<podcast:chapters>` (#477).
#[sea_orm(column_type = "Text", nullable)]
pub chapters: Option<String>,
/// The title and the text without markup, lowercased and cut short, which search reads
/// (#459); none until search.rs makes it.
#[sea_orm(column_type = "Text", nullable)]

View File

@@ -7,6 +7,7 @@ mod access;
mod art;
mod auth;
mod catalogue;
mod chapters;
mod cli;
mod config;
mod ctx;
@@ -23,6 +24,7 @@ mod lists;
mod logbuf;
mod logging;
mod metrics;
mod nzb;
mod play;
mod push;
mod retention;

349
crates/ipx/src/nzb.rs Normal file
View File

@@ -0,0 +1,349 @@
//! NZB enclosures through SABnzbd's API (#496), the way torrents go through qBittorrent (#494).
//! ipx fetches the .nzb itself, adds it under a category of its own with a job name it can find
//! again, follows it through the queue and post-processing, and moves the finished folder into
//! the enclosure's own. SABnzbd takes no save path for a job, only a category's folder, so that
//! folder has to be one ipx can see, inside `download_dir`.
use anyhow::{Context, Result, anyhow, bail};
use reqwest::multipart::{Form, Part};
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::time::{Duration, Instant};
use crate::config::Config;
/// Not the guarded client feeds are fetched with: SABnzbd is on the LAN by design, at the address
/// the admin gave, which the guard would refuse (#320).
static HTTP: LazyLock<reqwest::Client> =
LazyLock::new(|| reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("a client"));
/// One job in the queue, as much as ipx reads. SABnzbd gives sizes there as strings of MB.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
struct Queued {
nzo_id: String,
filename: String,
mb: String,
mbleft: String,
}
/// One job in the history: downloaded, and being or done being post-processed.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
struct Done {
nzo_id: String,
name: String,
status: String,
storage: String,
bytes: i64,
fail_message: String,
}
enum Job {
Queued(Queued),
Done(Done),
}
const POLL: Duration = Duration::from_secs(2);
/// Downloads an NZB through SABnzbd into the enclosure's own folder inside `feed_dir`, which is the
/// path returned, with its size.
pub async fn fetch(
cfg: &Config,
client: &reqwest::Client,
url: &str,
feed_dir: &Path,
enclosure: i64,
mut on_progress: impl FnMut(u64, u64),
) -> Result<(PathBuf, u64)> {
let limit = Duration::from_secs(cfg.nzb.stall_mins.max(1) * 60);
let name = job_name(enclosure);
// There already when ipx stopped while it ran (#410): taken up where SABnzbd has it.
if find(cfg, &name).await?.is_none() {
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
let file = tokio::time::timeout(limit, nzb_file(client, url))
.await
.map_err(|_| anyhow!("no .nzb after {} minutes, gave up", limit.as_secs() / 60))??;
let form = Form::new().part("name", Part::bytes(file).file_name(format!("{name}.nzb")));
let said: Added =
call(cfg, &[("mode", "addfile"), ("nzbname", &name), ("cat", &cfg.nzb.category)], Some(form)).await?;
if said.nzo_ids.is_empty() {
bail!("SABnzbd would not take the NZB");
}
}
let mut last = (-1i64, Instant::now());
let done = loop {
tokio::time::sleep(POLL).await;
// A SABnzbd restarting is a pause, not a failure, until the stall limit says so.
let job = match find(cfg, &name).await {
Ok(j) => j,
Err(e) if last.1.elapsed() < limit => {
tracing::debug!(error = %format!("{e:#}"), "SABnzbd did not answer");
continue;
}
Err(e) => return Err(e),
};
let left = match job {
None => bail!("the NZB is no longer in SABnzbd"),
Some(Job::Done(d)) if d.status == "Completed" => break d,
Some(Job::Done(d)) if d.status == "Failed" => {
forget(cfg, "history", &d.nzo_id).await;
bail!("SABnzbd says the download failed: {}", d.fail_message);
}
// Verifying, repairing, unpacking: all of it is here, and a large repair is slow.
Some(Job::Done(_)) => {
last.1 = Instant::now();
continue;
}
Some(Job::Queued(q)) => {
let mb = |s: &str| (s.trim().parse::<f64>().unwrap_or(0.0) * 1_048_576.0) as i64;
let (total, left) = (mb(&q.mb), mb(&q.mbleft));
on_progress((total - left).max(0) as u64, total.max(0) as u64);
(left, q)
}
};
let (left, q) = left;
if last.0 < 0 || left < last.0 {
last = (left, Instant::now());
} else if last.1.elapsed() > limit {
forget(cfg, "queue", &q.nzo_id).await;
bail!("no progress for {} minutes, gave up", limit.as_secs() / 60);
}
};
let dir = feed_dir.join(&name);
let from = their_path(cfg, Path::new(&done.storage));
tokio::fs::create_dir_all(feed_dir).await?;
if tokio::fs::metadata(&from).await.with_context(|| format!("finding {}", from.display()))?.is_dir() {
tokio::fs::rename(&from, &dir).await
} else {
tokio::fs::create_dir_all(&dir).await?;
tokio::fs::rename(&from, dir.join(from.file_name().unwrap_or_default())).await
}
// shortcut: a rename only, so SABnzbd's category folder must be on the same mount as
// download_dir; copy across filesystems if one ever is not.
.with_context(|| format!("moving {} into {}", from.display(), dir.display()))?;
// Out of the history once its files are ipx's, so nothing there points at a folder gone.
forget(cfg, "history", &done.nzo_id).await;
Ok((dir, done.bytes.max(0) as u64))
}
#[derive(Deserialize)]
struct Added {
#[serde(default)]
nzo_ids: Vec<String>,
}
/// The job by its name, in the queue or the history.
async fn find(cfg: &Config, name: &str) -> Result<Option<Job>> {
#[derive(Deserialize)]
struct Slots<T> {
slots: Vec<T>,
}
#[derive(Deserialize)]
struct Q {
queue: Slots<Queued>,
}
#[derive(Deserialize)]
struct H {
history: Slots<Done>,
}
// search matches part of a name, so nzb-9 finds nzb-90 too: the exact one is picked out.
let q: Q = call(cfg, &[("mode", "queue"), ("search", name)], None).await?;
if let Some(j) = q.queue.slots.into_iter().find(|s| s.filename == name) {
return Ok(Some(Job::Queued(j)));
}
let h: H = call(cfg, &[("mode", "history"), ("search", name)], None).await?;
Ok(h.history.slots.into_iter().find(|s| s.name == name).map(Job::Done))
}
/// Takes a job out of the queue or the history, its files with it from the queue (they are half
/// of a download), not from the history (they are the episode's, or already moved). Logged, not
/// raised: what called it is already giving up, or done.
async fn forget(cfg: &Config, from: &str, nzo_id: &str) {
let files = if from == "queue" { "1" } else { "0" };
let query = [("mode", from), ("name", "delete"), ("value", nzo_id), ("del_files", files)];
if let Err(e) = call::<serde_json::Value>(cfg, &query, None).await {
tracing::warn!(error = %format!("{e:#}"), "could not remove the NZB from SABnzbd");
}
}
/// One call to the API. SABnzbd answers a wrong key or a bad call with 200 and `status: false`.
/// Everything goes in the body, which SABnzbd reads as it reads a query: reqwest's errors say the
/// URL, and the key in it would have gone to the log and the episode's error.
async fn call<T: serde::de::DeserializeOwned>(cfg: &Config, query: &[(&str, &str)], form: Option<Form>) -> Result<T> {
let n = &cfg.nzb;
let url = format!("{}/api", n.sabnzbd_url.trim_end_matches('/'));
let mode = query.first().map_or("", |q| q.1);
let params = query.iter().copied().chain([("apikey", n.api_key.as_str()), ("output", "json")]);
let req = match form {
Some(f) => HTTP.post(url).multipart(params.fold(f, |f, (k, v)| f.text(k.to_owned(), v.to_owned()))),
None => HTTP.post(url).form(&params.collect::<Vec<_>>()),
};
let body = req
.send()
.await
.with_context(|| format!("asking SABnzbd ({mode})"))?
.error_for_status()
.with_context(|| format!("SABnzbd refused {mode}"))?
.text()
.await?;
let v: serde_json::Value = serde_json::from_str(&body).with_context(|| format!("reading SABnzbd's {mode}"))?;
if v.get("status") == Some(&serde_json::Value::Bool(false)) {
bail!("SABnzbd refused {mode}: {}", v.get("error").and_then(|e| e.as_str()).unwrap_or("no reason given"));
}
serde_json::from_value(v).with_context(|| format!("reading SABnzbd's {mode}"))
}
/// The job's name in SABnzbd, which is also the folder it finishes in.
fn job_name(enclosure: i64) -> String {
format!("nzb-{enclosure}")
}
/// Where ipx sees a path SABnzbd gave: `download_dir` in place of `save_path` when SABnzbd's mount
/// of it is somewhere else.
fn their_path(cfg: &Config, path: &Path) -> PathBuf {
let theirs = cfg.nzb.save_path.trim();
match path.strip_prefix(theirs) {
Ok(rest) if !theirs.is_empty() => cfg.general.download_dir.join(rest),
_ => path.to_owned(),
}
}
/// An NZB lists the articles of a release: a few MB even for a large one.
const MAX_NZB_FILE: usize = 20 << 20;
async fn nzb_file(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
let mut resp = client.get(url).send().await.context("fetching the .nzb")?.error_for_status()?;
let mut out = Vec::new();
while let Some(c) = resp.chunk().await.context("reading the .nzb")? {
out.extend_from_slice(&c);
if out.len() > MAX_NZB_FILE {
bail!("the .nzb is larger than {} MB, too large to be one", MAX_NZB_FILE >> 20);
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
/// A SABnzbd that, as the feed's server, serves the .nzb too. A job added is finished at once,
/// into its category's folder, and is in the history after one look at the queue. Its address,
/// and the calls it was asked to delete.
async fn sabnzbd(category_dir: PathBuf, episode: Vec<u8>) -> (std::net::SocketAddr, Arc<Mutex<Vec<String>>>) {
use axum::routing::{get, post};
use std::collections::HashMap;
type Jobs = Arc<Mutex<Vec<(String, u8)>>>;
let jobs: Jobs = Default::default();
let deleted: Arc<Mutex<Vec<String>>> = Default::default();
let (j, d) = (jobs.clone(), deleted.clone());
let app = axum::Router::new().route("/ep.nzb", get(|| async { "<?xml version=\"1.0\"?><nzb/>" })).route(
"/api",
post(move |body: axum::body::Bytes| async move {
// Either form: a multipart body read as text is enough to find a field's value.
let text = String::from_utf8_lossy(&body);
let q: HashMap<String, String> = if text.contains("Content-Disposition") {
let field = |p: &str| {
let (k, rest) = p.split_once('"')?;
Some((k.to_owned(), rest.split_once("\r\n\r\n")?.1.split("\r\n").next()?.to_owned()))
};
text.split("; name=\"").skip(1).filter_map(field).collect()
} else {
url::form_urlencoded::parse(&body).into_owned().collect()
};
if q["apikey"] != "key" {
return axum::Json(serde_json::json!({"status": false, "error": "API Key Incorrect"}));
}
let mut jobs = j.lock().unwrap();
let name = q.get("search").or(q.get("nzbname")).cloned().unwrap_or_default();
match q["mode"].as_str() {
"addfile" => {
assert_eq!(q["cat"], "ipx");
assert!(q["name"].starts_with("<?xml"), "the .nzb ipx fetched");
let folder = category_dir.join(&name);
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(folder.join("episode.mp3"), &episode).unwrap();
jobs.push((name, 0));
axum::Json(serde_json::json!({"status": true, "nzo_ids": ["SABnzbd_nzo_1"]}))
}
_ if q.get("name").is_some_and(|n| n == "delete") => {
d.lock().unwrap().push(format!("{} {} {}", q["mode"], q["value"], q["del_files"]));
jobs.clear();
axum::Json(serde_json::json!({"status": true}))
}
"queue" => {
let slots: Vec<_> = jobs.iter_mut().filter(|(n, _)| n.contains(&name)).filter(|(_, s)| *s == 0).map(|(n, s)| {
*s = 1;
serde_json::json!({"nzo_id": "SABnzbd_nzo_1", "filename": n, "mb": "2.0", "mbleft": "1.0"})
}).collect();
axum::Json(serde_json::json!({"queue": {"slots": slots}}))
}
"history" => {
let slots: Vec<_> = jobs.iter().filter(|(n, s)| n.contains(&name) && *s == 1).map(|(n, _)| serde_json::json!({
"nzo_id": "SABnzbd_nzo_1", "name": n, "status": "Completed", "bytes": episode.len(),
"storage": format!("/sab/ipx/{n}"),
})).collect();
axum::Json(serde_json::json!({"history": {"slots": slots}}))
}
m => panic!("no mode {m}"),
}
}),
);
let web = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let at = web.local_addr().unwrap();
tokio::spawn(async move { axum::serve(web, app).await });
(at, deleted)
}
#[tokio::test(flavor = "multi_thread")]
async fn an_nzb_lands_in_its_own_folder_and_leaves_sabnzbd_s_history() {
let root = std::env::temp_dir().join(format!("ipx-nzb-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let downloads = root.join("downloads");
let episode: Vec<u8> = (0..50_000u32).map(|i| (i % 251) as u8).collect();
let (at, deleted) = sabnzbd(downloads.join("ipx"), episode.clone()).await;
let mut cfg = Config::default();
cfg.general.download_dir = downloads.clone();
cfg.nzb.sabnzbd_url = format!("http://{at}/");
cfg.nzb.api_key = "key".into();
// SABnzbd sees download_dir as /sab, and its category's folder inside it.
cfg.nzb.save_path = "/sab".into();
let mut seen = Vec::new();
let (path, bytes) =
fetch(&cfg, &reqwest::Client::new(), &format!("http://{at}/ep.nzb"), &downloads.join("Show"), 9, |d, t| {
seen.push((d, t))
})
.await
.unwrap();
assert_eq!(path, downloads.join("Show/nzb-9"));
assert_eq!(bytes, episode.len() as u64);
assert_eq!(std::fs::read(path.join("episode.mp3")).unwrap(), episode);
assert_eq!(seen, [(1 << 20, 2 << 20)], "progress from the queue's MB");
assert_eq!(*deleted.lock().unwrap(), ["history SABnzbd_nzo_1 0"], "out of the history, files kept");
cfg.nzb.api_key = "wrong".into();
let err = fetch(&cfg, &reqwest::Client::new(), &format!("http://{at}/ep.nzb"), &downloads, 10, |_, _| {})
.await
.unwrap_err();
assert!(format!("{err:#}").contains("API Key Incorrect"), "{err:#}");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_path_sabnzbd_gives_is_where_ipx_sees_it() {
let mut cfg = Config::default();
cfg.general.download_dir = "/downloads".into();
let p = Path::new("/ipx-downloads/.sabnzbd/nzb-9");
assert_eq!(their_path(&cfg, p), p, "the same mount");
cfg.nzb.save_path = "/ipx-downloads".into();
assert_eq!(their_path(&cfg, p), Path::new("/downloads/.sabnzbd/nzb-9"));
}
}

View File

@@ -142,6 +142,10 @@ pub(crate) async fn reap(ctx: &Ctx, dry_run: bool, standalone: bool) -> Result<(
}
let removed = r.aged_out.iter().chain(r.over_quota.iter());
for c in removed {
// Only what is really gone: a folder that would not delete keeps seeding.
if !dry_run && !Path::new(&c.path).exists() {
ctx.forget_torrent(c.id, &c.path).await;
}
ctx.out.emit(Event::Reaped { path: c.path.clone(), bytes: c.bytes.max(0) as u64, dry_run });
}
if standalone {

View File

@@ -3,7 +3,7 @@
use crate::catalogue::Sub;
use crate::ctx::Ctx;
use crate::ipc::Event;
use crate::{catalogue, cli, config, db, download, feed, lists, metrics, signals, torrent};
use crate::{catalogue, cli, config, db, download, feed, lists, metrics, nzb, signals};
use anyhow::Result;
use std::collections::HashSet;
use std::path::Path;
@@ -229,6 +229,38 @@ pub(crate) fn quiet(usual: u64, same_for: Option<u64>) -> u64 {
}
}
fn sha256(bytes: &[u8]) -> String {
use sha2::Digest as _;
sha2::Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
}
/// What a feed's "the same as last time" is decided on (#242): its items and what it calls
/// itself, not its bytes. Substack stamps a new build time on every read and Patreon signs its
/// file links afresh, so their bytes were never the same and they stayed hourly with nothing
/// new (#503). An item's text edited with nothing else changed waits for the next full read.
fn identity(p: &feed::ParsedFeed) -> Vec<u8> {
let bare = |u: &str| u.split(['?', '#']).next().unwrap_or_default().to_owned();
let mut out = String::new();
let mut put = |s: &str| {
out.push_str(s);
out.push('\0');
};
put(p.title.as_deref().unwrap_or_default());
put(&bare(p.image.as_deref().unwrap_or_default()));
put(p.description.as_deref().unwrap_or_default());
put(&p.ttl_mins.map(|t| t.to_string()).unwrap_or_default());
for e in &p.entries {
put(&e.guid);
put(e.title.as_deref().unwrap_or_default());
put(&e.published.map(|t| t.to_string()).unwrap_or_default());
for enc in &e.enclosures {
put(&bare(&enc.url));
}
put("\x1e");
}
out.into_bytes()
}
pub(crate) fn backoff(usual: u64, failing_for: Option<u64>) -> u64 {
const CEILING: u64 = 86_400;
match failing_for {
@@ -354,26 +386,27 @@ pub(crate) async fn scan_one(
return Ok(Outcome::Empty);
}
// The same body as last time, from a server that ignores "not modified": nothing to read,
// A subscribed OPML is a list of feeds, not a feed. The original matched on a ".opml"
// URL; sniffing the body also catches one served from a URL without that extension.
let opml = feed::is_opml(&bytes);
let parsed = if opml { None } else { Some(feed::parse(&bytes)?) };
// The same feed as last time, from a server that ignores "not modified": nothing to read,
// as a 304 would have said (#242). Not when something is missing that a read would fill, as
// above, nor when someone asked for a full check.
let hash = {
use sha2::Digest as _;
sha2::Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect::<String>()
};
let hash = sha256(&match &parsed {
Some(p) => identity(p),
None => bytes.to_vec(),
});
if !force && state.body_hash.as_deref() == Some(hash.as_str()) && stored.entries > 0 && stored.image.is_some() {
ctx.db.touch_feed(id, &feed_cfg.url).await?;
return Ok(Outcome::NotModified);
}
// A subscribed OPML is a list of feeds, not a feed. The original matched on a ".opml"
// URL; sniffing the body also catches one served from a URL without that extension.
if feed::is_opml(&bytes) {
let Some(mut parsed) = parsed else {
ctx.db.touch_feed(id, &feed_cfg.url).await?;
return lists::sync_opml(ctx, id, &bytes).await;
}
let mut parsed = feed::parse(&bytes)?;
};
// Artwork on http moves to https where its host serves it (#110), before it is compared
// with what is stored, which is then the https address too.
let mut secure = std::collections::HashMap::new();
@@ -532,9 +565,10 @@ pub(crate) async fn scan_one(
let dest_dir = cfg.general.download_dir.join(&folder);
for item in ctx.db.pending(id, budget).await? {
if download::looks_like_torrent(&item.url, item.mime.as_deref()) {
if !ctx.cfg().torrent.enabled {
ctx.db.mark_enclosure(&item.url, "skipped", Some("torrents disabled")).await?;
// NZBs go the torrents' way and are counted with them (#496).
if let Some(via) = download::handed_on(&item.url, item.mime.as_deref()) {
if !via.on(&ctx.cfg()) {
ctx.db.mark_enclosure(&item.url, "skipped", Some(via.off())).await?;
ctx.out.emit(Event::TorrentDeferred { feed: id.to_string(), url: item.url.clone() });
scan.torrents += 1;
continue;
@@ -542,11 +576,11 @@ pub(crate) async fn scan_one(
if ctx.detach_torrents {
// 'downloading' keeps the next scan from queueing it a second time.
ctx.db.mark_enclosure(&item.url, "downloading", None).await?;
spawn_torrent(ctx, id.to_string(), item.id, item.url.clone(), dest_dir.clone());
spawn_torrent(ctx, via, id.to_string(), item.id, item.url.clone(), dest_dir.clone());
scan.torrents += 1;
continue;
}
match torrent_one(ctx, id, item.id, &item.url, &dest_dir).await {
match torrent_one(ctx, via, id, item.id, &item.url, &dest_dir).await {
Ok((path, bytes)) => {
ctx.db.mark_downloaded(&item.url, &path, bytes).await?;
ctx.out.emit(Event::DownloadDone {
@@ -746,23 +780,23 @@ pub(crate) async fn fetch_one(
})
.await?;
if matches!(got.kind, download::Kind::Torrent) {
// The MIME lied. Hand the URL to the torrent session instead of filing a .torrent
// as if it were an episode.
if let download::Kind::Via(via) = got.kind {
// The MIME lied. Hand the URL to qBittorrent or SABnzbd instead of filing a .torrent or
// an .nzb as if it were an episode.
let _ = tokio::fs::remove_file(&got.tmp).await;
if !ctx.cfg().torrent.enabled {
ctx.db.mark_enclosure(url, "skipped", Some("torrents disabled")).await?;
anyhow::bail!("body is a torrent and torrents are disabled");
if !via.on(&ctx.cfg()) {
ctx.db.mark_enclosure(url, "skipped", Some(via.off())).await?;
anyhow::bail!("body is a {via:?} and {}", via.off());
}
// As one advertised as a torrent goes: off the worker where it can be, and recorded either
// way. Run here and never recorded, it stayed pending, and every scan of its feed ran it
// again, on the worker, for up to the stall limit and the seeding time (#155).
if ctx.detach_torrents {
ctx.db.mark_enclosure(url, "downloading", None).await?;
spawn_torrent(ctx, feed_id.to_owned(), enclosure, url.to_owned(), dest_dir.to_owned());
spawn_torrent(ctx, via, feed_id.to_owned(), enclosure, url.to_owned(), dest_dir.to_owned());
return Ok(None);
}
let (path, bytes) = torrent_one(ctx, feed_id, enclosure, url, dest_dir).await?;
let (path, bytes) = torrent_one(ctx, via, feed_id, enclosure, url, dest_dir).await?;
ctx.db.mark_downloaded(url, &path, bytes).await?;
return Ok(Some((path, bytes)));
}
@@ -772,9 +806,16 @@ pub(crate) async fn fetch_one(
Ok(Some((path, got.bytes)))
}
/// Runs a torrent off the command worker, so feed scans and HTTP downloads keep moving
/// while it fetches metadata, transfers and then seeds.
pub(crate) fn spawn_torrent(ctx: &Arc<Ctx>, feed_id: String, enclosure: i64, url: String, dest_dir: PathBuf) {
/// Runs a torrent or an NZB off the command worker, so feed scans and HTTP downloads keep moving
/// while qBittorrent or SABnzbd has it.
pub(crate) fn spawn_torrent(
ctx: &Arc<Ctx>,
via: download::Via,
feed_id: String,
enclosure: i64,
url: String,
dest_dir: PathBuf,
) {
let ctx = ctx.clone();
tokio::spawn(async move {
// Held for the whole job, so a feed full of torrents cannot open hundreds at once.
@@ -782,7 +823,7 @@ pub(crate) fn spawn_torrent(ctx: &Arc<Ctx>, feed_id: String, enclosure: i64, url
Ok(p) => p,
Err(_) => return,
};
let outcome = torrent_one(&ctx, &feed_id, enclosure, &url, &dest_dir).await;
let outcome = torrent_one(&ctx, via, &feed_id, enclosure, &url, &dest_dir).await;
let db = &ctx.db;
match outcome {
Ok((path, bytes)) => {
@@ -830,20 +871,19 @@ pub(crate) async fn download_one(ctx: &Arc<Ctx>, id: i64) -> Result<()> {
let dest_dir = cfg.general.download_dir.join(&folder);
ctx.out.emit(Event::FeedStart { feed: enc.feed_id.clone() });
let is_torrent = download::looks_like_torrent(&enc.url, enc.mime.as_deref());
if is_torrent && cfg.torrent.enabled && ctx.detach_torrents {
let via = download::handed_on(&enc.url, enc.mime.as_deref());
if let Some(via) = via
&& via.on(&cfg)
&& ctx.detach_torrents
{
ctx.db.mark_enclosure(&enc.url, "downloading", None).await?;
spawn_torrent(ctx, enc.feed_id.clone(), enc.id, enc.url.clone(), dest_dir);
spawn_torrent(ctx, via, enc.feed_id.clone(), enc.id, enc.url.clone(), dest_dir);
return Ok(());
}
let result = if is_torrent {
if !cfg.torrent.enabled {
Err(anyhow::anyhow!("torrents are disabled"))
} else {
torrent_one(ctx, &enc.feed_id, enc.id, &enc.url, &dest_dir).await.map(Some)
}
} else {
fetch_one(ctx, &enc.feed_id, enc.id, feed_cfg, &enc.url, &dest_dir).await
let result = match via {
Some(via) if !via.on(&cfg) => Err(anyhow::anyhow!("{}", via.off())),
Some(via) => torrent_one(ctx, via, &enc.feed_id, enc.id, &enc.url, &dest_dir).await.map(Some),
None => fetch_one(ctx, &enc.feed_id, enc.id, feed_cfg, &enc.url, &dest_dir).await,
};
match result {
@@ -879,6 +919,7 @@ pub(crate) async fn download_one(ctx: &Arc<Ctx>, id: i64) -> Result<()> {
#[tracing::instrument(name = "torrent", skip_all, fields(feed = feed_id, enclosure = enclosure))]
pub(crate) async fn torrent_one(
ctx: &Arc<Ctx>,
via: download::Via,
feed_id: &str,
enclosure: i64,
url: &str,
@@ -887,24 +928,27 @@ pub(crate) async fn torrent_one(
let name = download::filename_for(url, None);
let mut last_pct = -1i64;
let cfg = ctx.cfg();
ctx.torrents()
.await?
.fetch(&cfg, &ctx.client, url, &torrent::own_folder(dest_dir, enclosure), |done, total| {
if let Some(pct) = (done * 100).checked_div(total).map(|p| p as i64)
&& pct > last_pct
{
last_pct = pct;
ctx.out.emit(Event::Progress {
feed: feed_id.to_string(),
enclosure,
url: url.to_string(),
file: name.clone(),
done,
total: Some(total),
});
}
})
.await
let progress = |done: u64, total: u64| {
if let Some(pct) = (done * 100).checked_div(total).map(|p| p as i64)
&& pct > last_pct
{
last_pct = pct;
ctx.out.emit(Event::Progress {
feed: feed_id.to_string(),
enclosure,
url: url.to_string(),
file: name.clone(),
done,
total: Some(total),
});
}
};
match via {
download::Via::Torrent => {
ctx.torrents().await?.fetch(&cfg, &ctx.client, url, dest_dir, enclosure, progress).await
}
download::Via::Nzb => nzb::fetch(&cfg, &ctx.client, url, dest_dir, enclosure, progress).await,
}
}
#[cfg(test)]
@@ -953,6 +997,22 @@ mod tests {
assert_eq!(same(&set), hour, "someone's own schedule wins");
}
#[test]
fn a_feed_is_the_same_by_its_items_not_its_build_time_or_signed_links() {
let feed = |built: &str, token: &str, title: &str| {
let xml = format!(
"<rss><channel><title>Show</title><lastBuildDate>{built}</lastBuildDate>\
<item><guid>1</guid><title>{title}</title>\
<enclosure url=\"https://c.example/a.mp3?token={token}\" type=\"audio/mpeg\"/></item>\
</channel></rss>"
);
sha256(&identity(&feed::parse(xml.as_bytes()).unwrap()))
};
let first = feed("Mon, 01 Jan 2024 00:00:00 GMT", "a", "One");
assert_eq!(first, feed("Tue, 02 Jan 2024 00:00:00 GMT", "b", "One"), "rebuilt and re-signed, the same");
assert_ne!(first, feed("Mon, 01 Jan 2024 00:00:00 GMT", "a", "Two"), "an item renamed is a change");
}
#[tokio::test]
async fn the_same_body_again_is_not_modified_unless_a_check_is_forced() {
let base = empty_or_feed_server().await;
@@ -972,10 +1032,9 @@ mod tests {
matches!(scan_one(&ctx, "same", &cfg, &state, true, None).await, Ok(Outcome::Feed(_))),
"a forced check reads it"
);
// Changed: read, and the same from now.
let moved = config::Feed { url: format!("{base}/fixed"), ..feed() };
assert!(matches!(scan_one(&ctx, "same", &moved, &state, false, None).await, Ok(Outcome::Feed(_))));
assert_ne!(ctx.db.http_state("same").await.unwrap().body_hash, state.body_hash);
// Only an item's text edited: the same feed, read at the next forced or changed read (#503).
let edited = config::Feed { url: format!("{base}/fixed"), ..feed() };
assert!(matches!(scan_one(&ctx, "same", &edited, &state, false, None).await, Ok(Outcome::NotModified)));
}
#[test]
@@ -1089,17 +1148,17 @@ mod tests {
let state = |ctx: Arc<Ctx>| async move { ctx.db.strings_for_test("SELECT state FROM enclosures").await };
// Detached, as the daemon runs them: no slot free, so it waits its turn as 'downloading'.
let mut ctx = test_ctx(config::Config::default()).await;
let mut on = config::Config::default();
on.torrent.qbittorrent_url = "http://127.0.0.1:9".into();
let mut ctx = test_ctx(on).await;
ctx.detach_torrents = true;
ctx.torrent_slots = Arc::new(tokio::sync::Semaphore::new(0));
let ctx = Arc::new(ctx);
assert_eq!(scan(ctx.clone()).await, (0, 1), "counted as a torrent, not a download");
assert_eq!(state(ctx).await, ["downloading"], "so the next scan does not queue it again");
// Turned off, it is skipped and still counted.
let mut cfg = config::Config::default();
cfg.torrent.enabled = false;
let ctx = Arc::new(test_ctx(cfg).await);
// With no qBittorrent to send it to, it is skipped and still counted.
let ctx = Arc::new(test_ctx(config::Config::default()).await);
assert_eq!(scan(ctx.clone()).await, (0, 1));
assert_eq!(state(ctx).await, ["skipped"]);
}

View File

@@ -55,6 +55,7 @@ pub async fn run(ctx: Arc<Ctx>, mut stop: tokio::sync::watch::Receiver<bool>) {
/// Every item without search text, given one, a batch at a time: how many.
async fn fill(ctx: &Ctx) -> anyhow::Result<usize> {
name_untitled(&ctx.db).await?;
let mut made = 0;
loop {
let batch = ctx.db.unsearched(BATCH).await?;
@@ -68,6 +69,23 @@ async fn fill(ctx: &Ctx) -> anyhow::Result<usize> {
}
}
/// Names the items stored before a feed's untitled ones were named as they were read (#502),
/// once, in batches; then finds none and costs one query a pass. Before the search text, which
/// the name goes into.
pub(crate) async fn name_untitled(db: &crate::db::Db) -> anyhow::Result<()> {
let mut after = (String::new(), String::new());
loop {
let batch = db.untitled((&after.0, &after.1), BATCH).await?;
let Some(last) = batch.last() else { return Ok(()) };
after = (last.0.clone(), last.1.clone());
for (feed, guid, description, file) in &batch {
if let Some(name) = crate::feed::untitled_name(description.as_deref(), file.as_deref()) {
db.name_untitled(feed, guid, &name).await?;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -1,20 +1,39 @@
//! Torrent enclosures via librqbit. Replaces iPXDownloader.getTorrent and the vendored
//! BitTorrent 4.2.1 + khashmir tree.
//! Torrent enclosures through qBittorrent's Web API (#494). ipx fetches the .torrent itself, hands
//! it over with the enclosure's own folder as its save path, and watches it to the end; qBittorrent
//! downloads it and seeds it to the limits set here. Until then ipx ran a BitTorrent session of its
//! own (librqbit), which replaced iPXDownloader.getTorrent and the vendored BitTorrent 4.2.1.
use anyhow::{Context, Result, bail};
use librqbit::{AddTorrent, AddTorrentOptions, AddTorrentResponse, Session, SessionOptions};
use std::net::SocketAddr;
use anyhow::{Context, Result, anyhow, bail};
use reqwest::header::{COOKIE, SET_COOKIE};
use reqwest::multipart::{Form, Part};
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::config::Config;
use librqbit::{ListenerOptions, ManagedTorrent};
pub struct Torrents {
session: Arc<Session>,
/// Not the guarded client feeds are fetched with: qBittorrent is on the LAN by design, at the
/// address the admin gave, which the guard would refuse (#320).
http: reqwest::Client,
/// The session cookie, `name=value`; qBittorrent 5 names it after its port.
cookie: tokio::sync::Mutex<Option<String>>,
}
/// What `torrents/info` says of one torrent, as much as ipx reads.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
struct Info {
hash: String,
state: String,
progress: f64,
total_size: i64,
completed: i64,
}
/// How often a running torrent is looked at.
const POLL: Duration = Duration::from_secs(2);
/// How long a torrent may make no progress before we give up on it. The original called
/// this torrentMaxBeatTime and counted display ticks; a wall clock is easier to reason about.
fn stall_limit(cfg: &Config) -> Duration {
@@ -22,133 +41,193 @@ fn stall_limit(cfg: &Config) -> Duration {
}
impl Torrents {
pub async fn new(cfg: &Config) -> Result<Self> {
let (lo, _hi) = cfg.torrent.ports();
let listen_addr: SocketAddr = format!("0.0.0.0:{lo}").parse()?;
let opts = SessionOptions {
listen: Some(ListenerOptions { listen_addr, ..Default::default() }),
client_name_and_version: Some(concat!("ipx ", env!("CARGO_PKG_VERSION")).into()),
// A test's swarm is two sessions and a tracker on 127.0.0.1, not the public DHT or the LAN.
dht: if cfg!(test) { None } else { Some(Default::default()) },
disable_local_service_discovery: cfg!(test),
..Default::default()
};
// The session root is only a fallback; every torrent names its own output folder.
let session = Session::new_with_opts(cfg.general.download_dir.clone(), opts)
.await
.context("starting the torrent session")?;
Ok(Self { session })
pub fn new() -> Result<Self> {
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build()?;
Ok(Self { http, cookie: Default::default() })
}
/// Downloads a torrent (a .torrent URL or a magnet link) straight into `dest_dir`,
/// seeds it up to the configured limit, then stops. `dest_dir` is the torrent's own
/// folder (`own_folder`), and it is the path returned: a file of several or one.
///
/// Downloading in place rather than into a staging dir is deliberate: seeding serves
/// the files it downloaded, so moving them first would break it.
/// Downloads a torrent (a .torrent URL or a magnet link) through qBittorrent into the
/// enclosure's own folder inside `feed_dir`, which is the path returned: a file of several or
/// one. Done once qBittorrent has all of it; the seeding is qBittorrent's.
pub async fn fetch(
&self,
cfg: &Config,
client: &reqwest::Client,
url: &str,
dest_dir: &Path,
feed_dir: &Path,
enclosure: i64,
mut on_progress: impl FnMut(u64, u64),
) -> Result<(PathBuf, u64)> {
tokio::fs::create_dir_all(dest_dir).await?;
let dir = own_folder(feed_dir, enclosure);
tokio::fs::create_dir_all(&dir).await?;
let limit = stall_limit(cfg);
let source = if url.starts_with("http://") || url.starts_with("https://") {
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
let file = tokio::time::timeout(limit, torrent_file(client, url))
.await
.map_err(|_| anyhow::anyhow!("no .torrent after {} minutes, gave up", limit.as_secs() / 60))??;
AddTorrent::from_bytes(file)
} else {
AddTorrent::from_url(url)
};
let tag = tag(enclosure);
// Resolving a magnet's metadata happens inside add_torrent, and against a dead
// swarm it never returns. The stall budget has to cover this phase too, or a
// torrent nobody is seeding wedges the scan forever.
let added = tokio::time::timeout(
limit,
self.session.add_torrent(
source,
Some(AddTorrentOptions {
output_folder: Some(dest_dir.to_string_lossy().into_owned()),
overwrite: true,
..Default::default()
}),
),
)
.await
.map_err(|_| anyhow::anyhow!("no metadata after {} minutes, gave up", limit.as_secs() / 60))?
.context("adding the torrent")?;
let (id, handle) = match added {
AddTorrentResponse::Added(id, h) | AddTorrentResponse::AlreadyManaged(id, h) => (id, h),
AddTorrentResponse::ListOnly(_) => bail!("torrent added in list-only mode"),
};
let mut last_progress = 0u64;
let mut last_move = Instant::now();
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
let stats = handle.stats();
if let Some(err) = &stats.error {
let _ = self.session.delete(id.into(), false).await;
bail!("torrent failed: {err}");
// There already when ipx stopped while it ran (#410): taken up where qBittorrent has it.
if self.info(cfg, &tag).await?.is_none() {
let file = if url.starts_with("http://") || url.starts_with("https://") {
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
let got = tokio::time::timeout(limit, torrent_file(client, url))
.await
.map_err(|_| anyhow!("no .torrent after {} minutes, gave up", limit.as_secs() / 60))??;
Some(got)
} else {
None
};
let t = &cfg.torrent;
let save = save_path(cfg, &dir);
let said = self
.api(cfg, "torrents/add", |req| {
let form = Form::new()
.text("savepath", save.clone())
.text("tags", tag.clone())
// The files straight into the folder, as the path recorded says (#318).
.text("contentLayout", "NoSubfolder")
.text("ratioLimit", t.seed_ratio.to_string())
.text("seedingTimeLimit", t.seed_time_mins.to_string());
req.multipart(match &file {
Some(b) => form.part("torrents", Part::bytes(b.clone()).file_name("episode.torrent")),
None => form.text("urls", url.to_owned()),
})
})
.await?;
if said.trim() == "Fails." {
bail!("qBittorrent would not take the torrent; it may have it already");
}
on_progress(stats.progress_bytes, stats.total_bytes);
}
if stats.finished {
break;
let mut last = (-1i64, Instant::now());
let done = loop {
tokio::time::sleep(POLL).await;
// A qBittorrent restarting is a pause, not a failure, until the stall limit says so.
let info = match self.info(cfg, &tag).await {
Ok(i) => i,
Err(e) if last.1.elapsed() < limit => {
tracing::debug!(error = %format!("{e:#}"), "qBittorrent did not answer");
continue;
}
Err(e) => return Err(e),
};
let Some(info) = info else { bail!("the torrent is no longer in qBittorrent") };
if matches!(info.state.as_str(), "error" | "missingFiles") {
self.delete(cfg, &info.hash).await;
bail!("qBittorrent says the torrent failed ({})", info.state);
}
if stats.progress_bytes > last_progress {
last_progress = stats.progress_bytes;
last_move = Instant::now();
} else if last_move.elapsed() > limit {
on_progress(info.completed.max(0) as u64, info.total_size.max(0) as u64);
if info.progress >= 1.0 && info.total_size > 0 {
break info;
}
if info.completed > last.0 {
last = (info.completed, Instant::now());
} else if last.1.elapsed() > limit {
// Leave the partial files behind; the row records the failure.
let _ = self.session.delete(id.into(), false).await;
self.delete(cfg, &info.hash).await;
bail!("no progress for {} minutes, gave up", limit.as_secs() / 60);
}
};
if cfg.torrent.seed_ratio <= 0.0 || cfg.torrent.seed_time_mins == 0 {
self.delete(cfg, &done.hash).await;
}
// The torrent's own name is the publisher's to choose, and librqbit checks it only when it
// picks the folder itself: joined on, "/config" or ".." pointed Delete, the reaper and
// /media at anything the daemon can reach (#318). The folder is ours, so it is the path.
let path = dest_dir.to_owned();
let size = handle.stats().total_bytes;
self.seed(cfg, &handle).await;
self.session.delete(id.into(), false).await.context("releasing the torrent")?;
Ok((path, size))
Ok((dir, done.total_size as u64))
}
/// Seeds until the ratio or the time limit is reached, whichever comes first.
async fn seed(&self, cfg: &Config, handle: &Arc<ManagedTorrent>) {
if cfg.torrent.seed_ratio <= 0.0 || cfg.torrent.seed_time_mins == 0 {
return;
/// Takes an episode's torrent out of qBittorrent once ipx has deleted its files, so it does not
/// stay there seeding nothing, as missing files (#495). Nothing when it is not there.
pub async fn forget(&self, cfg: &Config, enclosure: i64) {
match self.info(cfg, &tag(enclosure)).await {
Ok(Some(info)) => self.delete(cfg, &info.hash).await,
Ok(None) => {}
Err(e) => tracing::warn!(error = %format!("{e:#}"), enclosure, "could not ask qBittorrent for the torrent"),
}
let deadline = Instant::now() + Duration::from_secs(cfg.torrent.seed_time_mins * 60);
loop {
let stats = handle.stats();
if ratio(stats.uploaded_bytes, stats.total_bytes) >= cfg.torrent.seed_ratio {
tracing::info!(ratio = cfg.torrent.seed_ratio, "seed ratio reached");
return;
}
if Instant::now() >= deadline {
tracing::info!(mins = cfg.torrent.seed_time_mins, "seed time reached");
return;
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
async fn info(&self, cfg: &Config, tag: &str) -> Result<Option<Info>> {
let body = self.api(cfg, "torrents/info", |req| req.form(&[("tag", tag)])).await?;
let mut all: Vec<Info> = serde_json::from_str(&body).context("reading qBittorrent's torrent list")?;
Ok((!all.is_empty()).then(|| all.swap_remove(0)))
}
/// Takes the torrent out of qBittorrent, keeping its files. A failure is logged, not raised:
/// what called it is already giving up, or done.
async fn delete(&self, cfg: &Config, hash: &str) {
let form = [("hashes", hash), ("deleteFiles", "false")];
if let Err(e) = self.api(cfg, "torrents/delete", |req| req.form(&form)).await {
tracing::warn!(error = %format!("{e:#}"), "could not remove the torrent from qBittorrent");
}
}
/// One call to the Web API, signing in first when a user is set, and again once if the session
/// has expired (a 403). The answer's body.
async fn api(
&self,
cfg: &Config,
path: &str,
body: impl Fn(reqwest::RequestBuilder) -> reqwest::RequestBuilder,
) -> Result<String> {
let base = cfg.torrent.qbittorrent_url.trim_end_matches('/');
for retry in [false, true] {
let cookie = self.cookie(cfg, retry).await?;
let mut req = body(self.http.post(format!("{base}/api/v2/{path}")));
if let Some(c) = cookie {
req = req.header(COOKIE, c);
}
let resp = req.send().await.with_context(|| format!("asking qBittorrent ({path})"))?;
if resp.status() == reqwest::StatusCode::FORBIDDEN && !retry && !cfg.torrent.username.is_empty() {
continue;
}
let resp = resp.error_for_status().with_context(|| format!("qBittorrent refused {path}"))?;
return Ok(resp.text().await?);
}
unreachable!("the second try returns")
}
async fn cookie(&self, cfg: &Config, fresh: bool) -> Result<Option<String>> {
let t = &cfg.torrent;
if t.username.is_empty() {
return Ok(None);
}
let mut held = self.cookie.lock().await;
if fresh || held.is_none() {
let resp = self
.http
.post(format!("{}/api/v2/auth/login", t.qbittorrent_url.trim_end_matches('/')))
.form(&[("username", t.username.as_str()), ("password", t.password.as_str())])
.send()
.await
.context("signing in to qBittorrent")?;
let got = resp
.headers()
.get_all(SET_COOKIE)
.iter()
.filter_map(|v| v.to_str().ok()?.split(';').next())
.find(|c| c.split_once('=').is_some_and(|(name, _)| name.contains("SID")))
.map(str::to_owned);
*held = Some(got.ok_or_else(|| anyhow!("qBittorrent refused ipx's username and password"))?);
}
Ok(held.clone())
}
}
/// How ipx finds an enclosure's torrent in qBittorrent: by hash it cannot, since a magnet has none
/// until its metadata has come.
fn tag(enclosure: i64) -> String {
format!("ipx-{enclosure}")
}
/// Whether `path` is the folder `fetch` gave `enclosure`: a torrent of ours, then.
pub fn is_own_folder(path: &Path, enclosure: i64) -> bool {
path.file_name() == own_folder(Path::new(""), enclosure).file_name()
}
/// Where qBittorrent is to write `dir`: the same path, or `save_path` in place of `download_dir`
/// when qBittorrent's mount of it is somewhere else.
fn save_path(cfg: &Config, dir: &Path) -> String {
let theirs = cfg.torrent.save_path.trim();
match dir.strip_prefix(&cfg.general.download_dir) {
Ok(rest) if !theirs.is_empty() => Path::new(theirs).join(rest).display().to_string(),
_ => dir.display().to_string(),
}
}
/// A .torrent file is metadata: a few hundred KB even for a large torrent.
@@ -175,93 +254,95 @@ pub fn own_folder(feed_dir: &Path, enclosure: i64) -> PathBuf {
feed_dir.join(format!("torrent-{enclosure}"))
}
/// Uploaded over total. A zero-byte torrent counts as fully seeded rather than dividing by zero.
pub fn ratio(uploaded: u64, total: u64) -> f64 {
if total == 0 {
return f64::INFINITY;
}
uploaded as f64 / total as f64
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
/// A swarm on 127.0.0.1: a seeding session holding `file`, and a web server answering for the
/// .torrent (`/ep.torrent`) and as its tracker, naming the seed as the one peer. The server's
/// address, and the seeding session, which stops seeding when dropped.
async fn swarm(file: &Path) -> (SocketAddr, Arc<Session>) {
/// A qBittorrent that wants a sign-in, and as the feed's server serves the .torrent too. A
/// torrent added is finished at once: the file is written into its save path, as qBittorrent
/// would. Its address, and the hashes deleted.
async fn qbittorrent(episode: Vec<u8>) -> (std::net::SocketAddr, Arc<std::sync::Mutex<Vec<String>>>) {
use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{get, post};
type Held = Arc<std::sync::Mutex<Vec<serde_json::Value>>>;
let held: Held = Default::default();
let deleted: Arc<std::sync::Mutex<Vec<String>>> = Default::default();
let signed_in = |h: &HeaderMap| h.get("cookie").is_some_and(|c| c == "QBT_SID_8080=abc");
// The multipart body read as text: enough to find a field's value in a test.
let field = |body: &str, name: &str| {
let at = body.find(&format!("name=\"{name}\"\r\n\r\n")).unwrap() + name.len() + 11;
body[at..].split("\r\n").next().unwrap().to_owned()
};
let (h1, h2, d) = (held.clone(), held.clone(), deleted.clone());
let app = axum::Router::new()
.route("/ep.torrent", get(|| async { "d4:infode" }))
.route(
"/api/v2/auth/login",
post(|body: String| async move {
if body == "username=ipx&password=pw" {
([("set-cookie", "QBT_SID_8080=abc; HttpOnly; path=/")], "Ok.").into_response()
} else {
"Fails.".into_response()
}
}),
)
.route(
"/api/v2/torrents/add",
post(move |h: HeaderMap, body: axum::body::Bytes| async move {
if !signed_in(&h) {
return (StatusCode::FORBIDDEN, "Forbidden").into_response();
}
let body = String::from_utf8_lossy(&body);
assert!(body.contains("d4:infode"), "the .torrent ipx fetched");
assert_eq!(field(&body, "contentLayout"), "NoSubfolder");
let save = field(&body, "savepath");
std::fs::write(Path::new(&save).join("episode.mp3"), &episode).unwrap();
let n = episode.len();
h1.lock().unwrap().push(serde_json::json!({"hash": "h1", "tags": field(&body, "tags"),
"state": "uploading", "progress": 1.0, "total_size": n, "completed": n}));
"Ok.".into_response()
}),
)
.route(
"/api/v2/torrents/info",
post(move |h: HeaderMap, body: String| async move {
if !signed_in(&h) {
return (StatusCode::FORBIDDEN, "Forbidden").into_response();
}
let tag = body.strip_prefix("tag=").unwrap().to_owned();
let all = h2.lock().unwrap().iter().filter(|t| t["tags"] == tag).cloned().collect::<Vec<_>>();
axum::Json(all).into_response()
}),
)
.route(
"/api/v2/torrents/delete",
post(move |body: String| async move {
d.lock().unwrap().push(body);
"Ok."
}),
);
let web = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let at = web.local_addr().unwrap();
let seed_port = free_port();
let made = librqbit::create_torrent(
file,
librqbit::CreateTorrentOptions {
name: None,
trackers: vec![format!("http://{at}/announce")],
piece_length: Some(16 * 1024),
},
&librqbit::spawn_utils::BlockingSpawner::new(2),
)
.await
.unwrap();
let torrent = made.as_bytes().unwrap();
// Compact peers: the address's four bytes, then the port's two.
let mut peers = b"d8:intervali60e5:peers6:".to_vec();
peers.extend_from_slice(&[127, 0, 0, 1]);
peers.extend_from_slice(&seed_port.to_be_bytes());
peers.push(b'e');
let app = axum::Router::new()
.route("/ep.torrent", axum::routing::get(move || std::future::ready(torrent.clone())))
.route("/announce", axum::routing::get(move || std::future::ready(peers.clone())));
tokio::spawn(async move { axum::serve(web, app).await });
let seed = Session::new_with_opts(
file.parent().unwrap().to_owned(),
SessionOptions {
dht: None,
disable_local_service_discovery: true,
listen: Some(ListenerOptions {
listen_addr: format!("127.0.0.1:{seed_port}").parse().unwrap(),
..Default::default()
}),
..Default::default()
},
)
.await
.unwrap();
seed.add_torrent(
AddTorrent::from_bytes(made.as_bytes().unwrap()),
Some(AddTorrentOptions {
output_folder: Some(file.parent().unwrap().display().to_string()),
overwrite: true,
..Default::default()
}),
)
.await
.unwrap();
(at, seed)
(at, deleted)
}
#[tokio::test(flavor = "multi_thread")]
async fn a_detached_torrent_lands_in_its_own_folder_is_recorded_and_frees_its_slot() {
let root = std::env::temp_dir().join(format!("ipx-torrent-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (seeded, downloads) = (root.join("seed"), root.join("downloads"));
std::fs::create_dir_all(&seeded).unwrap();
let downloads = root.join("downloads");
let episode: Vec<u8> = (0..200_000u32).map(|i| (i * 7 % 251) as u8).collect();
std::fs::write(seeded.join("episode.mp3"), &episode).unwrap();
let (at, _seed) = swarm(&seeded.join("episode.mp3")).await;
let (at, deleted) = qbittorrent(episode.clone()).await;
let mut cfg = Config::default();
cfg.general.download_dir = downloads.clone();
cfg.torrent.enabled = true;
let port = free_port();
cfg.torrent.port_range = format!("{port}-{port}");
cfg.general.fetch_internal = vec!["127.0.0.1".into()];
cfg.torrent.qbittorrent_url = format!("http://{at}/");
cfg.torrent.username = "ipx".into();
cfg.torrent.password = "pw".into();
cfg.torrent.seed_ratio = 0.0;
let mut ctx = crate::test_util::test_ctx(cfg.clone()).await;
ctx.detach_torrents = true;
@@ -274,8 +355,15 @@ mod tests {
.await
.unwrap();
crate::scan::spawn_torrent(&ctx, "f".into(), 9, url.clone(), downloads.join("Show"));
let row = tokio::time::timeout(Duration::from_secs(90), async {
crate::scan::spawn_torrent(
&ctx,
crate::download::Via::Torrent,
"f".into(),
9,
url.clone(),
downloads.join("Show"),
);
let row = tokio::time::timeout(Duration::from_secs(30), async {
loop {
let row = ctx.db.enclosure(9).await.unwrap().unwrap();
if row.state != "downloading" {
@@ -285,17 +373,45 @@ mod tests {
}
})
.await
.expect("the torrent finished within 90 s");
.expect("the torrent finished within 30 s");
let folder = own_folder(&downloads.join("Show"), 9);
assert_eq!((row.state.as_str(), row.last_error.as_deref()), ("done", None));
assert_eq!(row.path.as_deref(), Some(folder.display().to_string().as_str()), "the folder is ours (#318)");
assert_eq!(std::fs::read(folder.join("episode.mp3")).unwrap(), episode);
assert_eq!(
*deleted.lock().unwrap(),
["hashes=h1&deleteFiles=false"],
"no seeding asked for: let go, files kept"
);
// Its files deleted, by the reaper or Delete: out of qBittorrent too, and only a torrent (#495).
deleted.lock().unwrap().clear();
ctx.forget_torrent(9, &downloads.join("Show/episode.mp3").display().to_string()).await;
assert!(deleted.lock().unwrap().is_empty(), "a file that is not a torrent's folder");
ctx.forget_torrent(9, &folder.display().to_string()).await;
assert_eq!(*deleted.lock().unwrap(), ["hashes=h1&deleteFiles=false"]);
// The slot is let go once the row is written; give the task its moment.
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(ctx.torrent_slots.available_permits(), 2, "the slot is free again");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn only_an_enclosures_own_folder_is_its_torrent() {
assert!(is_own_folder(&own_folder(Path::new("/downloads/Show"), 9), 9));
assert!(!is_own_folder(&own_folder(Path::new("/downloads/Show"), 9), 19));
assert!(!is_own_folder(Path::new("/downloads/Show/episode.mp3"), 9));
}
#[test]
fn the_save_path_is_where_qbittorrent_sees_the_folder() {
let mut cfg = Config::default();
cfg.general.download_dir = "/downloads".into();
let dir = Path::new("/downloads/Show/torrent-9");
assert_eq!(save_path(&cfg, dir), "/downloads/Show/torrent-9", "the same mount");
cfg.torrent.save_path = "/data/ipx".into();
assert_eq!(save_path(&cfg, dir), "/data/ipx/Show/torrent-9");
}
#[tokio::test]
async fn a_torrent_file_from_an_internal_address_is_refused_unless_allowed() {
let app = axum::Router::new().route("/ep.torrent", axum::routing::get(|| async { "d4:infode" }));
@@ -317,14 +433,6 @@ mod tests {
);
}
#[test]
fn ratio_handles_the_empty_torrent() {
assert_eq!(ratio(0, 100), 0.0);
assert_eq!(ratio(50, 100), 0.5);
assert_eq!(ratio(200, 100), 2.0);
assert!(ratio(0, 0).is_infinite(), "must not divide by zero or seed forever");
}
#[tokio::test]
async fn an_endless_torrent_file_stops_at_the_cap() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};

View File

@@ -77,6 +77,7 @@ const WIRE: ipx_wire::Routes = &[
("POST", "/api/entries/{feed_id}/{guid}/flags", "ipx.Flags", "ipx.FeedRow"),
("POST", "/api/entries/{feed_id}/{guid}/position", "ipx.Position", ""),
("POST", "/api/entries/{feed_id}/{guid}/share", "ipx.ShareBody", "ipx.ShareLink"),
("GET", "/api/enclosures/{id}/chapters", "", "ipx.Chapters"),
("POST", "/api/feeds/{id}/read-all", "", "ipx.Marked"),
("POST", "/api/read-all", "", "ipx.Marked"),
("POST", "/api/feeds/{id}/download-latest", "ipx.HowMany", "ipx.Queued"),
@@ -128,6 +129,7 @@ pub fn router(state: WebState) -> Router {
.route("/api/feeds/{id}/download-latest", post(download_latest))
.route("/api/enclosures/{id}/download", post(download_now))
.route("/api/enclosures/{id}", delete(delete_file))
.route("/api/enclosures/{id}/chapters", get(chapters))
.route("/api/fetch", post(fetch_now))
.route("/api/opml", get(export_opml).post(import_opml))
.route("/api/settings", get(get_settings).patch(patch_settings))
@@ -2724,6 +2726,53 @@ struct Force {
force: bool,
}
#[derive(Deserialize)]
struct ChaptersAsked {
/// Played from DeadAir's shortened copy, whose clock the starts are then given in.
#[serde(default)]
deadair: bool,
}
/// A file's chapters, for Now Playing (#477): from the file its item names, else from the file
/// itself once downloaded. None is an empty list, as is one that could not be read: the player
/// plays on without them, and the trace has why.
async fn chapters(
State(state): State<WebState>,
Path(id): Path<i64>,
user: crate::db::User,
Query(q): Query<ChaptersAsked>,
) -> Result<Json<Vec<crate::chapters::Chapter>>, ApiError> {
let enc = state.ctx.db.enclosure(id).await?.ok_or_else(|| ApiError::not_found(format!("no file {id}")))?;
subscribed(&state, &user, &enc.feed_id).await?;
let mut list = Vec::new();
if let Some(url) = state.ctx.db.chapters_url(&enc.feed_id, &enc.guid).await? {
match crate::chapters::fetch(&state.ctx.client, &url).instrument(db::step("chapters_fetch")).await {
Ok(l) => list = l,
Err(e) => {
tracing::debug!(url = %crate::feed::redact(&url), error = %format!("{e:#}"), "could not read the chapters")
}
}
}
if list.is_empty()
&& let Some(path) = &enc.path
{
let file = crate::download::playable(std::path::Path::new(path));
match crate::chapters::in_file(&file).instrument(db::step("chapters_file")).await {
Ok(l) => list = l,
Err(e) => tracing::debug!(error = %format!("{e:#}"), "could not read the file's chapters"),
}
}
if q.deadair
&& !list.is_empty()
&& let Some(plan) = crate::deadair::plan_for(&state.ctx, user.id, &enc.feed_id, id).await?
{
for c in &mut list {
c.start = crate::deadair::to_copy(&plan.cuts, (c.start * 1000.0) as i64) as f64 / 1000.0;
}
}
Ok(Json(list))
}
async fn delete_file(
State(state): State<WebState>,
Path(id): Path<i64>,
@@ -2765,6 +2814,9 @@ async fn delete_file(
{
return Err(e.into());
}
if let Some(path) = &enc.path {
state.ctx.forget_torrent(id, path).await;
}
// The row survives as 'reaped', which is what stops the next scan re-downloading it.
state.ctx.db.mark_reaped(id).await?;
state

View File

@@ -21,5 +21,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
- Built with SQLite 3.54 (libsqlite3-sys 0.40, through sqlx 0.9.1), past an advisory on opening a crafted database (RUSTSEC-2026-0459, #467), and url 2.5.9, which a web address nested thousands of times in `blob:` can no longer crash (RUSTSEC-2026-0592, #492).
- 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

@@ -289,6 +289,17 @@ message SeasonRows {
repeated SeasonRow items = 1;
}
// One chapter of a file in GET /api/enclosures/{id}/chapters (#477): its start in seconds, in
// the clock of what plays, and its title, which may be empty.
message Chapter {
double start = 1;
string title = 2;
}
message Chapters {
repeated Chapter items = 1;
}
// POST /api/playlists, the answer.
message PlaylistId {
int64 id = 1;

View File

@@ -7,14 +7,9 @@ targets = ["x86_64-unknown-linux-gnu"]
[advisories]
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)" },
# chrono is unmaintained, every version, and no vulnerability is known. rss and atom_syndication
# depend on it, so ipx's own code moving off it would not take it out (#493).
{ id = "RUSTSEC-2026-0543", reason = "unmaintained, not vulnerable; the feed parsers depend on it (#493)" },
]
[licenses]

View File

@@ -16,9 +16,6 @@ services:
# For Postgres instead of SQLite:
# IPX_DATABASE_URL: "postgres://ipx:password@db-host:5432/ipx"
# No web port of its own: ipx-web is the way in, and passes the API on to it.
ports:
- "6881:6881/tcp" # BitTorrent peers
- "6881:6881/udp" # DHT
volumes:
- ./config:/config # config.toml, written on first start
- ./data:/data # state.db

369
docs/STYLE-GUIDE.md Normal file
View File

@@ -0,0 +1,369 @@
# The iPX style guide
How iPX looks, behaves and reads: the page (`web/`), the admin page, sign-in, the iOS app's own
alerts (`ios/`) and the directory's and ipx-play's pages. The first half is design: principles,
layout, controls, dialogs, keyboard, feedback, safety and accessibility. The second half is
writing: every string a person sees.
iPX is a web page in English, used with a mouse and keyboard in a desktop browser, by touch on a
phone's home screen, and inside the iOS app, by people who run their own server or were given an
account on one. They know what a podcast and a feed are; they do not know what a guid, a scan job
or a 304 is. Where a browser or iOS has a convention of its own, it wins over this guide.
The rules were chosen against forty years of interface guides (Apple 1987-2014, Windows 1995 and
2010, NeXTSTEP, GNOME, KDE, Android and others); the reasons for the disputed ones are in the two
decision logs.
# Design
## Principles
| Principle | For iPX | ✅ | ❌ |
|---|---|---|---|
| The person is in control | iPX acts on its own only where it was asked to (downloads by a feed's settings, checks on the schedule), and each can be turned off | A feed downloads its newest five because its settings say so | Marking an item read because it scrolled past |
| See and point | Every action is on screen somewhere; a key or a swipe is a quicker way to it, never the only one | On a phone a swipe goes to the next item; so do the reader's arrow and `j` | An action only on a long-press |
| Consistency | The same thing looks and works the same on every screen, on a phone and a desktop, as it did in the last release | Every dialog has Cancel on the left and its action on the right | A Save at the top of one dialog and the bottom of the next |
| Stability | Things stay where they were: the list keeps its place, a dialog closes back to the control that opened it, a reader keeps its scroll when it redraws | A button that cannot act now is dimmed in place | A toolbar whose buttons come and go with the selection |
| Feedback | Every action shows a result where it happened, within a tenth of a second | The row's dot empties as it is marked read | A spinner in the corner for a change to one row |
| Forgiveness | What can be taken back is taken back easily; what cannot is asked about first | Unsubscribe asks, and says what goes | Delete a file at one tap |
| Accessible from the start | A screen reader, a keyboard alone, zoom, reduced motion and high contrast all work, in every theme | An icon button with a tooltip and a matching `aria-label` | An icon button with only its icon |
## Layout and visual system
**Two layouts, one breakpoint.** Wider than 820 px: the feed list, the item list and the reader
side by side. 820 px or narrower: one column, the feed list as a drawer, the reader as a sheet. No
third layout for a tablet; a breakpoint is added only with a test that fails without it. (The
admin page wraps its tabs at 600 px, its one exception.)
**Spacing** comes from one scale: 2, 4, 6, 8, 10, 12, 14 px, the gaps the stylesheet already uses.
✅ `gap:8px` · ❌ `gap:9px`. Within a group the smaller steps, between groups the larger.
**Corners**: 6-10 px on controls and rows, 14 px on cards and sheets, round (`999px`) on pills and
chips, `50%` on round buttons and art. Not a new radius for one component.
**Type**: 13 px is the body of the interface; 11-12.5 px for secondary lines (dates, counts), 14-17
px for headings and the reader's text, 26 px only for a sheet's title. The fonts are the person's
choice in Settings (interface and reading separately), so a component never names a font: it uses
`--f-*` through the theme. Numbers that are compared (times, counts, sizes) use tabular figures and
line up on the right.
**Colour** is by role, never by value: `--bg`, `--panel`, `--panel2`, `--raise` for surfaces;
`--fg`, `--dim`, `--faint` for text by importance; `--accent`, `--accent2` for the selection and
the primary action; `--good`, `--warn`, `--bad` for state; `--line` for rules. ✅
`color:var(--bad)` · ❌ `color:#d33`. Every palette defines every role, and
`node tests/contrast.ts` checks each against WCAG AA; a new role needs a value in every palette and a
contrast check. Working on a component never changes a theme's colours.
**Colour is never the only signal.** An unread item has its dot and its weight; a failing feed has
its icon and its label; a pressed toggle has its shape and `aria-pressed`. ✅ the pin's outline
fills in · ❌ the pin turns green.
**Icons** are Font Awesome Free, embedded as SVG through `ICON`, only those used; nothing is
fetched from another site. One icon means one thing everywhere: the plus adds, the check saves,
the cross cancels or closes. An icon that toggles changes shape (pin, pin-on), not colour.
**Touch targets** are at least 44 by 44 px on a phone, 40 px where a row is dense, as the player's
and toolbar's buttons are. Hover effects sit inside `@media (hover:hover)`, so a phone never keeps
one stuck after a tap.
**The phone's edges**: the page is `viewport-fit=cover` and pads itself by the safe-area insets
(`--safe-*`), on the home screen and in the app alike.
## Controls
| Control | Use for | Not for |
|---|---|---|
| Button | An action now | A setting that stays: that is a toggle or a select |
| Icon button | A frequent action whose icon is unambiguous: play, close, add, delete | Anything needing a word to tell it apart; give it a label |
| Toggle button (`aria-pressed`) | A state of the thing in view: pinned, DeadAir on, read | A choice among three or more |
| Checkbox | An on-or-off setting in a form | An action |
| Select | One of four or more fixed choices | Two choices (a toggle), or a list to search (a filter box) |
| Tabs (Unread, All, In progress) | Views of the same list | Steps of a task |
| Chips | Words someone types: keywords, hidden words | A fixed set of choices |
| Search box | A list longer than a screen; it gets a clear button once something is typed | A list of five |
Every control has hover (only where there is hover), focus, pressed and disabled states, drawn
from the theme's roles. Focus is always visible: ✅ the theme's focus ring · ❌ `outline:none`
with nothing in its place.
A control that cannot act now is **dimmed in place**, with a tooltip saying why, not removed:
✅ Play, dimmed, "Nothing to play in this item" · ❌ Play missing from items without a file. Remove
it only where it can never apply, as the file buttons on an item with no file.
## Dialogs and sheets
* **Modal only when iPX needs an answer first**: adding a feed, a feed's settings, a confirmation.
Everything else is in place: the reader, the player, Now Playing.
* **One purpose, short.** A dialog that scrolls on a desktop is two dialogs, or a page.
* **Buttons** go at the bottom right: Cancel on the left, the action on the right, as `cardacts`
draws them. ✅ *Cancel* *Unsubscribe* · ❌ *Unsubscribe* *Cancel*. Two buttons is the norm; three
at most.
* **The action is named**, not OK: ✅ *Add feed*, *Download*, *Make playlist*. An icon button
names it in its tooltip and `aria-label`.
* **A destructive action is red** (`danger`) and is never the default: Enter in a box does not
unsubscribe.
* **Escape, a tap outside, and Cancel all close** without changing anything. Focus goes back to
the control that opened the dialog.
* **A confirmation is the page's own dialog**: `ask()`, or a dialog of its own when it has more
than a sentence to say, as Unsubscribe does. Never `confirm()`, which the iOS app answered
Cancel without showing (#453).
* **When changes apply**: how iPX looks (theme, fonts, light or dark) applies as it is chosen; what
changes what the server does (a feed's settings, a signal, a playlist) applies on Save, since
it costs a check or a download.
* **On a phone** a dialog is a sheet from the bottom edge, its buttons within reach of a thumb.
## Commands and menus
* **No menu bar.** Commands are in the toolbar of what they act on: the feed's header for the
feed, the reader's bar for the item, the player for what plays. A row's less frequent commands
are in its More menu.
* **Every command has one visible home**; a key, a swipe or a context menu is a quicker way to it.
* **Toggles change their name**: ✅ Pin, Unpin · ❌ two buttons, one always dimmed.
* **Frequent first**: within a menu, the commands used most at the top, the destructive ones last,
after a separator.
## Keyboard
The page uses single keys, like Feedly's, and `?` lists them all. The list in `keysModal()` is
the table; a new key goes there in the same change.
| Rule | ✅ | ❌ |
|---|---|---|
| Never take a key the browser or the system has: anything with Ctrl, Cmd or Alt | `r` reloads the lists | Ctrl+R reloads the lists |
| A key does nothing while typing in a box, except Escape | `j` in the search box types a j | `j` in the search box moves the selection |
| Escape always closes the top thing: a confirmation, then a dialog, then the drawer, then Now Playing | | |
| One key, one meaning, in every view | `s` pins the selected item | `s` saving settings in one view |
| Pairs go by `g` + a letter, within a second and a half | `g u` Up Next | |
| Every key's action has a button too | | A key with no button |
**Focus order** follows reading order: the toolbar, the feed list, the item list, the reader, the
player. A row in a list is reached with Tab and opened with Enter or Space. Opening a dialog puts
focus in it; closing it puts focus back.
## Feedback and timing
| Wait | What shows |
|---|---|
| Under 0.1 s | The result, in place: the row changes, the button presses |
| 0.1-1 s | Nothing extra; the result arrives |
| Over 1 s | A spinner where the result will appear, not over the whole page |
| Over 5 s, or a download | Progress with an amount: "Downloading *file*: 52%", a bar on the row |
| Over 10 s | Progress and a way to stop it |
* **Motion** is short: 120-250 ms for a press, a fade or a sheet, never over 450 ms, starting at
once. With reduced motion asked for, nothing moves; spinners pulse instead of turning, sheets
and toasts fade instead of sliding.
* **Toasts** confirm what just happened, at the bottom, for 3.2 s. An error toast stays until it is
dismissed, and a run of them does not stack up the screen.
* **Sound and haptics** are never the only feedback; on the phone an error toast also gives a
warning tap.
## Errors, undo and safety
* **Prevent before reporting**: Save is dimmed until the form can be saved; a number box has its
limits (`min`, `max`); an address is checked when it is added, not on every key.
* **Validate on Save**, not on each keystroke and not on leaving a field.
* **Ask only before what cannot be taken back**: unsubscribing, marking a whole list read,
deleting a playlist or a signal, removing an account. Not before marking one item read, pinning
or queueing, which a second tap undoes.
* **Offline is not an error**: what was kept still opens, and reads, pins and places are sent when
the connection is back.
* **A failure keeps what the person typed**: a dialog whose Save fails stays open with the message
in it.
## Accessibility checklist
* Every icon-only control has a tooltip and an `aria-label` saying the same thing.
* Every toggle has `aria-pressed`; every dialog `aria-labelledby` its title; a dialog makes the
page behind it `inert`.
* Every pointer action has a keyboard path, and every swipe a button.
* Contrast passes WCAG AA in every palette (`node tests/contrast.ts`), for text and for icons.
* Nothing relies on colour alone, on hover alone, or on sound alone.
* Reduced motion, reduced transparency and more contrast are honoured
(`prefers-reduced-motion`, `prefers-reduced-transparency`, `prefers-contrast`).
* Text zooms to 200% without a horizontal scroll at 320 px wide.
* Touch targets are at least 44 px, 40 in a dense row.
* The page's language is set (`lang="en"`).
## Design decision log
| Decision | Choice | Why |
|---|---|---|
| Dialog button order | Cancel left, action right, bottom right | What every iPX dialog already does, and Apple's order since 1987, which the iOS app's users see in every other app; Windows 2010 has the reverse. One order, never mixed |
| Default button | None for a destructive action; otherwise the action, never Cancel | Mac 1992, Windows 1995 and 2010 agree a dangerous action is never the default |
| Menus | No menu bar; toolbars on what they act on, a More menu per row | A web page in a browser and an app on a phone have no menu bar of their own; Windows 2010 drops one with three categories or fewer |
| Modal or in place | In place by default; modal only for an answer iPX needs first | Mac 1992 and Windows 1995: modal only when the program cannot go on without it |
| Dim or hide | Dim in place, with the reason as a tooltip; hide only what can never apply | Apple 1987-2009 and Windows 1995: dimming keeps the screen stable |
| When a change applies | Appearance at once; what the server does on Save | Windows 2010's live preview for what is cheap to try; Save for what costs a check or a download |
| Shortcuts | Single keys and `g` pairs, as Feedly's, never a modifier | A reader's keys are used a hundred times a session; Apple 2009 and Windows 1995 say not to take the system's keys, which any modifier risks in a browser |
| Confirm or undo | Ask before what cannot be taken back; what a second tap undoes is not asked | Apple 1987: alerts should be rare. iPX has no undo, so what cannot be reversed is asked about instead |
| Breakpoints | One, at 820 px | Two layouts are tested; a third doubles the testing for a tablet that does well with either |
# Writing
## Voice and tone
| Be | This | Not that |
|---|---|---|
| Plain | Nothing in progress. Episodes you start and do not finish show up here. | No in-progress entries found. |
| Direct, to "you" | Choose at least one podcast. | The user must select one or more podcasts. |
| Calm | Unable to reach iPX. Check your connection and try again. | Error! Network request failed! |
| Brief | Link copied | The link has been successfully copied to your clipboard. |
| Honest about what happens next | Saved. It applies from the next check. | Saved. |
Signals and DeadAir have their own voice, radio's signal against noise; see
[signals.md](signals.md). Everything else is the plain voice above.
## Capitalization
Sentence case everywhere: capitalize the first word and proper nouns, nothing else.
| Element | ✅ | ❌ |
|---|---|---|
| Heading, dialog title | Add a feed | Add a Feed |
| Button | Copy link | Copy Link |
| Menu item, tab | Show notes | Show Notes |
| Label, checkbox | Media types to download | Media Types To Download |
| Tooltip | Check every feed for new items | Check Every Feed For New Items |
| Placeholder | Filter feeds… | FILTER FEEDS… |
Names of iPX's own features are proper nouns and keep their capitals: **iPX, Up Next, Now Playing,
Currently Listening, All Subscriptions, Signals, DeadAir, Admin, Directory**. The filters Unread, All and In progress
are tab labels, so only their first word is capitalized. Write other products as they write
themselves: TypeSafe, Patreon, OPML, CarPlay.
## Punctuation
* **Ellipsis**: the one character `…` (U+2026), never three periods, which screen readers read
out. Use it on a command that needs more from the person before it runs (✅ Import…), on a
placeholder that invites typing (✅ Filter…), and on work in progress (✅ Loading…). Not on a
command that only opens something: ✅ Settings, ❌ Settings….
* **Periods**: a complete sentence ends with one; a fragment does not. ✅ Link copied ·
✅ There is nothing to play in this item. ❌ Link copied. Two sentences both end with periods.
* **No exclamation marks**, anywhere.
* **Colons** after a label only when what follows completes it in the same line:
✅ Downloading: *episode title*. Not after a form label.
* **Quotation marks**: curly double quotes around what the person typed: ✅ No podcast is
called “f1”.
* **No symbols for words**: ✅ light or dark, ❌ light/dark · ✅ and, ❌ & · ✅ number of
episodes, ❌ # of episodes.
* **No dashes to join clauses**; two sentences instead. ❌ Could not copy automatically — select
the URL… ✅ Unable to copy the link. Select it and copy it yourself.
## Elements
**Buttons** start with a verb and are four words at most, with no closing punctuation:
✅ Use the new address · ✅ Share link · ❌ New address · ❌ Initials. An icon-only button has a
tooltip and an `aria-label` that say the same thing. A link or button inside a sentence takes the sentence's case: ✅ Get one at typesafe.ai,
then add it in Settings. A button that toggles changes its verb:
✅ Pin / Unpin · ❌ Pin: on.
**Paired commands** match: Subscribe / Unsubscribe, Keep / Remove (an episode on this device),
Mark read / Mark unread, Show / Hide.
**Tooltips** say what the control does, in more words than its label, and name its key when it has
one: ✅ Back 15 seconds (←) · ✅ Play the next in Up Next. No closing period. Not a repeat of the
label: ❌ title="Clear" on a button reading Clear.
**Labels** are nouns or short questions: ✅ Feed address · ✅ How many of the newest
undownloaded items? Not instructions.
**Placeholders** show the form of an answer or invite a search, never replace the label:
✅ https://example.com/rss · ✅ Morning commute · ❌ Enter the feed URL here. A field that holds a
secret says whether one is set: ✅ Set. Paste a new one to replace it.
**Hints** under a control say what the person would not otherwise know: its effect, not how to use
it. ✅ Only items matching a keyword are downloaded. ❌ Type keywords into the box above. If a
control needs a paragraph, change the control.
**Empty lists** say what is missing and how it fills: ✅ No podcasts yet. Add a feed with episodes
in it, and it shows here. ❌ No results.
**Toasts** confirm something that just happened, or say why it did not. One line; the subject is
what changed, not iPX: ✅ Removed from Up Next · ❌ iPX has removed the episode from Up Next.
## Errors, warnings and confirmations
An error says **what did not happen, and what to do now**, with the why between them when it
helps. The form is `Unable to <what>. <What to do>.`
| ✅ | ❌ |
|---|---|
| Unable to play this file. Try again, or download it again. | Playback error. |
| Unable to reach iPX just now. Try again in a minute. | Request failed (502). |
| Unable to keep it on this device. Try again. | Error: QuotaExceededError |
* Never "error", "failed" or "invalid" as the message, and nothing that blames the person.
* No codes, status numbers, exception names or paths in the message. They go to the log, which
the admin page shows.
* Before writing an error, ask whether it can be prevented: a Save button stays disabled until the
form is complete, rather than "Name is required" after the click.
* When iPX can fix the problem, the message offers the fix as a button: ✅ Add it in Settings.
* One message per problem; never one alert after another.
A **confirmation** asks only before something that cannot be undone. Its title is a question; its
buttons name the action, the destructive one not the default.
| ✅ | ❌ |
|---|---|
| Unsubscribe? · *Cancel* · *Unsubscribe* | Are you sure? · *OK* · *Cancel* |
Cancel means nothing happened. If the action cannot be taken back halfway, the button is Stop.
The page's `confirm()` (and the iOS app's answer to it) can only offer Cancel and OK, so its
question names the action in full: ✅ Delete this file from the server?
**please** only when the person has to wait or do something because of iPX: ✅ Please wait while
iPX imports 214 feeds. **sorry** only when something is lost or cannot go on. Neither as filler.
## Vocabulary
One word for each thing, everywhere.
| Use | Not | Meaning |
|---|---|---|
| podcast | show, talk show, channel | a feed with audio or video in it |
| episode | track, file (as the thing played) | an item of a podcast |
| item | entry, post, article | anything a feed publishes; an episode is an item |
| feed | RSS, source, channel | what someone subscribes to |
| address | URL, link (for a feed) | where a feed or server is; "link" is what is shared |
| subscribe, unsubscribe | follow, add/remove (for feeds) | |
| download | fetch, grab | the server saving an episode's file |
| keep on this device | download, save offline, cache | the phone or browser holding a copy |
| check | scan, poll, refresh | the server reading a feed for new items |
| read, unread | seen, new, viewed | |
| pin | star, favorite, protect | an item kept from being deleted |
| sign in, sign out | log in, log out, login | |
| server | backend, instance, daemon | the iPX someone signs in to |
| token | API key, secret | what a script or another server signs in with |
| Up Next | queue, playlist | the episodes lined up to play |
| playlist | smart list, collection | a list made from chosen podcasts |
Never in the interface: guid, enclosure, entry, scan job, worker, cache, 304, ETag, OPML child,
widget, payload, and the names of the people who use iPX (no character speaks, waiting is a
spinner). OPML stays: people exporting a list meet the word in other apps.
## Localization
iPX ships in English only, and its strings live in the code, not in a resource file. Write as if
that will change: no sentence built from fragments joined in code (✅ `Kept on this device, to
play offline: ${title}` keeps the variable at the end), plurals handled as a whole sentence, not
with "(s)", dates and numbers through `toLocaleString` and the page's date helpers, and room for
half again as much text in every label.
## Writing decision log
| Decision | Choice | Why |
|---|---|---|
| Title or sentence case for buttons and menus | Sentence case for everything | The web has no platform rule; Windows 2010 moved everything but titles to sentence case, and iPX's strings already are. One rule, no list of words to keep lowercase |
| Case for labels, checkboxes, tooltips | Sentence case | Follows from the above; Windows 1995, Apple 2009, GNOME and KDE agree |
| Lowercase words in title case | None needed | Nothing is in title case |
| Contractions | Never: do not, cannot, it is | iPX's house style already spells them out, and KDE 2021 and GEM agree. Android and Windows 2010 use them for friendliness; iPX finds it in plain words instead |
| Failure wording | "Unable to …" | Most of the page's errors already say it; one form, not "Could not", "Cannot" and "Unable to" side by side |
| Ellipsis character | `…` | Apple 2009 and KDE: three periods break screen readers |
| Ellipsis on Settings | No | Windows' test: an ellipsis means more input is needed, not that something opens; GNOME agrees, Apple 2009 differs |
| Room for translation | Half again | KDE's 50% over GNOME's 30%; short labels grow most |
| Exclamation marks | Never | House style; KDE and GEM keep them out of errors |
| OK and Cancel | Specific verbs; OK only to acknowledge or where `confirm()` allows nothing else; Cancel only when nothing changed, otherwise Stop | Mac 1992, Windows 1995 and Apple 2009 over Motif's standard pair |
| Button length | Four words at most | Mac 1992 says three; "Use the new address" needs four and is clearer than any three |
| Tone | Plain and friendly, second person, never jokey in errors | Android 2012 and Windows 2010; Signals keeps its own radio voice |
| please and sorry | The Windows 2010 rule: please when the person is put out, sorry when something is lost | Avoids the filler apology Android 2012 warns against |

View File

@@ -53,7 +53,8 @@ id, and Caddy's request lines theirs. ipx also serves Prometheus metrics (`[web]
| `crates/feed/src/jev.rs` | Jev's pick of a category | — |
| `crates/feed/src/guard.rs` | The connection guard against internal addresses (#320) | — |
| `crates/ipx/src/download.rs` | Streaming download, naming, type sniffing, placement | `iPXDownloader.getFile` |
| `crates/ipx/src/torrent.rs` | librqbit session, seeding limits, stall abort | vendored BitTorrent 4.2.1 |
| `crates/ipx/src/torrent.rs` | Hands torrents to qBittorrent's Web API and watches them to the end, stall abort | vendored BitTorrent 4.2.1 |
| `crates/ipx/src/nzb.rs` | Hands NZBs to SABnzbd's API, watches them through post-processing, moves the finished folder in | |
| `crates/ipx/src/retention.rs` | Quota and age sweeps | `iPXQuotaManager.py` |
| `crates/ipx/src/ipc.rs` | Event and command types, the socket server | `printMSG` on stdout |
| `crates/ipx/src/auth.rs` | Argon2id hashing, session tokens, header names | — |
@@ -102,7 +103,7 @@ and the files, and no page.
a reason. What a filter skipped is judged again every scan, so a change of settings brings it
back. A feed in a group takes your settings on the group for anything you have not set on it.
7. Download what is still pending, newest first, up to the per-scan cap. A `.torrent` body goes to
the torrent path whatever its advertised type; an HTML body is a failed download — a login wall
qBittorrent and an `.nzb` body to SABnzbd whatever its advertised type; an HTML body is a failed download — a login wall
or an error page — and is deleted.
## Data model

View File

@@ -89,15 +89,41 @@ database as described above; `download_dir`, `socket`, `organize` and `fetch_int
```toml
[torrent]
enabled = true
seed_ratio = 1.0 # stop seeding at this ratio ...
seed_time_mins = 60 # ... or after this long, whichever comes first
port_range = "6881-6889"
stall_mins = 30 # give up on a torrent making no progress
enabled = true
qbittorrent_url = "http://qbittorrent:8080" # its Web UI; empty holds torrents back
username = "ipx" # empty when qBittorrent lets ipx's address in without one
password = ""
save_path = "" # where qBittorrent sees download_dir, if not at the same path
seed_ratio = 1.0 # qBittorrent stops seeding at this ratio ...
seed_time_mins = 60 # ... or after this long, whichever comes first
stall_mins = 30 # give up on a torrent making no progress
```
A `.torrent` body is handed to the torrent path whatever MIME type it was advertised as. Torrents
run on their own tasks (two at a time) so a slow swarm never blocks a scan.
Torrents go to [qBittorrent](https://www.qbittorrent.org/) through its Web API: ipx fetches the
`.torrent` (or passes on the magnet link), adds it with the episode's own folder as its save path,
and records the episode once qBittorrent has all of it. qBittorrent does the seeding. It has to be
able to write to `download_dir`: mount the same folder into its container, and if the path is not
the same as in ipx's, say where in `save_path`. A `.torrent` body is handed to qBittorrent whatever
MIME type it was advertised as. Torrents are watched on their own tasks (two at a time) so a slow
swarm never blocks a scan.
```toml
[nzb]
enabled = true
sabnzbd_url = "http://sabnzbd:8080" # empty holds NZBs back
api_key = "" # SABnzbd's API key (Config, General)
category = "ipx" # the category jobs are added under
save_path = "" # where SABnzbd sees download_dir, if not at the same path
stall_mins = 30 # give up on an NZB making no progress
```
NZBs go to [SABnzbd](https://sabnzbd.org/) the same way (#496): ipx fetches the `.nzb`, adds it
under `category` named `nzb-<id>`, follows it through the queue and post-processing, then moves the
finished folder into the episode's own and takes the job out of SABnzbd's history. SABnzbd takes no
folder for a job, only for its category, so give the category a folder inside `download_dir` as
SABnzbd sees it (for example `/ipx-downloads/.sabnzbd`), on the same disk, since the move is a
rename. An `.nzb` body is handed to SABnzbd whatever MIME type it was advertised as, and NZBs share
the torrents' two slots.
## `[web]`

View File

@@ -23,8 +23,10 @@ The iOS app, `ios/`. Format: [Keep a Changelog](https://keepachangelog.com/en/1.
### Changed
- The alert for a server out of reach reads "Unable to reach", with its buttons in sentence case, as the page writes (#507).
- The player, the badge and CarPlay talk to ipx in protobuf rather than JSON, which is smaller and quicker to read; they need an ipx with protobuf (#465), and a place saved offline by an older build is still sent (#469).
### Fixed
- The app opens with no connection instead of saying it cannot reach the server: a load that fails for want of a connection is tried again from what the app last loaded (#506).
- A question the page asks before going ahead (deleting a file, sharing an address that carries your access) is shown with Cancel and OK, rather than answered Cancel at once with nothing shown (#453).

View File

@@ -136,15 +136,34 @@ final class WebViewController: UIViewController, WKNavigationDelegate, WKUIDeleg
present(alert, animated: true)
}
/// The load from the web view's own cache has been tried since the last that worked.
private var triedCache = false
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
triedCache = false
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error) {
// No connection: the page as last loaded, from the web view's cache, which then reads
// what the service worker kept. The app's own load may not go through the worker, so
// offline it failed and said the server could not be reached (#506).
let offline: Set<URLError.Code> = [.notConnectedToInternet, .cannotConnectToHost, .cannotFindHost,
.timedOut, .networkConnectionLost, .dnsLookupFailed,
.dataNotAllowed, .internationalRoamingOff]
if !triedCache, let code = (error as? URLError)?.code, offline.contains(code), let url = Server.url {
triedCache = true
webView.load(URLRequest(url: url, cachePolicy: .returnCacheDataDontLoad))
return
}
triedCache = false
let host = Server.url?.host ?? "the server"
let alert = UIAlertController(title: "Cannot reach \(host)",
let alert = UIAlertController(title: "Unable to reach \(host)",
message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Try Again", style: .default) { [weak self] _ in
alert.addAction(UIAlertAction(title: "Try again", style: .default) { [weak self] _ in
if let url = Server.url { self?.webView.load(URLRequest(url: url)) }
})
alert.addAction(UIAlertAction(title: "Change Server", style: .default) { [weak self] _ in
alert.addAction(UIAlertAction(title: "Change server", style: .default) { [weak self] _ in
self?.askForServer()
})
if presentedViewController == nil { present(alert, animated: true) }

View File

@@ -1201,6 +1201,34 @@ nonisolated struct Ipx_SeasonRows: Sendable {
init() {}
}
/// One chapter of a file in GET /api/enclosures/{id}/chapters (#477): its start in seconds, in
/// the clock of what plays, and its title, which may be empty.
nonisolated struct Ipx_Chapter: 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 start: Double = 0
var title: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
nonisolated struct Ipx_Chapters: 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: [Ipx_Chapter] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// POST /api/playlists, the answer.
nonisolated struct Ipx_PlaylistId: Sendable {
// SwiftProtobuf.Message conformance is added in an extension below. See the
@@ -4007,6 +4035,71 @@ nonisolated extension Ipx_SeasonRows: SwiftProtobuf.Message, SwiftProtobuf._Mess
}
}
nonisolated extension Ipx_Chapter: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Chapter"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}start\0\u{1}title\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.decodeSingularDoubleField(value: &self.start) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.title) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.start.bitPattern != 0 {
try visitor.visitSingularDoubleField(value: self.start, fieldNumber: 1)
}
if !self.title.isEmpty {
try visitor.visitSingularStringField(value: self.title, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Ipx_Chapter, rhs: Ipx_Chapter) -> Bool {
if lhs.start != rhs.start {return false}
if lhs.title != rhs.title {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Ipx_Chapters: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Chapters"
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: Ipx_Chapters, rhs: Ipx_Chapters) -> Bool {
if lhs.items != rhs.items {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
nonisolated extension Ipx_PlaylistId: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".PlaylistId"
static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0")

View File

@@ -86,6 +86,15 @@ test('ago says how long since, and never for nothing', () => {
assert.match(run(`ago(${NOW - 90 * 86400})`), /2026/);
});
test('a row date is short: the time today, the day this year, the month before (#508)', () => {
const now = 'new Date(2026, 11, 3, 15, 0)';
assert.match(run(`rowDate(new Date(2026, 11, 3, 9, 36).getTime()/1000, ${now})`), /9:36/);
const day = run(`rowDate(new Date(2026, 10, 20).getTime()/1000, ${now})`);
assert.match(day, /20/); assert.doesNotMatch(day, /2026/);
assert.match(run(`rowDate(new Date(2025, 4, 2).getTime()/1000, ${now})`), /2025/);
assert.equal(run('rowDate(null)'), '');
});
test('due says how long until a feed is checked', () => {
assert.equal(run(`due(${NOW - 1})`), 'due now');
assert.equal(run(`due(${NOW + 10})`), 'in 1m');
@@ -141,6 +150,15 @@ test('an item without a title is named by its file', () => {
assert.deepEqual({ ...name({ enclosures: [{ url: 'https://x/100%.mp3' }] }) }, { text: '100%', derived: true });
});
test('a title that only opens the text is not shown above it again (#502)', () => {
const echoes = (e: object, words: string) => run(`titleEchoes(${JSON.stringify(e)}, ${JSON.stringify(words)})`);
assert.equal(echoes({ title: 'Hello there' }, 'Hello there'), true);
assert.equal(echoes({ title: 'A long post cut\u2026' }, 'A long post cut short here'), true);
assert.equal(echoes({ title: 'Episode 1' }, 'In this episode we talk'), false);
assert.equal(echoes({ title: 'Anything' }, ''), false);
assert.equal(echoes({}, 'Words'), false);
});
test('the directory sorts by name as people read, and by subscribers', () => {
const sorted = (list: object[], by: string) => run(`${JSON.stringify(list)}.sort(${by}).map(p => p.title)`);
assert.deepEqual([...sorted([{ title: 'ep 10' }, { title: 'Ep 2' }, { title: 'ep 1' }], 'byName')], ['ep 1', 'Ep 2', 'ep 10']);
@@ -358,7 +376,7 @@ test('Share says why an episode gets no page anyone can play, and warns of a key
const note = (why: string | null, url: string) => run(`noLinkNote(${JSON.stringify(why)}, ${JSON.stringify(url)})`) as string;
const paid = 'https://c10.patreonusercdn.com/ep.mp3?token-hash=abc';
assert.match(note('private', paid), /private to you.*includes your own access/s);
assert.match(note('failed', 'https://example.com/ep.mp3'), /could not be made just now/);
assert.match(note('failed', 'https://example.com/ep.mp3'), /Unable to make a page anyone can play just now/);
assert.doesNotMatch(note('failed', 'https://example.com/ep.mp3'), /own access/);
// A server with no ipx-play shares as it always has, with no reason to give.
assert.equal(note('not_set_up', 'https://example.com/ep.mp3'), '');
@@ -379,7 +397,7 @@ test('a file\'s box says where it is: the publisher, on its way, iPX, this devic
const where = (x: object) => run(`whereText(${JSON.stringify({ id: 7, deadair: 0, path: null, state: 'held', ...x })})`) as string;
assert.equal(where({}), 'Publisher only');
assert.equal(where({ state: 'pending' }), 'Queued for iPX');
assert.equal(where({ state: 'error' }), 'iPX could not download it');
assert.equal(where({ state: 'error' }), 'Unable to download to iPX');
run(`want(7, 'Ep')`);
assert.equal(where({ state: 'pending' }), 'Downloading to iPX, then this device');
run('unwant(7)');

View File

@@ -53,6 +53,16 @@ test.beforeEach(async ({ page }) => {
await expect(page.locator('#feedlist')).toBeVisible();
});
test('a toolbar button that cannot act says why, and its usual tooltip comes back when it can (#507)', async ({ page }) => {
await page.locator('#feedlist .place', { hasText: 'All Subscriptions' }).click();
await expect(page.locator('#tbRemove')).toBeDisabled();
await expect(page.locator('#tbRemove')).toHaveAttribute('title', 'Open a feed to unsubscribe from it');
await expect(page.locator('#tbRead')).toHaveAttribute('title', 'Choose an item first');
await page.locator('#feedlist .feed', { hasText: 'Test Show' }).click();
await expect(page.locator('#tbRemove')).toBeEnabled();
await expect(page.locator('#tbRemove')).toHaveAttribute('title', 'Unsubscribe from this feed');
});
test('the page loads and lists the configured feeds', async ({ page }) => {
// Regression: a ReferenceError in the script left the shell rendered and the sidebar
// empty, with every handler below the error dead. Server-side checks all passed.
@@ -493,6 +503,13 @@ test('Now Playing opens from the player bar with the artwork, show notes and Up
await expect(sheet.locator('h2')).toHaveText('Second Episode');
await expect(sheet.locator('.dbody')).toContainText('Notes for the second.');
await expect(sheet.locator('#nowqueue .childrow')).toHaveText([/First Episode/]);
// Its chapters, from the file its item names, in order; a tap plays from there (#477).
const chapters = sheet.locator('.chapters button');
await expect(chapters).toHaveText([/0:00\s*Opening/, /0:01\s*The middle/]);
await chapters.nth(1).click();
await expect.poll(() => page.evaluate(() => audio.currentTime)).toBeGreaterThanOrEqual(1.4);
await expect(chapters.nth(1)).toHaveAttribute('aria-current', 'true');
await expect(chapters.nth(0)).not.toHaveAttribute('aria-current');
await page.keyboard.press('Escape');
await expect(sheet).toBeHidden();
// From the keyboard too, and the podcast's name opens its feed.
@@ -537,6 +554,13 @@ test('a smart playlist puts its first podcasts ahead and plays on through itself
await expect(page.locator('#ptitle')).toHaveText('First Episode');
await page.locator('#pclose').click();
// Its X marks it played (#497): an onclick of the playlist's own once skipped it.
const twoFiles = async () => (await page.evaluate(() => api('/api/feeds/multi-show/entries')) as ListPage).entries
.find(e => e.title === 'Two Files')!;
await page.locator('#listening .childrow', { hasText: 'Two Files' }).locator('[data-a="remove"]').click();
await expect.poll(async () => (await twoFiles()).read).toBe(true);
await page.evaluate(e => setRead(e, false), await twoFiles());
await page.locator('#content .acts [data-a="rm"]').click();
await answer(page);
await expect(page.locator('#feedlist .feed.child', { hasText: 'Commute' })).toHaveCount(0);
@@ -1604,7 +1628,7 @@ test('a download by hand fills its bar and names its file, and only on its own s
await slow.click();
await page.locator('#files button[title="Download to iPX"]').click();
await expect(slow.locator('.dlbar.live')).toBeAttached({ timeout: 10_000 });
await expect(page.locator('#count')).toContainText(/downloading .+ — \d+%/);
await expect(page.locator('#count')).toContainText(/Downloading .+: \d+%/);
await expect(page.locator('.toast', { hasText: /^Downloaded .+\.mp3/ })).toBeVisible({ timeout: 20_000 });
await expect(slow.locator('.kind.here')).toBeVisible({ timeout: 5_000 });
@@ -3118,7 +3142,7 @@ test('a dialog keeps the keyboard inside it and gives it back on closing', async
await expect(page.locator('#modalCard[role=dialog]')).toHaveAttribute('aria-labelledby', /.+/);
await expect(page.locator('#nurl')).toBeFocused();
// Labels name their boxes (#307).
await expect(page.getByRole('textbox', { name: 'Feed URL' })).toHaveCount(1);
await expect(page.getByRole('textbox', { name: 'Feed address' })).toHaveCount(1);
for (let i = 0; i < 8; i++) {
await page.keyboard.press('Tab');
// Past the last control Tab goes to the browser's own toolbar (the body, from here), never the page behind.
@@ -3256,3 +3280,81 @@ test('a podcast told in seasons runs in its own order, one season at a time or a
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click();
await expect(page.locator('#content .seasons button.on')).toHaveText('All seasons');
});
test.describe('on a phone', () => {
test.use({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true });
test('a row spends its width on the title: unread a dot before it, pinned a pin under it (#484)', async ({ page }) => {
await page.locator('#burger').click();
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click({ timeout: 20_000 });
await page.locator('#content .tabs button[data-f="all"]').click();
const row = page.locator('#eps .ep', { hasText: 'The Pilot' });
await expect(row).toBeVisible();
// No read or pin button before the title: it starts at the row's own padding.
await expect(row.locator('.st')).toBeHidden();
await expect(row.locator('.fl')).toBeHidden();
const [r, t] = [await row.boundingBox(), await row.locator('.t').boundingBox()];
expect(t!.x - r!.x).toBeLessThan(16);
// Unread says so before the title, by a dot a screen reader names; read, nothing.
const flags = (body: object) => page.evaluate(b => fetch('/api/entries/seasoned-show/sn-1/flags',
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b) }), body);
await flags({ read: false, flagged: true });
await page.reload();
await page.locator('#burger').click();
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click();
await expect(row.locator('.t [role=img][aria-label="Unread"]')).toBeVisible();
// One line like the rest: no length under the title (#500).
await expect(row.locator('.line')).not.toContainText(/\d:\d\d/);
await expect(row.locator('.line [aria-label="Pinned"]')).toBeVisible();
// What is under the title starts where its text does, past the dot, and the date is on the
// title's line, not centred between the two.
const [dot, mark, title, date] = await Promise.all(['.udot', '.pinmark', '.t', '.date'].map(s => row.locator(s).boundingBox()));
expect(Math.abs(mark!.x - (dot!.x + dot!.width + 7))).toBeLessThan(2);
expect(date!.y + date!.height).toBeLessThan(title!.y + title!.height + 3);
await flags({ read: true, flagged: false });
await page.reload();
await page.locator('#burger').click();
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click();
await expect(row.locator('.udot')).toBeHidden();
await expect(row.locator('.pinmark')).toHaveCount(0);
});
test('the reader opened on a phone has its scroller back two frames on, and scrolls (#450)', async ({ page }) => {
await page.locator('#burger').click();
await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click({ timeout: 20_000 });
await page.locator('#content .tabs button[data-f="all"]').click();
await page.locator('#eps .ep .t').first().click();
const d = page.locator('#detail');
await expect.poll(() => d.evaluate(el => getComputedStyle(el).overflowY)).toBe('auto');
expect(await d.evaluate(el => el.style.overflowY)).toBe('');
});
test('a page of its own starts its header where a podcast\'s does (#485)', async ({ page }) => {
const artX = async (id: string) => {
await page.evaluate(id => { selectFeed(id); nav(false); }, id);
await expect(page.locator('#content .fhead .art').first()).toBeVisible();
return (await page.locator('#content .fhead .art').first().boundingBox())!.x;
};
const podcast = await artX('test-show');
for (const id of [':upnext', ':listening']) expect(await artX(id), id).toBe(podcast);
});
test('a folder\'s triangle is on the far left in a narrow margin, and a lone header button keeps its row (#486, #487, #491)', async ({ page }) => {
await page.locator('#burger').click();
const box = async (sel: string) => (await page.locator(sel).first().boundingBox())!;
// Once the drawer has slid in: measured on its way, the rows are still moving.
await expect.poll(async () => (await box('#feedlist')).x).toBeGreaterThanOrEqual(0);
await page.waitForFunction(() => document.getAnimations().length === 0);
const [list, folder, feed] = [await box('#feedlist'), await box('.feed.group .fart'), await box('#feedlist .feed:not(.group):not(.sigs):not(.plists) .fart')];
// Every row's art in one line, near the list's edge: 20 px in, where the 16 px margin #486 took
// out put it at 26.
expect(feed.x).toBe(folder.x);
expect(feed.x - list.x).toBeLessThanOrEqual(20);
// The folder's triangle first, at the list's edge, and clear of the art (#491).
const chev = await box('.feed.group .chev');
expect(chev.x - list.x).toBeLessThanOrEqual(1);
expect(chev.x + chev.width).toBeLessThanOrEqual(folder.x + 0.5);
await page.evaluate(() => { selectFeed(PLAYLISTS); nav(false); });
const [art, add] = [await box('#content .fhead .art'), await box('#content .fhead [data-a="new"]')];
expect(add.y).toBeLessThan(art.y + art.height);
});
});

View File

@@ -124,6 +124,10 @@ http.createServer((req, res) => {
// Where /flip.xml moves to for good.
'/moved.xml': ['application/rss+xml', `<?xml version="1.0"?><rss version="2.0"><channel><title>Flip Show</title>
<item><guid>flip-1</guid><title>Flip one</title></item></channel></rss>`],
// Second Episode's chapters (#477): one only for its artwork, which is not listed.
'/chapters.json': ['application/json+chapters', JSON.stringify({ version: '1.2.0', chapters: [
{ startTime: 1.5, title: 'The middle' }, { startTime: 0, title: 'Opening' }, { startTime: 1, img: `${at}/art.jpg`, toc: false },
] })],
'/said.txt': ['text/plain', 'Unable to establish a DB connection'],
'/long.txt': ['text/plain', 'This site is down for maintenance and will be back shortly, thank you for your patience while we work'],
'/empty.xml': ['application/xml', ''],

View File

@@ -1,5 +1,5 @@
<?xml version="1.0"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:podcast="https://podcastindex.org/namespace/1.0">
<channel><title>Test Show</title><link>http://127.0.0.1:8792/</link><description>A fixture feed.</description>
<itunes:image href="http://127.0.0.1:8792/art.png"/>
<itunes:category text="Technology"/>
@@ -12,5 +12,6 @@
<pubDate>Mon, 08 Sep 2026 10:00:00 +0000</pubDate>
<description>Notes for the second.</description>
<itunes:duration>900</itunes:duration>
<podcast:chapters url="http://127.0.0.1:8792/chapters.json" type="application/json+chapters"/>
<enclosure url="http://127.0.0.1:8792/ep1.mp3?2" length="40000" type="audio/mpeg"/></item>
</channel></rss>

View File

@@ -109,6 +109,16 @@ test('a page older than the script the server sends is loaded again, not run wit
expect(await kept()).not.toContain('/app.js?v=000000000000');
});
test('the page has the worker keep it however it was loaded, for the iOS app (#506)', async ({ page }) => {
await controlled(page);
const has = () => page.evaluate(async () => !!(await (await caches.open('ipx-page')).match('/')));
// As if the load had not come through the worker, which the app's own load does not.
await page.evaluate(async () => { await (await caches.open('ipx-page')).delete('/'); });
expect(await has()).toBe(false);
await page.evaluate(() => navigator.serviceWorker.controller!.postMessage({ keepPage: true }));
await expect.poll(has).toBe(true);
});
test('online, a picture in an item\'s text still comes from its publisher, through the worker', async ({ page }) => {
await controlled(page);
await page.locator('#feedlist .feed', { hasText: 'Offline Blog' }).click({ timeout: 20_000 });

View File

@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Now Playing lists the episode's chapters, when its podcast has them, with the one playing in bold; a tap plays from there (#477).
- A podcast told in seasons lists its episodes in its own order, season 1 episode 1 first, until a heading is clicked to sort it otherwise, with each season's start marked. A season picker under its tabs lists one season at a time, or the episodes in none, and a season picked can be downloaded whole (#482).
- Smart playlists, in a folder of their own in the feed list: choose the podcasts, which of them play first, unplayed episodes only or all, newest or oldest first, and the playlist keeps itself up to date. Playing from one goes on through it once Up Next is empty (#476).
- Now Playing: tap the player bar to see what is playing with its artwork large, its podcast (a tap opens it), its show notes and what follows in Up Next; Esc or the bar closes it (#475).
@@ -39,6 +40,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- The page is kept for opening offline however it was loaded, so the iOS app opens with no connection too (#506).
- On a phone, an episode's row is one line like the rest: its length, which took a line of its own, is in the reader, and the date sits on the title's line (#500).
- On an iPhone, the reader rebuilds its scrolling each time an item opens, and again after a drag that did not move it, so a freshly opened item scrolls on the first try (#450).
- The count under All Subscriptions counts only its own unread items, not those of feeds hidden from it, so it agrees with the header (#499).
- An item without a title is named in bold like the rest of the list, not in regular weight beside them (#498).
- The X on a playlist's episode marks it played again; it did nothing (#497).
- A folder's triangle in the feed list is back on the far left, in a narrower margin than before, with every feed's artwork still in line (#491).
- Opening a podcast or a list draws only the list: the feed list beside it is no longer rebuilt to move its highlight, and dates are written by one formatter rather than one a row, about 40% less work on a phone (#490).
- A report of a reader that would not scroll no longer comes from a quick flick that did scroll, and says when the reader was last swiped across, not that it was just now (#488).
- The headers of Currently Listening, Up Next, Playlists and Signals start where a podcast's does, rather than twice as far in and further down (#485).
- On a phone, a pinned item's pin in the reader's floating actions is on its accent disc again, rather than nearly invisible on a light theme (#480).
- Swiping between items on a phone no longer flashes: the pictures of the items either side are loaded ahead, so the preview under your finger shows its picture with its text, and the swipe ends only once the new item's pictures are ready (#471).
- Deleting a downloaded file, marking everything read, deleting a signal and the other actions that ask first now ask in the page's own dialog, so they go ahead in the iOS app, which answered the browser's question Cancel without showing it (#462).
@@ -54,6 +65,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- An item row's date is short and smaller: the time today, the day and month this year, the month and year before; the full date on hover (#508).
- A toolbar button that cannot act says why in its tooltip (Choose an item first, Open a feed to unsubscribe from it, Nothing to play in this item), and the admin page's Save says nothing has changed yet; on a phone a checkbox's row is 40 px to tap (#507).
- On a phone the toolbar's buttons and the list's tabs are at least 40 px to tap, a chapter no longer stays lit after a tap, and an item's pin and download buttons have names a screen reader reads, as the style guide's design half asks (#507).
- The page's words follow one style (docs/STYLE-GUIDE.md): failures say "Unable to …" and what to do, a podcast is a podcast rather than a show, a feed has an address rather than a URL, and the buttons Auto and Initials in a signal's icon picker read Pick for me and Use initials (#507).
- A title that is only the opening of an item's own text, as ipx now names an untitled item, is not shown again above that text in the reader or a directory preview (#502).
- A folder's triangle in the feed list is at its row's end, before the count, so every feed lines up with the places above at the list's edge, and on a phone Playlists' and Signals' + button sits beside the title rather than on a line of its own (#486, #487).
- On a phone, an episode's title starts at the row's edge: the read and pin buttons are gone from the row, an unread episode has a dot before its title and a pinned one a pin under it, and both are changed from the reader's actions (#484).
- Podcasts are in order by name with a leading "The", "A" or "An" set aside, in the feed list, the Podcasts shelf, a playlist's choices and the Directory: The Rest Is Science is under R, not T (#481).
- A file has one button that brings it to where you are: on a phone or in the iOS app it ends on the device, with iPX fetching it first when it has not got it, and on a computer iPX fetches it and the button then saves a copy. A line beside the file's size says where it is (publisher only, queued for iPX, on iPX, on this device), and the rarer actions (remove from this device, delete from iPX, download to iPX only) are under ⋯ (#457).
- The admin page is laid out as a feed's settings are: each tab in named parts, numbers with their unit beside them, switches for on and off, Server's Save always in reach, and on a phone the tabs in a row of their own so all four fit (#414).

View File

@@ -571,7 +571,7 @@ a{color:var(--accent)}
@media (hover:hover){.sidetools button:hover,.sidefoot button:hover{border-color:var(--accent);color:var(--fg)}}
/* Settings and the log are housekeeping: they sit under the feeds, out of the way. */
.sidefoot{
display:flex;flex-direction:column;gap:7px;padding:8px 12px;
display:flex;flex-direction:column;gap:6px;padding:8px 12px;
border-top:1px solid var(--line);flex:none;
}
.sidefoot .row{display:flex;gap:6px}
@@ -600,9 +600,9 @@ input:focus,select:focus{border-color:var(--accent)}
.clearx svg{width:11px;height:11px}
.clearable:has(>input:placeholder-shown) .clearx{display:none}
.inline .clearable{flex:1}
/* The wider left gutter is the folder triangle's; everything in the list shifts with it, so the
feeds still line up with the places above. */
#feedlist{overflow-y:auto;overscroll-behavior:contain;padding:0 8px 12px 16px;flex:1;min-height:0}
/* The wider left gutter is the folder triangle's, kept narrow (#486, #491): everything in the list
shifts with it, so the feeds still line up with the places above. */
#feedlist{overflow-y:auto;overscroll-behavior:contain;padding:0 8px 12px 10px;flex:1;min-height:0}
.feed{
display:flex;gap:10px;align-items:center;padding:7px 8px;border-radius:9px;
cursor:pointer;margin-bottom:1px;position:relative;
@@ -644,11 +644,11 @@ input:focus,select:focus{border-color:var(--accent)}
content:"";display:inline-block;width:10px;height:10px;margin-left:6px;vertical-align:-1px;border-radius:50%;
border:2px solid var(--line);border-top-color:var(--accent);animation:ipxspin .8s linear infinite;
}
/* Only a folder has a triangle, hung in the margin so every feed's art lines up with the places
above it. The button is the row's full height and 24 px wide: a near miss used to open the
folder's page, and 16 px left the triangle cramped against the art. */
/* Only a folder has a triangle, on the far left (#491), hung in the list's margin so every feed's
art lines up with the places above it. The row's full height, and the margin and the row's
padding wide, up to the art: a near miss used to open the folder's page. */
.chev{
position:absolute;left:-16px;top:0;bottom:0;width:24px;display:grid;place-items:center;
position:absolute;left:-10px;top:0;bottom:0;width:18px;display:grid;place-items:center;
border-radius:4px;color:var(--faint);
}
@media (hover:hover){.chev:hover{color:var(--fg)}}
@@ -690,7 +690,7 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
and time left move as it plays. The rest stay neutral, so that one is what stands out. */
#listening .childrow,#nowqueue .childrow{position:relative;overflow:hidden;gap:12px;padding:10px 10px 13px}
#listening .childrow .art,#nowqueue .childrow .art{width:44px;height:44px;font-size:13px}
#listening .txt b,#nowqueue .txt b{display:flex;align-items:center;gap:7px}
#listening .txt b,#nowqueue .txt b{display:flex;align-items:center;gap:6px}
#listening .txt b span,#nowqueue .txt b span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#listening .txt small,#nowqueue .txt small{display:flex;gap:12px;margin-top:3px;color:var(--faint);font-size:11.5px}
#listening .txt small .fd,#nowqueue .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
@@ -709,6 +709,12 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
.nowmeta small{color:var(--dim);font-size:12.5px;font-variant-numeric:tabular-nums}
#nowsheet h3{font-size:14px;font-weight:600;margin:22px 0 10px;color:var(--dim)}
#nowqueue{display:flex;flex-direction:column;gap:6px}
/* Chapters (#477): a tap plays from there; the one playing reads bold. */
.chapters{list-style:none;margin:0;padding:0;display:flex;flex-direction:column}
.chapters button{display:flex;gap:14px;width:100%;padding:8px 6px;border-radius:8px;text-align:left;font-size:14px}
@media (hover:hover){.chapters button:hover{background:var(--raise)}}
.chapters .ctime{min-width:4.5em;color:var(--dim);font-variant-numeric:tabular-nums}
.chapters button[aria-current]{font-weight:600}
#pnow{cursor:pointer;border-radius:8px}
@media (max-width:820px){
.nowhead{grid-template-columns:1fr;justify-items:center;text-align:center;gap:18px}
@@ -745,7 +751,7 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
/* The Directory, laid out as Apple's is: a large title, then sections. Every page carries what
kind of feed (.tabs, as the item filters are) in its title row. */
.dhead{margin-bottom:6px}
.dback{display:inline-flex;align-items:center;gap:5px;margin:0 0 8px -5px;padding:3px 5px;border-radius:6px;font-size:13px;color:var(--accent)}
.dback{display:inline-flex;align-items:center;gap:4px;margin:0 0 8px -5px;padding:3px 5px;border-radius:6px;font-size:13px;color:var(--accent)}
.dback .i{width:11px;height:11px}
@media (hover:hover){.dback:hover{background:var(--raise)}}
.dtitle{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 18px}
@@ -819,7 +825,7 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
here reads it beside it, then what it has published lately. */
.show{display:flex;gap:22px;align-items:flex-end;margin-top:4px}
.show>.art{width:180px;height:180px;font-size:48px;border-radius:12px;box-shadow:var(--shadow)}
.show .meta{min-width:0;flex:1;display:flex;flex-direction:column;align-items:flex-start;gap:5px}
.show .meta{min-width:0;flex:1;display:flex;flex-direction:column;align-items:flex-start;gap:4px}
.show h2{margin:0 0 2px;font-size:30px;line-height:1.15;font-weight:700;letter-spacing:-.02em;overflow-wrap:anywhere}
.show .sub{margin:0;color:var(--dim);font-size:13px;font-variant-numeric:tabular-nums}
.show .dfail{color:var(--bad)}
@@ -837,7 +843,7 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
.lep b a{color:var(--fg);text-decoration:none}
@media (hover:hover){.lep b a:hover{color:var(--accent)}}
.lep p{margin:4px 0 0;color:var(--dim);font-size:13px;line-height:1.5;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3;overflow:hidden}
.lep small{display:flex;align-items:center;gap:7px;margin-top:6px;color:var(--faint);font-size:12px;font-variant-numeric:tabular-nums}
.lep small{display:flex;align-items:center;gap:6px;margin-top:6px;color:var(--faint);font-size:12px;font-variant-numeric:tabular-nums}
/* Outlined, not filled: on --raise the warning and error colours fell short of AA in most light
themes, where on the row's own ground they clear it. */
.tag{
@@ -881,6 +887,9 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
#content{display:flex;flex-direction:column;min-height:0;min-width:0;flex:1}
#content>.fhead,#content>.toolbar{padding-left:20px;padding-right:20px;flex:none}
#content>.fhead{padding-top:16px}
/* A page of its own (Up Next, Playlists, Signals) has its own padding already: with this one too its
header started twice as far in as a podcast's (#485). */
#content.plain>.fhead{padding:0}
/* Three panes, as the original had: feeds beside, items above, the item below. */
#split{
@@ -947,7 +956,7 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
.fhead .sub{color:var(--dim);font-size:13px;margin-bottom:8px}
.fhead .sub a{color:var(--dim);text-decoration:none}
@media (hover:hover){.fhead .sub a:hover{color:var(--accent)}}
.acts{display:flex;gap:7px;align-items:center;margin-top:auto}
.acts{display:flex;gap:6px;align-items:center;margin-top:auto}
.acts .btn{display:inline-flex;align-items:center;gap:6px;padding:7px 13px;border-radius:999px}
.acts .btn i{font-style:normal;font-size:13px;line-height:1;opacity:.7}
@media (hover:hover){.acts .btn:hover{background:var(--raise)}}
@@ -1113,11 +1122,11 @@ body.playing .eq i:nth-child(3){animation-delay:-.6s}
@keyframes eq{from{transform:scaleY(.35)}}
@media (hover:hover){.ep .st:hover,.ep .fl:hover{background:var(--raise)}}
.ep .t{font-weight:600;font-size:13.5px;display:block;width:100%;padding:0;text-align:start;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
/* An item with no title shows its opening words: set as text, not as a heading. */
.ep .t.notitle{font-weight:400}
.ep.read .t{color:var(--dim);font-weight:500}
.ep .line{display:flex;gap:9px;align-items:center;flex-wrap:wrap;color:var(--faint);font-size:11.5px}
.ep .line{display:flex;gap:8px;align-items:center;flex-wrap:wrap;color:var(--faint);font-size:11.5px}
.ep .line:empty{display:none}
/* A phone's marks for what the row's buttons say elsewhere (#484). */
.ep .udot,.ep .pinmark,.ep .pinmark+.dot{display:none}
.ep .kept{display:inline-flex;align-items:center;gap:4px;color:var(--dim)}
.ep .kept svg{width:1em;height:1em}
.ep .fd,.ep .size,.ep .date{color:var(--dim);font-size:12.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
@@ -1164,14 +1173,14 @@ body.has-video #audio{
#pnow .eq{color:var(--accent2);margin-right:6px}
#pnow small{color:var(--faint);font-size:11.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block}
#pmid{display:flex;flex-direction:column;gap:3px;min-width:0}
#pbtns{display:flex;gap:5px;align-items:center;justify-content:center}
#pbtns{display:flex;gap:4px;align-items:center;justify-content:center}
#pbtns .iconbtn{width:34px;height:34px}
#pplay{
width:40px!important;height:40px!important;background:var(--fg);color:var(--bg);
border-radius:50%;
}
@media (hover:hover){#pplay:hover{background:var(--accent);color:var(--ink)}}
#seekrow{display:flex;gap:9px;align-items:center;font-variant-numeric:tabular-nums;font-size:11.5px;color:var(--faint)}
#seekrow{display:flex;gap:8px;align-items:center;font-variant-numeric:tabular-nums;font-size:11.5px;color:var(--faint)}
input[type=range]{
-webkit-appearance:none;appearance:none;height:4px;border-radius:3px;flex:1;
background:var(--raise);cursor:pointer;
@@ -1206,7 +1215,7 @@ dialog.ask p{margin:0;line-height:1.45}
background:var(--bg);border:1px solid var(--line);border-radius:9px;padding:10px 12px;
height:min(60vh,520px);overflow:auto;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;
}
#logbox .l{display:flex;gap:9px;white-space:pre-wrap;overflow-wrap:anywhere}
#logbox .l{display:flex;gap:8px;white-space:pre-wrap;overflow-wrap:anywhere}
#logbox time{color:var(--faint);flex:none}
#logbox .lv{flex:none;width:42px;font-weight:700}
#logbox .lv.ERROR{color:var(--bad)} #logbox .lv.WARN{color:var(--warn)}
@@ -1402,13 +1411,28 @@ body:has(#player.on) #status{padding-bottom:3px}
#topbar #epBox{width:auto;flex:1;min-width:0}
.tgroup button,.tgroup a{padding:4px 8px;min-width:32px}
.fhead.slim .acts{flex:1 1 100%}
/* One button, Playlists' and Signals' +, stays beside the title rather than on a line alone (#487). */
.fhead.slim .acts:has(>.btn:only-child){flex:none}
.fhead.slim:has(>.acts>.btn:only-child) .meta{flex-basis:0}
.iconbtn{width:38px;height:38px}
/* One pane at a time: the list, then the item over it. */
#split{grid-template-columns:1fr;grid-template-rows:1fr;grid-template-areas:"list"}
/* Title and date only; the files sit above the item's text in the reader instead. */
#files,.ephead,.ep .fd,.ep .file,.ep .size,.ep .rowacts{display:none}
.ep,#split.one .ep{grid-template-columns:20px 20px minmax(0,1fr) auto}
/* No read or pin button: their two columns cost 77px of a 390px screen before the title, empty
once an episode is read (#484). Unread is a dot before the title, pinned a pin under it, and
both are changed from the reader's actions. */
.ep .st,.ep .fl{display:none}
.ep,#split.one .ep{grid-template-columns:minmax(0,1fr) auto}
.ep:not(.read) .udot{display:inline-block;width:9px;height:9px;border-radius:50%;background:var(--accent2);margin-inline-end:7px;vertical-align:.12em}
/* The line under an unread title starts where the title's text does, past the dot, and the date
sits on the title's baseline: centred on the row, it floated between the two lines. */
.ep:not(.read) .line{padding-inline-start:16px}
.ep .date{align-self:baseline}
.ep .pinmark{display:inline-flex;color:var(--dim)}
.ep .pinmark+.dot{display:block}
.ep .pinmark svg{width:.9em;height:.9em}
#grab{display:none}
#detail{position:fixed;inset:0;z-index:38;display:none;border-top:0;padding:12px 16px 90px;padding-top:calc(12px + var(--safe-t))}
body.reading #detail{display:block}
@@ -1522,7 +1546,7 @@ body:has(#player.on) #status{padding-bottom:3px}
.iconbtn{width:40px;height:40px;border-radius:999px;background:var(--panel2)}
.tgroup{border-radius:999px}
.tgroup button+button,.tgroup button+a{border-left-color:var(--edge)}
.tgroup button,.tgroup a{min-width:36px;height:40px;padding:0 8px}
.tgroup button,.tgroup a{min-width:40px;height:40px;padding:0 8px}
/* Text boxes filled, and at 16px or more: Safari zooms the page in on one any smaller. */
input[type=search],input[type=text],input[type=password],input[type=number],select{
@@ -1545,7 +1569,7 @@ body:has(#player.on) #status{padding-bottom:3px}
/* Tabs as a segmented control: equal segments on one track, the chosen one lifted. */
.tabs{flex:1 1 100%;border-radius:10px;padding:2px}
.tabs button,.tabs a{flex:1;text-align:center;padding:7px 4px;border-radius:8px;font-size:14px}
.tabs button,.tabs a{flex:1;text-align:center;padding:7px 4px;border-radius:8px;font-size:14px;min-height:40px}
.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%}
@@ -1556,8 +1580,9 @@ body:has(#player.on) #status{padding-bottom:3px}
.ep{padding:10px 8px;border-radius:10px;min-height:44px}
.ep.sel{border-color:var(--edge)}
.ep .t{font-size:17px}
.ep .line,.ep .date{font-size:15px}
.ep+.ep{background-image:linear-gradient(var(--line),var(--line));background-size:calc(100% - 64px) 1px;background-position:64px 0;background-repeat:no-repeat}
.ep .line{font-size:15px}
.ep .date{font-size:13px}
.ep+.ep{background-image:linear-gradient(var(--line),var(--line));background-size:calc(100% - 8px) 1px;background-position:8px 0;background-repeat:no-repeat}
.ep.sel,.ep.sel+.ep{background-image:none}
.feed{padding:9px 10px;min-height:44px;border-radius:10px}
.places{border-bottom-color:var(--edge);padding-bottom:10px;margin-bottom:10px}
@@ -1580,7 +1605,7 @@ body:has(#player.on) #status{padding-bottom:3px}
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}
.check{font-size:17px;min-height:40px}
/* A feed's settings, at a phone's sizes. */
.card.fset{padding:0}
.fsetbody{padding:20px 16px 24px}

View File

@@ -19,16 +19,16 @@
<span id="applogo" title="iPX"><img class="logo onlight" src="/logo.svg" alt="iPX"><img class="logo ondark" src="/logo-dark.svg" alt="iPX"><img class="logo classic" src="/icon.png" alt="iPodderX"></span>
<div class="tgroup">
<button id="addFeed" title="Add a feed" aria-label="Add a feed" data-icon="plus"></button>
<button id="tbRemove" title="Unsubscribe from this feed" aria-label="Unsubscribe from this feed" data-icon="circleMinus" disabled></button>
<button id="tbRemove" title="Open a feed to unsubscribe from it" aria-label="Unsubscribe from this feed" data-icon="circleMinus" disabled></button>
<button id="scanAll" title="Check every feed for new items" aria-label="Check every feed for new items" data-icon="scan"></button>
</div>
<div class="tgroup item">
<button id="tbPlay" title="Play the selected item" aria-label="Play the selected item" data-icon="play" disabled></button>
<button id="tbRead" title="Mark the selected item read or unread" aria-label="Mark read or unread" data-icon="check" disabled></button>
<button id="tbFlag" title="Pin the selected item, so it is never deleted" aria-label="Pin" data-icon="pin" disabled></button>
<button id="tbPlay" title="Choose an item first" aria-label="Play the selected item" data-icon="play" disabled></button>
<button id="tbRead" title="Choose an item first" aria-label="Mark read or unread" data-icon="check" disabled></button>
<button id="tbFlag" title="Choose an item first" aria-label="Pin" data-icon="pin" disabled></button>
</div>
<span class="grow"></span>
<span class="clearable" id="epBox"><input type="search" id="epSearch" placeholder="Search" aria-label="Search"><button type="button" class="clearx" title="Clear" aria-label="Clear" data-icon="close"></button></span>
<span class="clearable" id="epBox"><input type="search" id="epSearch" placeholder="Search" aria-label="Search"><button type="button" class="clearx" title="Clear the search" aria-label="Clear the search" data-icon="close"></button></span>
<div class="tgroup" id="admintools">
<button id="prefs" title="Settings" aria-label="Settings" data-icon="settings"></button>
<a id="admin" href="/admin" title="Admin: the server's settings, accounts and the log" aria-label="Admin" data-icon="admin"></a>
@@ -36,7 +36,7 @@
</header>
<div id="shell">
<aside id="sidebar">
<div class="searchwrap"><span class="clearable"><input type="search" id="feedFilter" placeholder="Filter feeds…" aria-label="Filter feeds"><button type="button" class="clearx" title="Clear" aria-label="Clear" data-icon="close"></button></span></div>
<div class="searchwrap"><span class="clearable"><input type="search" id="feedFilter" placeholder="Filter feeds…" aria-label="Filter feeds"><button type="button" class="clearx" title="Clear the filter" aria-label="Clear the filter" data-icon="close"></button></span></div>
<div id="feedlist"></div>
<div class="sidefoot">
<div class="who"><span id="who"></span><button id="signout" title="Sign out" aria-label="Sign out" data-icon="signout"></button></div>

View File

@@ -3,7 +3,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark light">
<title>Sign in — iPX</title>
<title>Sign in to iPX</title>
<link rel="icon" type="image/png" sizes="128x128" href="/favicon.png" media="(prefers-color-scheme:light)">
<link rel="icon" type="image/png" sizes="128x128" href="/favicon-dark.png" media="(prefers-color-scheme:dark)">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">

View File

@@ -63,9 +63,9 @@ async function drawServer(){
: 'This server has no TypeSafe key (<code>TYPESAFE_KEY</code>), so each person uses their own.'}</p>
${anum('gsigdays', 'A new Signal looks back', g.signal_days, 'days', ' min="1" max="365"')}
<p class="cap">Each item read is a call to TypeSafe, so a longer look back costs more, once for each new Signal.</p>`)}
<div class="afoot"><button class="btn primary" id="gsave" disabled>${ICON.check} Save</button></div>`;
<div class="afoot"><button class="btn primary" id="gsave" title="Nothing changed yet" disabled>${ICON.check} Save</button></div>`;
// Save waits for a change, so it says whether there is one.
box.oninput = () => { $<HTMLButtonElement>('#gsave').disabled = false; };
box.oninput = () => { dim($<HTMLButtonElement>('#gsave'), null, 'Save'); };
$<HTMLButtonElement>('#gsave').onclick = async () => {
try{
await api('/api/settings', {method: 'PATCH', body: JSON.stringify({
@@ -79,7 +79,7 @@ async function drawServer(){
// Left alone while the server has no key to offer, rather than switched off.
...($<HTMLInputElement>('#gsig').disabled ? {} : {signals_on_server: $<HTMLInputElement>('#gsig').checked})})});
toast('Settings saved');
$<HTMLButtonElement>('#gsave').disabled = true;
dim($<HTMLButtonElement>('#gsave'), 'Nothing changed yet', 'Save');
}catch(e){ toast(why(e), true); }
};
}
@@ -156,7 +156,7 @@ async function drawDirectoryStatus(){
const sh = s.shared;
if(sh){
const when = new Date(sh.at * 1000).toLocaleString();
lines.push(sh.error ? `Sharing failed at ${esc(when)}: ${esc(sh.error)}`
lines.push(sh.error ? `Unable to share at ${esc(when)}: ${esc(sh.error)}`
: `Shared ${plural(sh.accepted, 'feed')} at ${esc(when)}.` +
(sh.refused_private ? ` The directory refused ${plural(sh.refused_private, 'feed')} as private.` : '') +
(sh.refused_blocked ? ` ${plural(sh.refused_blocked, 'feed')} the directory has removed.` : ''));
@@ -272,7 +272,7 @@ function drawLogView(){
<div class="tabs" id="logtabs">
${Object.keys(LOG_TABS).map(t =>
`<button data-t="${t}" class="${logTab === t ? 'on' : ''}" title="${LOG_TAB_SAYS[t]}">${
{all: 'All', daemon: 'Daemon I/O', scan: 'Scans', web: 'HTTP'}[t]}</button>`).join('')}
{all: 'All', daemon: 'Daemon I/O', scan: 'Checks', web: 'HTTP'}[t]}</button>`).join('')}
</div></div>
<div class="logbar">
<select id="loglevel" aria-label="Level">

View File

@@ -35,8 +35,8 @@ $('#modal').onclick=(e: MouseEvent)=>{ if((e.target as Element).id==='modal') cl
$<HTMLButtonElement>('#addFeed').onclick=()=>{
openModal(`<h3>Add a feed</h3>
<div class="field"><label for="nurl">Feed URL</label><input type="text" id="nurl" placeholder="https://example.com/rss">
<span class="hint">A Patreon token on its own adds every show from that creator.</span></div>
<div class="field"><label for="nurl">Feed address</label><input type="text" id="nurl" placeholder="https://example.com/rss">
<span class="hint">A Patreon token on its own adds every podcast from that creator.</span></div>
<div class="field"><label for="nkw">Keywords (optional, comma separated)</label>
<input type="text" id="nkw"><span class="hint">Only items matching a keyword are downloaded.</span></div>
<label class="check"><input type="checkbox" id="nexp"> Allow items marked explicit</label>
@@ -279,7 +279,9 @@ async function fillShow(box: HTMLElement,p: DirFeed){
}
const items=got.items;
list.innerHTML=items.length?items.map(e=>{
const name=entryName(e), text=name.derived?'':plainText(e.description).slice(0,500);
const name=entryName(e), words=plainText(e.description);
// No excerpt that only repeats the name ipx made from these same words (#502).
const text=name.derived||titleEchoes(e,words)?'':words.slice(0,500);
const when=[dateOf(e.published),e.duration&&clock(e.duration)].filter(Boolean);
return `<article class="lep"><b>${webUrl(e.link)?`<a href="${esc(webUrl(e.link))}" target="_blank" rel="noopener">${esc(name.text)}</a>`:esc(name.text)}</b>`
+(text?`<p>${esc(text)}</p>`:'')
@@ -301,7 +303,7 @@ function catTile(c: string,name: string,count: string,rows: DirFeed[]){
async function renderListed(v: {title: string, icon: string, url?: string, blurb?: string}){
const box=$('#content');
box.classList.add('plain');
$<HTMLButtonElement>('#tbRemove').disabled=true;
dim($<HTMLButtonElement>('#tbRemove'),NO_FEED,UNSUB);
syncTools(null);
if(v===VIEWS[':directory']){
$<HTMLInputElement>('#epSearch').placeholder='Find a feed…';
@@ -366,8 +368,9 @@ function drawListening(box: HTMLElement,rows: Entry[]){
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){
/// to take it out of the list, which `remove` does. `start` plays it: a playlist's goes on through
/// the playlist.
function listenRow(e: Entry,removeLabel: string,remove: ()=>void,start=()=>play(e)){
// Carries its episode, for paintListenRow to repaint as the player moves.
const el: HTMLDivElement & {entry?: Entry}=document.createElement('div');
el.className='childrow';
@@ -379,7 +382,7 @@ function listenRow(e: Entry,removeLabel: string,remove: ()=>void){
`<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);
:el.classList.contains('now')&&!audio.paused?audio.pause():start();
paintListenRow(el);
return el;
}
@@ -456,7 +459,7 @@ function due(ts: number){
function deadSavedText(me: Me|null){
const s=me&&me.deadair_saved||0;
return s?`It has saved you ${spanText(s)} of dead air, on episodes you heard three quarters of or more.`
:'Turn it on in a show\'s settings, or beside the speed while it plays, to cut the dead air from it.';
:'Turn it on in a podcast\'s settings, or beside the speed while it plays, to cut the dead air from it.';
}
async function prefsModal(){
@@ -471,7 +474,7 @@ async function prefsModal(){
<div class="field" id="smodefield"${THEMES[theme.name].modes?'':' hidden'}><label for="smode">Light or dark</label>
<select id="smode">${Object.entries(MODES).map(([k,t])=>
`<option value="${k}"${theme.mode===k?' selected':''}>${esc(t)}</option>`).join('')}</select>
<span class="hint">Auto follows your system's light/dark setting.</span></div>
<span class="hint">Auto follows your system's light or dark setting.</span></div>
<div class="field"><label for="sfont">Interface font</label>
<select id="sfont">${Object.entries(FONTS).map(([k,t])=>
`<option value="${k}"${font===k?' selected':''}>${esc(t)}</option>`).join('')}</select></div>
@@ -651,7 +654,7 @@ function settingsModal(f: Feed, newUrl?: string){
// Each part named in a column of its own, the controls beside it (#290): the dialog had grown one
// captioned setting at a time into a single column three screens long on a phone.
const sect=(title: string, body: string)=>`<section class="fsec"><h4>${title}</h4><div class="fsecin">${body}</div></section>`;
const these=isGroup?'these shows':'this show';
const these=isGroup?'these podcasts':'this podcast';
// The places in the sidebar this show's items go to, drawn as the sidebar draws them (#288, #289).
const place=(id: string, key: 'hide_from_all'|'hide_from_signals', icon: string, title: string)=>{
const byList=f.group?S.feeds.find(g=>g.id===f.group&&g[key]):undefined;
@@ -709,7 +712,7 @@ function settingsModal(f: Feed, newUrl?: string){
// The download limit, said as what it does. A number in a box hid that it is a window on the
// newest items, not a pace through the back catalogue (#97).
const each=isGroup?' of each show':'';
const each=isGroup?' of each podcast':'';
const older=' Older ones stay listed, to download by hand.';
const caption=()=>mode==='newest'
? `Downloads the newest <input type="number" id="smax" min="1" value="${newest}"
@@ -806,7 +809,7 @@ function downloadLatestModal(f: Feed){
openModal(`<h3>Download latest items</h3>
<div class="field"><label for="dcount">How many of the newest undownloaded items?</label>
<input type="number" id="dcount" min="1" max="100" value="5">
<span class="hint">Queued immediately, ignoring the per-scan limit.</span></div>
<span class="hint">Downloaded now, past the limit on each check.</span></div>
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Cancel" aria-label="Cancel">${ICON.close}</button>
<button class="btn ico primary" id="dgo" title="Download" aria-label="Download">${ICON.download}</button></div>`);
$<HTMLButtonElement>('#dgo').onclick=async()=>{

View File

@@ -31,7 +31,7 @@ function connect(){
// every pending bar at once, so adding a feed looked like it was fetching the lot.
const bar=document.querySelector<HTMLElement>(`.dlbar[data-bar="${ev.enclosure}"] i`);
if(bar){ bar.style.width=pct+'%'; bar.parentElement!.classList.add('live'); }
$('#count') && ($('#count').textContent=`downloading ${ev.file} — ${pct.toFixed(0)}%`);
$('#count') && ($('#count').textContent=`Downloading ${ev.file}: ${pct.toFixed(0)}%`);
}
else if(ev.ev==='download_done'){
const bar=document.querySelector(`.dlbar[data-bar="${ev.enclosure}"]`);

View File

@@ -28,7 +28,7 @@ function renderFeed(){
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;
dim($<HTMLButtonElement>('#tbRemove'),f?null:NO_FEED,UNSUB);
syncTools(null);
if(!v&&!f&&!sg){ box.innerHTML='<p class="empty">Add a feed to get started.</p>'; $('#count').textContent=''; return; }
const name=f?(f.title||f.id):sg?sg.name:v.title;

View File

@@ -181,11 +181,11 @@ function renderFeeds(){
// The mark sits on the artwork, the thing the eye scans the list by, and the line under
// the name says what is wrong in place of the counts.
`<span class="fart">${mine.length?folderArt(f,mine):artHTML(f.image,f.title||f.id)}`+
(err?`<span class="ferr" role="img" title="${esc(err)}" aria-label="Error: ${esc(err)}">${ICON.alert}</span>`:'')+
(err?`<span class="ferr" role="img" title="${esc(err)}" aria-label="Not updating: ${esc(err)}">${ICON.alert}</span>`:'')+
(f.pinned?`<span class="fpin" role="img" title="Pinned" aria-label="Pinned">${ICON.pinOn}</span>`:'')+`</span>`+
`<div class="txt"><b>${esc(f.title||f.id)}</b><small>`+
(nbad?`${plural(nbad,'feed')} not updating`
:err?esc(f.failing?.reason||'The last check failed')
:err?esc(f.failing?.reason||'Unable to read it at the last check')
:`${mine.length?plural(mine.length,'feed'):plural(eps,'item')} · ${saved} downloaded`)+
`</small></div>`+
(f.orphaned?'<span class="tag" title="No longer listed, kept because it has downloads">Gone</span>':'')+
@@ -204,7 +204,16 @@ function renderFeeds(){
function selectFeed(id: string){
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();
markSelected(); renderFeed(); loadEntries();
}
/// The highlight moved to the feed now open. Rebuilding every row for it, as selecting once did,
/// was a third of a list's drawing time on a phone.
function markSelected(){
for(const el of $$<HTMLElement>('#feedlist [data-id]')){
const on=el.dataset.id===S.feed;
el.classList.toggle('sel',on);
if(on) el.setAttribute('aria-current','page'); else el.removeAttribute('aria-current');
}
}
/// A failing feed's error, in plain words with something to do about it, once `failing` is

View File

@@ -118,7 +118,8 @@ function beside(dx: number){
/// beside it with it.
function slide(dx: number, ms = 160){
const d = $('#detail'); if(!d) return;
slidAt = Date.now();
// Only a move across: every touch in the reader that is not a swipe ends in slide(0) (#488).
if(dx) slidAt = Date.now();
dx = Math.round(dx); // whole pixels, or the seam between the reader and its neighbour blurs
const w = d.clientWidth || 1, tr = ms ? `transform ${ms}ms ease-out, opacity ${ms}ms ease-out` : 'none';
d.style.transition = tr;
@@ -209,7 +210,7 @@ document.addEventListener('touchcancel', () => { if(touch?.pane === 'list') pull
// 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,
let drag: {x: number, y: number, t: 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'
@@ -225,7 +226,7 @@ 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), moves: 0, cancelled: false};
drag = {x: t.clientX, y: t.clientY, t: Date.now(), top: d.scrollTop, on: named(ev.target as Element), moves: 0, cancelled: false};
// After the swipe's own touchstart, which may cancel it, has run.
queueMicrotask(() => { if(drag) drag.cancelled = ev.defaultPrevented; });
}, {passive: true});
@@ -234,8 +235,28 @@ document.addEventListener('touchend', ev => {
const d = $('#detail'), t = ev.changedTouches[0], g = drag;
drag = null;
if(!g || !d || !t) return;
const dy = t.clientY - g.y, room = d.scrollHeight - d.clientHeight;
if(!stuckDrag(dy, t.clientX - g.x, g.top, d.scrollTop, room)) return;
const dy = t.clientY - g.y, dx = t.clientX - g.x, room = d.scrollHeight - d.clientHeight, ms = Date.now() - g.t;
if(!stuckDrag(dy, dx, g.top, d.scrollTop, room)) return;
// Looked at again a moment later: iOS scrolls off the main thread, and a fast flick can end
// before the page has been told where it went (#488).
setTimeout(() => {
if(stuckDrag(dy, dx, g.top, d.scrollTop, room)) stuck(d, t, g, dy, room, ms);
}, 300);
});
/// Makes iOS build the reader's scroller again (#450): every stuck drag was on a reader whose
/// content had been swapped, with nothing over it and the touch left alone, which is WebKit keeping
/// a scroller sized for what was there before. Two frames without overflow, so the hidden state is
/// committed and not merged away with the change back.
function rearm(d: HTMLElement){
d.style.overflowY = 'hidden';
requestAnimationFrame(() => requestAnimationFrame(() => { d.style.overflowY = ''; }));
}
let stuckAt = 0;
function stuck(d: HTMLElement, t: Touch, g: NonNullable<typeof drag>, dy: number, room: number, ms: number){
rearm(d);
// A second report soon after the first says rearm did not free it.
const again = stuckAt ? Math.round((Date.now() - stuckAt) / 1000) + 's ago' : 'never';
stuckAt = Date.now();
const inert = ([...document.body.children] as HTMLElement[]).filter(el => el.inert).map(named).join(' ');
report('scroll_stuck', {feed: S.feed, state: [
`top ${g.top} of ${room}`, `drag ${Math.round(dy)}px`, `started on ${g.on}`,
@@ -244,6 +265,6 @@ document.addEventListener('touchend', ev => {
`transform ${d.style.transform || 'none'}`, `peek ${$('#dpeek') ? 'left behind' : 'gone'}`,
`overflow ${getComputedStyle(d).overflowY}`, `reading ${document.body.classList.contains('reading')}`,
`shown ${Math.round((Date.now() - shownAt) / 1000)}s ago`, `${S.entries.length} loaded`,
`from x ${Math.round(g.x)}`, `${g.moves} moves seen`, `touch ${g.cancelled ? 'cancelled' : 'left alone'}`,
`slid ${slidAt ? Math.round((Date.now() - slidAt) / 1000) + 's ago' : 'never'}`].join(', ')});
});
`from x ${Math.round(g.x)}`, `${g.moves} moves seen in ${ms}ms`, `touch ${g.cancelled ? 'cancelled' : 'left alone'}`,
`slid ${slidAt ? Math.round((Date.now() - slidAt) / 1000) + 's ago' : 'never'}`, `last stuck ${again}`].join(', ')});
}

View File

@@ -146,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?(seasonUnread(f.id)??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:unreadInAll();
$('#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;
@@ -195,12 +195,16 @@ function epEl(e: Entry){
<button class="st" data-a="read" title="Mark ${e.read?'unread':'read'}" aria-label="Mark ${e.read?'unread':'read'}">${
inPlayer(e)?EQ:(e.read?'':'<span aria-hidden="true">●</span>')}</button>
<button class="fl${e.flagged?' on':''}" data-a="flag" aria-pressed="${!!e.flagged}" title="${
e.flagged?'Unpin':'Pin, so it is never deleted'}">${e.flagged?ICON.pinOn:ICON.pin}</button>
e.flagged?'Unpin':'Pin, so it is never deleted'}" aria-label="${e.flagged?'Unpin':'Pin, so it is never deleted'}">${e.flagged?ICON.pinOn:ICON.pin}</button>
<div class="body">
<button type="button" class="t${name.derived?' notitle':''}">${esc(name.text)}</button>
<button type="button" class="t">${e.read?'':'<span class="udot" role="img" aria-label="Unread"></span>'}${esc(name.text)}</button>
<div class="line">${[
// On a phone, where the row has no pin button, what says it is pinned (#484).
e.flagged&&`<span class="pinmark" role="img" aria-label="Pinned">${ICON.pinOn}</span>`,
num&&`<span>${num}</span>`,
left&&`<span>${left}</span>`,
// Not on a phone, where it took a second line under a title the others do not have, and
// the reader says it anyway.
left&&!window.matchMedia?.('(max-width:820px)')?.matches&&`<span>${left}</span>`,
others>0&&`<span>+${others} more file${others===1?'':'s'}</span>`,
enc&&enc.deadair&&enc.deadair>0&&`<span title="DeadAir cut its dead air">${shorter(enc.deadair)}</span>`,
enc&&enc.deadair_pending&&DEAD_PENDING,
@@ -215,12 +219,12 @@ function epEl(e: Entry){
${enc&&!has?`<div class="dlbar" data-bar="${enc.id}"><i></i></div>`:''}
</div>
<span class="size">${enc?mb(enc.length):''}</span>
<span class="date">${dateOf(e.published)}</span>
<span class="date" title="${dateOf(e.published)}">${rowDate(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>`:'')}
enc.state==='skipped'?kindOf(enc):'file'}" aria-label="Download this ${enc.state==='skipped'?kindOf(enc):'file'}">${ICON.download}</button>`:'')}
${has?`<button class="iconbtn" data-a="del" title="Delete file" aria-label="Delete file">${ICON.trash}</button>`:''}
</div>`;
el.onclick=()=>selectEntry(e);
@@ -262,7 +266,7 @@ function kindIcon(enc: Enclosure){
const k=kindOf(enc);
const i=(<Record<string,string>>{audio:ICON.audio,video:ICON.video,image:ICON.image,pdf:ICON.doc,torrent:ICON.torrent})[k]||ICON.file;
const [cls,label]=enc.path ? [' here',`${k}, downloaded`]
: enc.state==='error' ? [' bad',`${k}, download failed${enc.last_error?': '+enc.last_error:''}`]
: enc.state==='error' ? [' bad',`${k}, unable to download${enc.last_error?': '+enc.last_error:''}`]
: ['',k];
return `<span class="kind${cls}" title="${esc(label)}" aria-label="${esc(label)}">${i}</span>`;
}
@@ -273,13 +277,19 @@ const feedName=(id: string|null|undefined): string=>{ const f=S.feeds.find(x=>x.
/// What an item is called. Its title, or for one published without (RSS 2.0 makes it optional,
/// and Scripting News titles almost none of its posts) the opening of its text, then its file's
/// name, then its feed and date: "(untitled)" fifty times down a list said nothing about any of
/// them. `derived` marks a name that is not a title, which the list sets as text, not heading.
/// them. `derived` marks a name that is not a title, which the reader does not repeat as its text.
/// Feed HTML as plain words. An inert document: nothing in it loads or runs, where a detached
/// element fetches its images. A line break or paragraph's end is a space, or "2010)<br>Recorded"
/// read "2010)Recorded".
const plainText=(html?: string|null)=>html
? (new DOMParser().parseFromString(html.replace(/<(br|\/p|\/div|\/li|\/h\d)\b[^>]*>/gi,' $&'),'text/html').body.textContent||'')
.replace(/\s+/g,' ').trim() : '';
/// Whether the title is only the opening of the item's own text: the name ipx gives an untitled
/// item as it stores it (#502), or a post titled by its first sentence. Shown above that text, it
/// reads twice.
const titleEchoes=(e: Partial<Entry>, words=plainText(e.description))=>
!!e.title && !!words && words.startsWith(e.title.trim().replace(/\u2026$/,''));
// ipx names an untitled item as it stores it (#502); this is for a list saved offline before then.
function entryName(e: Partial<Entry>): {text: string, derived: boolean}{
if(e.title&&e.title.trim()) return {text:e.title, derived:false};
const words=plainText(e.description);
@@ -389,8 +399,12 @@ function dragSplit(pane: HTMLElement){
/// Which item the toolbar's play, read and keep buttons act on.
const cur=()=>S.entries.find(x=>entryKey(x)===S.sel);
function syncTools(e: Entry|null){
$<HTMLButtonElement>('#tbPlay').disabled=!(e&&e.enclosures.some(isPlayable));
$<HTMLButtonElement>('#tbRead').disabled=$<HTMLButtonElement>('#tbFlag').disabled=!e;
const pick=e?null:'Choose an item first';
dim($<HTMLButtonElement>('#tbPlay'),pick??(e!.enclosures.some(isPlayable)?null:'Nothing to play in this item'),'Play the selected item');
dim($<HTMLButtonElement>('#tbRead'),pick,e?`Mark ${e.read?'unread':'read'}`:'');
dim($<HTMLButtonElement>('#tbFlag'),pick,e?.flagged?'Unpin':'Pin, so it is never deleted');
// The play button says Pause when the item chosen is the one playing.
syncPlayButtons();
// The same icons as the item's own buttons beside its title, so the two never disagree. Each
// shows what is, as the pin always did: read showed what a click would do, so the two side by
// side said opposite things (#74). The shape carries it, not the colour.
@@ -398,10 +412,6 @@ function syncTools(e: Entry|null){
$<HTMLButtonElement>('#tbRead').setAttribute('aria-pressed',String(!!(e&&e.read)));
$<HTMLButtonElement>('#tbFlag').setAttribute('aria-pressed',String(!!(e&&e.flagged)));
$<HTMLButtonElement>('#tbFlag').innerHTML=e&&e.flagged?ICON.pinOn:ICON.pin;
if(e){
$<HTMLButtonElement>('#tbRead').title=`Mark ${e.read?'unread':'read'}`;
$<HTMLButtonElement>('#tbFlag').title=e.flagged?'Unpin':'Pin, so it is never deleted';
}
}
/// The item's text in the pane below the list, and its files in the pane beside it.
@@ -423,6 +433,7 @@ function showDetail(e: Entry|null){
const narrow=!!window.matchMedia?.('(max-width:820px)')?.matches;
box.innerHTML=detailHtml(e);
if(files) files.innerHTML=narrow?'':`<div class="fhd">Files</div>${encs}`;
if(narrow) rearm(box);
$<HTMLButtonElement>('#dback').onclick=()=>showDetail(null);
const view=box.querySelector<HTMLSelectElement>('.tview');
if(view) view.onchange=()=>{
@@ -460,7 +471,7 @@ function detailHtml(e: Entry){
at hand anywhere in a long post, not only back at its top. */
narrow ? `<div class="dfloat">${back}${acts}</div>` : back}
${/* A post without a title starts with its text: its own first words as a heading above
themselves would read as a mistake. */ e.title&&e.title.trim() ? `<h3 class="dt">${esc(e.title)}</h3>` : ''}
themselves would read as a mistake. */ e.title&&e.title.trim()&&!titleEchoes(e) ? `<h3 class="dt">${esc(e.title)}</h3>` : ''}
<div class="dmeta">
${/* Joined, so a missing date or number leaves no stray dot behind. */
[f&&esc(f.title||f.id), num, dateOf(e.published), e.duration&&clock(e.duration),
@@ -492,7 +503,7 @@ function whereText(x: Enclosure){
if(here) return 'On this device';
if(wanted.has(x.id)) return 'Downloading to iPX, then this device';
if(x.state==='pending') return 'Queued for iPX';
if(x.state==='error') return 'iPX could not download it';
if(x.state==='error') return 'Unable to download to iPX';
return 'Publisher only';
}
return here ? 'On iPX and this device' : busy ? 'On iPX, downloading to this device' : 'On iPX';
@@ -578,7 +589,7 @@ const shareAt=(url: string, secs: number)=>secs>=5 ? `${url}?t=${Math.floor(secs
function noLinkNote(why: string|null, url: string): string{
const notes: string[]=[];
if(why==='private') notes.push('This podcast\'s feed is private to you, so it gets no page anyone can play, and its file is never shared: this is the episode\'s own page.');
else if(why==='failed') notes.push('The page anyone can play could not be made just now, so this is the episode\'s own address. Try again later for a link to it.');
else if(why==='failed') notes.push('Unable to make a page anyone can play just now, so this is the episode\'s own address. Try again later for a link to it.');
if(carriesAccess(url)) notes.push(ACCESS_WARNING);
return notes.map(n=>`<p class="hint">${esc(n)}</p>`).join('');
}

View File

@@ -11,5 +11,5 @@ document.getElementById('f')!.onsubmit = async e => {
}),
});
if (r.ok) location.href = '/';
else msg.textContent = await r.text() || 'Sign in failed';
else msg.textContent = await r.text() || 'Unable to sign in. Check your name and password.';
};

View File

@@ -34,6 +34,7 @@ function drawNow(){
<small>${[dateOf(e.published),e.duration?clock(e.duration):''].filter(Boolean).join(', ')}</small>
</div>
</div>
<div id="nowchaps"></div>
${upNext.length?`<h3>Up Next</h3><div class="childlist" id="nowqueue"></div>`:''}
<h3>Show notes</h3>
<div class="dbody">${textOf(e)}</div>`;
@@ -41,6 +42,52 @@ function drawNow(){
$<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)))));
drawChapters();
}
/// Chapters of what plays (#477), asked for once a file and clock: DeadAir's copy has its own
/// times. A failure is forgotten, so the next opening asks again.
const chapterLists=new Map<string,Promise<Chapter[]>>();
let nowChapters: Chapter[]=[];
function chaptersOf(enc: number, deadair: boolean): Promise<Chapter[]> {
const k=`${enc}${deadair?'d':''}`;
let got=chapterLists.get(k);
if(!got){
got=api(`/api/enclosures/${enc}/chapters${deadair?'?deadair=true':''}`).catch(()=>{ chapterLists.delete(k); return []; });
chapterLists.set(k,got);
}
return got;
}
function drawChapters(){
const enc=player.enc;
nowChapters=[];
if(enc==null) return;
chaptersOf(enc,!!player.src?.includes('/deadair')).then(cs=>{
const box=$('#nowchaps');
if(!box||!nowOpen()||player.enc!==enc||!cs.length) return;
nowChapters=cs;
box.innerHTML=`<h3>Chapters</h3><ol class="chapters">${cs.map((c,i)=>
`<li><button type="button" data-i="${i}"><span class="ctime">${clock(c.start)}</span><span>${esc(c.title)||`Chapter ${i+1}`}</span></button></li>`).join('')}</ol>`;
for(const b of $$<HTMLButtonElement>('button',box)) b.onclick=()=>{
audio.currentTime=cs[Number(b.dataset.i)]!.start;
// Marked now: a player still loading says nothing until it plays.
markChapter();
if(audio.paused) audio.play();
};
markChapter();
});
}
/// The chapter playing now, marked as the one current.
function markChapter(){
if(!nowChapters.length||!nowOpen()) return;
// A seek to a chapter's start can land a frame before it.
const t=audio.currentTime+.25;
let at=-1;
nowChapters.forEach((c,i)=>{ if(c.start<=t) at=i; });
$$<HTMLButtonElement>('#nowchaps button').forEach((b,i)=>{
if(i===at) b.setAttribute('aria-current','true'); else b.removeAttribute('aria-current');
});
}
audio.addEventListener('timeupdate',markChapter);
$('#pnow').onclick=()=>nowOpen()?closeNow():openNow();
$('#pnow').onkeydown=(ev: KeyboardEvent)=>{ if(ev.key==='Enter'||ev.key===' '){ ev.preventDefault(); $('#pnow').click(); } };

View File

@@ -5,6 +5,8 @@
// it was.
const worker=('serviceWorker' in navigator) ? navigator.serviceWorker : null;
worker?.register('/sw.js').catch(()=>{});
// The worker keeps this page for opening offline, however it was loaded (#506).
void worker?.ready.then(r=>r.active?.postMessage({keepPage:true}));
const toWorker=(msg: object)=>worker?.controller?.postMessage(msg);
/// What waited for the connection goes now: on its return, and when the live stream comes back.
function flushOutbox(){ toWorker({flush:true}); }

View File

@@ -33,7 +33,7 @@ function setSrc(url: string): Promise<void>|null{
return ready.then(()=>{
// Its playlist and audio requests join the trace of the tap that played them (#192).
hls=new w.Hls({xhrSetup:(xhr: XMLHttpRequest)=>xhr.setRequestHeader('traceparent',traceparent())});
hls.on(w.Hls.Events.ERROR,(_: string,d: {fatal: boolean, type: string, details: string})=>{ if(d.fatal){ toast('Unable to play the DeadAir version. Try again, or turn DeadAir off for this show.',true);
hls.on(w.Hls.Events.ERROR,(_: string,d: {fatal: boolean, type: string, details: string})=>{ if(d.fatal){ toast('Unable to play the DeadAir version. Try again, or turn DeadAir off for this podcast.',true);
report('player_error',{msg:`hls.js: ${d.type} ${d.details}`,feed:player.feed,enclosure:player.enc}); } });
hls.loadSource(url); hls.attachMedia(audio);
});
@@ -158,7 +158,9 @@ function syncPlayButtons(){
for(const b of $$('#eps .ep [data-a=play]')) paint(b,on(b.closest<HTMLElement>('.ep')!.dataset.key),'Play');
for(const b of $$('#files [data-a=play][data-enc], #detail [data-a=play][data-enc]'))
paint(b,on(S.sel,Number(b.dataset.enc)),'Play');
const e=cur(); paint($<HTMLButtonElement>('#tbPlay'),!!e&&on(entryKey(e)),'Play the selected item');
// Dimmed, it keeps the reason it is dimmed (#507).
const e=cur(), tb=$<HTMLButtonElement>('#tbPlay');
if(!tb.disabled) paint(tb,!!e&&on(entryKey(e)),'Play the selected item');
}
for(const ev of ['play','pause','timeupdate']) audio.addEventListener(ev,syncListening);
window.addEventListener('beforeunload',savePos);
@@ -247,7 +249,7 @@ function paintDead(){
if(!f||b.hidden) return;
b.setAttribute('aria-pressed',String(!!f.deadair));
b.innerHTML=tile(f.deadair?'deadair-on':'deadair-off');
b.title=f.deadair?'DeadAir is cutting the dead air from this show':'DeadAir: cut the dead air from this show';
b.title=f.deadair?'DeadAir is cutting the dead air from this podcast':'DeadAir: cut the dead air from this podcast';
}
$<HTMLButtonElement>('#pdead').onclick=async()=>{
const f=S.feeds.find(x=>x.id===player.feed); if(!f) return;
@@ -256,8 +258,8 @@ $<HTMLButtonElement>('#pdead').onclick=async()=>{
catch(err){ toast(why(err),true); return; }
f.deadair=on; paintDead();
const switched=await switchVersion();
toast(!on?'DeadAir is off for this show':switched?'DeadAir is cutting the dead air from this show'
:'DeadAir is on for this show. Episodes lose their dead air a few minutes after they download.');
toast(!on?'DeadAir is off for this podcast':switched?'DeadAir is cutting the dead air from this podcast'
:'DeadAir is on for this podcast. Episodes lose their dead air a few minutes after they download.');
renderEntries();
};
/// Carries on at the same place in the other version of what is playing, once DeadAir has been
@@ -352,7 +354,7 @@ function keysModal(){
[g('a'),'All Subscriptions'],[g('d'),'Directory'],
[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'],
[k('/'),'Search items, Currently Listening or the Directory'],[k('r'),'Reload the lists'],[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'],

View File

@@ -37,7 +37,7 @@ function playlistFolder(list: HTMLElement, q: string){
/// The folder's page: every playlist, and New playlist.
function renderPlaylists(){
$('#count').textContent=`Playlists: ${plural(playlists.length,'playlist')}`;
$<HTMLButtonElement>('#tbRemove').disabled=true;
dim($<HTMLButtonElement>('#tbRemove'),NO_FEED,UNSUB);
syncTools(null);
const box=$('#content');
box.classList.add('plain');
@@ -63,7 +63,7 @@ function renderPlaylists(){
/// 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;
dim($<HTMLButtonElement>('#tbRemove'),NO_FEED,UNSUB);
syncTools(null);
const box=$('#content');
box.classList.add('plain');
@@ -96,13 +96,9 @@ async function renderPlaylist(p: Playlist){
$('#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);
// Not an onclick of its own over listenRow's: that one skipped the X and never marked it (#497).
list.appendChild(listenRow(e,'Mark played',async()=>{ try{ await setRead(e,true); }catch(err){ toast(why(err),true); } renderPlaylist(p); loadPlaylists(); },
()=>playFrom(rows,e)));
}
}
/// Plays an episode of a list that goes on to the list's next.

View File

@@ -74,7 +74,7 @@ function signalFolder(list: HTMLElement, q: string){
function renderSignals(){
const unread=S.signals.reduce((k,s)=>k+s.unread,0);
$('#count').textContent=`Signals: ${plural(S.signals.length,'signal')}, ${unread} unread`;
$<HTMLButtonElement>('#tbRemove').disabled=true;
dim($<HTMLButtonElement>('#tbRemove'),NO_FEED,UNSUB);
syncTools(null);
const box=$('#content');
box.classList.add('plain');
@@ -144,8 +144,8 @@ function signalModal(sg?: Signal){
<input type="text" id="sgname" value="${esc(sg?.name||'')}" placeholder="Formula 1"></div>
<div id="sgpicker" hidden>
<div class="inline">${searchBox('<input type="search" id="sgiconq" placeholder="Search icons: robot, car, music…" autocomplete="off">')}
<button type="button" class="dlink" id="sgjev" title="Pick an icon for me">Auto</button>
<button type="button" class="dlink" id="sgnoicon">Initials</button></div>
<button type="button" class="dlink" id="sgjev" title="Pick an icon for me">Pick for me</button>
<button type="button" class="dlink" id="sgnoicon">Use initials</button></div>
<div class="icongrid" id="sgicons" role="listbox" aria-label="Icons"></div>
</div></div>
<div class="field"><label for="sgkwin">Listen for</label>

View File

@@ -151,6 +151,13 @@ interface State {
sort: {col: string, dir: 'asc' | 'desc'};
}
/// One chapter of a file, `/api/enclosures/{id}/chapters` (chapters.rs Chapter, #477): its start
/// in seconds, in the clock of what plays.
interface Chapter {
start: number;
title: string;
}
/// One season of a podcast, `/api/feeds/{id}/seasons` (db.rs SeasonCount, #482). No season is
/// the episodes that name none.
interface SeasonCount {

View File

@@ -114,7 +114,7 @@ for(const b of $$('[data-icon]')) b.insertAdjacentHTML('afterbegin',ICON[b.datas
/// A search box with an x at its right end that clears it, shown once something is typed (#291).
const searchBox=(input: string, cls='')=>
`<span class="clearable ${cls}">${input}<button type="button" class="clearx" title="Clear" aria-label="Clear">${ICON.close}</button></span>`;
`<span class="clearable ${cls}">${input}<button type="button" class="clearx" title="Clear the search" aria-label="Clear the search">${ICON.close}</button></span>`;
// Every box's x, wherever it is drawn: cleared as if the typing were deleted, so the box's own input
// handler runs and its list comes back whole.
document.addEventListener('click',(e: MouseEvent)=>{
@@ -204,7 +204,7 @@ async function api(url: string, opts?: RequestInit): Promise<any>{
// whole 502 page (#219). A 500's words are the daemon's own workings, which its log already
// has; they are not something to show the person who pressed the button (#304).
const said=!/html/.test(r.headers.get('Content-Type')||'')&&await r.text().catch(()=>'');
throw new Error(r.status===500 ? 'iPX could not do that just now. Try again in a minute.'
throw new Error(r.status===500 ? 'Unable to 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'));
@@ -237,7 +237,7 @@ async function copyText(text: string,btn?: HTMLElement){
flash(true);
}catch(e){
flash(false);
toast('Could not copy automatically — select the URL and copy it manually',true);
toast('Unable to copy the link. Select it and copy it yourself.',true);
}
}
@@ -272,6 +272,10 @@ async function sendLink(title: string, url: string, btn?: HTMLElement){
toast('Link copied');
}
/// A button that cannot act now is dimmed in place, its tooltip saying why, and gets its usual
/// tooltip back when it can (#507): dimmed with its usual one, it looked broken.
function dim(b: HTMLButtonElement, why: string|null, usual: string){ b.disabled=!!why; b.title=why??usual; }
const NO_FEED='Open a feed to unsubscribe from it', UNSUB='Unsubscribe from this feed';
function toast(msg: string, bad?: boolean){
const t=document.createElement('div'), box=$('#toasts');
t.className='toast'+(bad?' bad':''); t.textContent=msg;
@@ -302,7 +306,19 @@ const ago = (t: number|null) => {
if(d<2592000) return Math.round(d/86400)+'d ago';
return new Date(t*1000).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'});
};
const dateOf = (t: number|null) => t?new Date(t*1000).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'}):'';
// One formatter: toLocaleDateString with options makes a new one each call, every row of a list.
const DATE_FMT = new Intl.DateTimeFormat(undefined,{month:'short',day:'numeric',year:'numeric'});
const dateOf = (t: number|null) => t?DATE_FMT.format(t*1000):'';
// A row's date is short (#508): the time today, the day this year, the month before that.
const TIME_FMT = new Intl.DateTimeFormat(undefined,{hour:'numeric',minute:'2-digit'});
const DAY_FMT = new Intl.DateTimeFormat(undefined,{month:'short',day:'numeric'});
const MONTH_FMT = new Intl.DateTimeFormat(undefined,{month:'short',year:'numeric'});
const rowDate = (t: number|null, now=new Date()) => {
if(!t) return '';
const d=new Date(t*1000);
if(d.toDateString()===now.toDateString()) return TIME_FMT.format(d);
return (d.getFullYear()===now.getFullYear()?DAY_FMT:MONTH_FMT).format(d);
};
// A podcast episode is tens of MB, an article's image a few KB: whole MB made the small ones "0 MB".
const mb = (n: number|null) => !n?'' : n<1048576?Math.max(1,Math.round(n/1024))+' KB'
: n<1073741824?Math.round(n/1048576)+' MB' : (n/1073741824).toFixed(1)+' GB';

View File

@@ -53,8 +53,11 @@ sw.addEventListener('fetch', e => {
});
sw.addEventListener('message', e => {
const m = e.data as {flush?: boolean, pictures?: string[]} | null;
const m = e.data as {flush?: boolean, pictures?: string[], keepPage?: boolean} | null;
if (m?.flush) e.waitUntil(flush());
// Asked by the page each time it loads, since what loaded it may not have come through here:
// the iOS app's own load of the page never did, so the worker had no page to open offline (#506).
if (m?.keepPage) e.waitUntil(fetch('/', { credentials: 'same-origin', redirect: 'manual' }).then(keepPage, () => {}));
if (Array.isArray(m?.pictures)) e.waitUntil(keepPictures(m.pictures));
});
@@ -63,13 +66,17 @@ sw.addEventListener('message', e => {
async function page(req: Request): Promise<Response> {
try {
const r = await fetch(req);
if (r.ok && r.type === 'basic' && new URL(req.url).pathname === '/') (await caches.open(PAGE)).put('/', r.clone());
if (new URL(req.url).pathname === '/') await keepPage(r);
return r;
} catch {
return (await caches.match('/', { cacheName: PAGE })) || Response.error();
}
}
async function keepPage(r: Response) {
if (r.ok && r.type === 'basic') await (await caches.open(PAGE)).put('/', r.clone());
}
async function hashed(req: Request, client: string): Promise<Response> {
const kept = await caches.match(req, { cacheName: PAGE });
if (kept) return kept;