Compare commits

..
Author SHA1 Message Date
sanapachandClaude Opus 5.5 3e60195352 VFD panel: live signal path output row
The lower row of the signal path schematic was decoration (TONE, AMP,
SPEAKERS A). It now shows what leaves the player, read right to left
after the volume stage: the sample rate, STEREO or MONO, and the output
peak after the volume (the analyzer measures before rodio's gain, which
is volume cubed), refreshed four times a second and red near full scale.
The compact strip line and the transport STEREO lamp use the same values.

Comparing the L and R levels cannot tell stereo from mono: a wide mix
with balanced channels has equal levels. The analyzer therefore also
accumulates the side signal (L - R) / 2 per window, exposed as
level_side, and the meter decides stereo or mono on loud raw windows
(side within 30 dB of the louder channel), before any ballistics, and
keeps the decision through silence; scripts get it as channel_mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 22:12:41 +02:00
sanapachandClaude Opus 5.5 5a00a1c8e8 VFD panel: display modes with a hardware-style switch
DISPLAY_MODE() replaces LAYOUT() with "full", "spectrum", "minimal" and
"deck" ("auto" follows Shift+M; the old names still work). When the
layout on screen changes, the time and L/R meters stay lit while the
other sections go dark and light up one after another with a short
overshoot, like a display switching modes in hardware. A pinned mode or
a fallback to the same layout only flashes the mode lamps.

The analyzer's display range follows the music: its top rises with the
loudest band and falls 4 dB/s within -26..-6 dBFS, never reaching below
the analyzer floor, so silence stays dark. Spectrum mode caps the
analyzer at 18 rows and centres the panel; minimal mode is at most 132
columns wide and centred. Deck mode adds AMS, NR [B], AUTO REVERSE and
REW / FF lamps and a tape counter that races during a seek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:38:26 +02:00
sanapachandClaude Opus 5.5 d1c89511ed Finish the VFD panel: 14-segment transport word and display behaviour polish
PLAY / PAUSE / STOP are drawn as full 14-segment letters (box-drawing
diagonals, a split middle bar, centre strokes) with faint unlit segments,
so the word no longer mixes segment and dot-matrix styles. Unlit lamps are
brighter and keep their level at night; the balance marker is two thin
segments over a bright centre mark; analyzer peak marks hold, then fall with
growing speed; and the lower-right block is one digital module with captions
and equally tall digits for track and volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:14:12 +02:00
sanapachandClaude Opus 5.5 2288392825 Switch visualizer display modes with Shift+M and polish the VFD panel
A new CycleVisualizerMode action (Shift+M by default) steps the fullscreen
visualizer's display mode; the choice is saved in visualizations.toml and
reaches scripts as input.mode. The VFD panel uses it for its classic, focus,
minimal and tape modes, with a row of mode lamps after each change and a
step-down when a mode does not fit the window.

Polish: quieter signal-path lines with lit boxes and nodes, two-cell peak
marks and a mid-level red zone in the level meter, A and Y in a 14-segment
style with thin diagonals, an analyzer tint from warm amber in the bass to
light yellow in the treble, and bar inertia that is separate from peak hold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 17:49:38 +02:00
sanapachandClaude Opus 5.5 204d17f14c Give the VFD panel glow levels, a measuring module and a signal schematic
The analyzer shows three levels of glow (a dimmer foot, the body, a nearly
white top segment), faint unlit segments and a light peak-hold mark, on a
nonlinear scale; loud columns glow brighter on their own instead of the
whole panel brightening. The peak frequency becomes one measuring module
(caption, held value, rule, sample rate) with a real hold. The signal path
is a schematic of framed boxes on a bus with nodes, a wire to the lower row,
a pulse that now and then runs along it and a SIGNAL PATH state label.
PLAY / PAUSE / STOP use segment letters with centre strokes, mode lamps get
indicator bars, paused colours fade into unlit phosphor, and a new source
goes dark and relights with its value. LAYOUT() chooses between the full
panel, a spectrum focus and a tape deck composition, or picks by size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:04:07 +02:00
sanapachandClaude Opus 5.5 73a8e94c78 Even out the VFD panel's thin lines and clean up its routing
Verticals of the segment digits now use quarter blocks, as thick as the
eighth-block horizontals, and the mesh behind them is gone; unlit segments
are fainter so lit digits read clearly. The routing display uses label
plates without sides, and its wire runs along cell edges from the volume
plate's corner straight down to the tone plate's corner, so it joins
cleanly. The bass / treble fans are single thin strokes instead of braille
lines, and the braille amplifier and speakers are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:48:48 +02:00
sanapachandClaude Opus 5.5 61027d22ca Add VFD panel effects and a local-time clock for visualizations
The VFD panel gains a dot-matrix title line (5x7 Latin and Cyrillic in
braille, smooth scrolling), palettes, optional needle VU meters, a night
dimmer, a filament "breath" and loudness brightening, uneven digit
brightness, a mesh behind the big digits, a tape counter, LOUDNESS / MUTE /
SEARCH lamps, a burst of static on track and source changes, and a standby
clock with a sweep at the top of every minute.

The visualization clock now shows local time (it showed UTC), and scripts
get clock_hour, clock_minute, clock_second and clock_millis from the same
reading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:28:59 +02:00
sanapachandClaude Opus 5.5 8606f08a36 Add visualization protocol v3 and the VFD panel preset
Scripts now receive the spectrum, channel levels, sample rate and track,
queue and transport details; may return #{ commands, state } to keep state
between frames (with dt and frame, reset on reload and on opening); can draw
thin braille dots and lines (clipped to the area); and can set bold, dim,
italic, underline or reversed on any command. v2 scripts keep working.

The bundled "VFD panel" preset uses all of it for a vacuum-fluorescent hi-fi
front panel in a thin style: segment counter, peak level meter, 25-band
analyzer with peak hold, tone fans, routing diagram and transport lamps,
with a power-on segment test, a counter search on track changes and an
OVER lamp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:48:13 +02:00
sanapachandClaude Opus 5.5 aabca327b2 Measure a third-octave spectrum and channel levels for visualizations
The analyzer now keeps a full-rate mono PCM history and per-window left/right
RMS and peaks. The FFT and all ballistics run on the reader side when a
snapshot is taken, so the audio callback only appends samples: 31 bands with
exact base-2 edges that partition the FFT bins, an ~85 ms window that follows
the sample rate, time-based attack/fall/peak hold, and silence only after the
PCM counter has stalled for longer than a few device callbacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:48:13 +02:00
Aleksandr Bogomiakov 038f0979af Release Furumi 0.5.0 with published FRID podcast crates 2026-11-20 14:17:49 +00:00
ab 81f422b244 Merge pull request 'Публичные подкасты в TUI: «Поделиться», поиск с типом podcast и «Подписаться» из карточки (MR-T3)' (#4) from sanapach/furumi-tui:podcasts/discovery into federation 2026-11-20 14:11:11 +00:00
ab 7659313dc2 Merge pull request 'Подкасты в TUI на контракте FRID: подписки, воспроизведение, прогресс, синхронизация устройств v4 (MR-T2)' (#3) from sanapach/furumi-tui:podcasts/tui into federation 2026-11-20 14:11:09 +00:00
ab 44d0bb5abe Merge pull request 'Порядок вкладок 1–6 с Podcasts на 4 и миграция keymap (MR-T1)' (#2) from sanapach/furumi-tui:podcasts/tab-order into federation 2026-11-20 14:11:00 +00:00
sanapachandClaude Opus 5.5 59d6a1fe24 Point frid deps at the fork branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:15 +02:00
sanapachandClaude Opus 5.5 409188b9a9 Publish podcast cards only after the first device sync
A device restarted with a "share" decision that another device of its
group revoked meanwhile sent that card again: the first reconciler pass
called sync_shares from the stale registers before device sync ran.
Until DeviceSync says the registers are current (a sync exchange with a
v4 device of the group after the store was attached, or no such device
to wait for), passes now only unpublish cards the local registers no
longer share and never call sync_shares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 ce5697ce1d Document held-back revocation and quitting during a revocation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 adfe809a40 Wait for in-flight revocations and track them with federation off
Share-off and unsubscribe now take a revocation ticket on the UI thread
before the write starts and ask for the immediate pass from the blocking
task once the write succeeded, so quitting right after Shift+F (before the
write's event was handled) still waits for the tombstone. With the
federation off or not started yet, a podcast that was shared counts as
possibly not revoked: the reconciler keeps it in the Off reports until the
overlay runs, the side panel says the card may not be revoked yet, and the
quit-time flush logs a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 d6962eba47 Keep public artwork whose path only looks random
Public podcast hosts and CDNs name artwork and pages by UUIDs and
content hashes, so the random-looking path rule dropped the artwork of
most public podcasts. Artwork and links now follow the query and host
rules only; a member feed's artwork is still left out with its feed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 43e0696531 Drop share confirmations whose decision was not written
A confirmation is recorded as pending before the share decision is
written and covers the next newer decision. When the write failed (the
podcast was unsubscribed by a sync meanwhile, a database error), the
pending entry stayed and later covered a decision taken on another
device that this user never saw. Put the previous entry back on failure,
and drop pending entries left in the file by a call that never finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 405f8ae6d3 Hold back unconfirmed private-looking cards before syncing
FRID's sync_shares keeps publishing a card whose feed URLs this device
already publishes, even without the privacy confirmation. A device that
missed an intermediate share-off would go on publishing a private-looking
URL nobody confirmed for the new decision. share_plan now leaves such a
podcast out of the states, so sync_shares revokes the old card, and
reports it as held back itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 3ddf7995e8 Document prompt revocation and moved-feed subscriptions
README, ARCHITECTURE, CHANGELOG and AGENTS describe the immediate
revocation and quit-time wait, decision-bound confirmations, the card
URL filter, devices that left the group, the separate bounded podcast
search, and which direction of a moved feed the search mark covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 17ed8bfcd4 Scroll the podcast card exactly to its end
The card and the share dialog measure their word-wrapped height the
way it is rendered (ratatui's rendered-line-info), and scroll keys stop
at the last line instead of running past it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 fd6827126f Recognize subscriptions under a feed's newer address
Subscribing to an older address whose feed announces a newer one this
device already follows (itunes:new-feed-url without a redirect) reports
the existing subscription instead of adding a second one, and a card
whose feed moved to a followed address reads «Уже подписан» once its
episodes were read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 744d56e06b Leave private-looking artwork and links out of cards
The share dialog shows the feed URLs only, so a card no longer carries
an artwork or web page URL that looks like it holds an access key, and
a member feed's card carries neither.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 7add66920d Bind share confirmations to the share decision
A privacy confirmation now covers the share decision it was given for,
not only the URLs: sharing turned off, or turned on again after a
revocation, on any trusted device drops it, so this device asks again
before it publishes a feed URL that looks private.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 1137670229 Revoke podcast cards promptly and report unrevoked ones
Turning sharing off or unsubscribing runs a reconciler pass right away,
and quitting waits up to 4 s for it. The Podcasts tab tells a private
podcast whose card from this device is still live, failed revocations
are reported without ids, the overlay peer count stays current, and the
reconciler loop is tested against a loopback overlay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 a51f5552e3 Search public podcasts apart from the music search
Federated music results no longer wait for the discovery overlay: the
podcast search runs as its own task, bounded at 15 s including the
overlay's bootstrap, and arrives as its own event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 d38144fe45 Document finding public podcasts and bump to 0.5.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 160237b5a5 Test subscribing from a public podcast card
Cover the merge order of podcast hits, alias resolution, the feed
preview, subscribing from a card (same podcast id as by URL, never a
claimed URL, forged ids refused) and an end-to-end run: a stranger's
node finds a shared card over loopback overlay nodes, subscribes
privately, refreshes from a local feed server and keeps the
subscription after the publisher stops sharing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 e038f282c2 Find public podcasts in search and subscribe from their cards
Federated search also queries the podcast discovery overlay and lists
the podcast entries of merge_search_results after the music results,
marked [podcast], with the publishing devices or "subscribed" (also
through a feed alias resolved off the UI thread). Enter opens the card:
the publishers' claims, the origin feed URL, unverified moved-feed
claims, an optional episode preview read from the feed itself, and
«Подписаться», which subscribes privately with the origin URL only.
«Уже подписан» opens the podcast in the Podcasts tab instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 25a9f2b0ec Subscribe to a parsed feed URL
Split refresh::subscribe into input parsing and subscribe_url, so a
public card's origin URL can be subscribed to exactly as given, and let
the feed parser be reused for previews.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 6d225531a5 Document sharing podcasts in the federation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 8f4e58d8af Add a share toggle to the Podcasts tab
Shift+F in the podcasts context shares the selected or opened podcast
through PodcastStore::set_shared (a synced decision) or makes it private
again. A feed URL that looks private is confirmed first in a dialog that
lists the warnings in Russian. The reconciler runs after share and
unsubscribe actions, received podcast operations, feed refreshes, overlay
restarts and periodically; the list and side panel show the shared and
published state and publication errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 8c90035fa2 Reconcile own podcast publications with the share registers
podcasts::publication builds one PodcastShareState per subscription (cards
from the catalog for shared podcasts only, the device-local privacy
confirmation) and hands them to PodcastDht::sync_shares, which publishes
what is shared and tombstones the rest. Without a readable store every own
card is revoked. Privacy confirmations live in a 0600 JSON file next to
podcasts.sqlite3 and cover exactly the confirmed URLs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 c453b0a52f Run the podcast discovery overlay in the federation node
The node serves FRID's podcast_dht overlay next to the similarity overlay
(cache federation/podcast-dht.sqlite3), runs its maintenance, hands peer
capability manifests to note_peer_capabilities and advertises podcast_dht
only while the overlay runs. A cache that cannot be opened is logged and
only turns discovery off. The running overlay is exposed through a watch
channel for the publication reconciler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
42 changed files with 9875 additions and 175 deletions

No files matched your search

+15 -2
View File
@@ -65,8 +65,21 @@ update it only when dependencies change.
stream reader (HTTP Range, bounded buffer) and the ordered progress writer;
podcast identity, merge rules and the SQLite store come from FRID
(`music_dht::podcast`, `furumi_library::podcasts`) and must not be
re-derived here. Queue items are identified by `state::track_key` /
`TrackItem::key`, never by numeric id (every episode has the same sentinel
re-derived here. Public podcast cards are published only through
`podcasts::publication` (`PodcastDht::sync_shares` over the merged
registers): never publish a podcast directly, never log feed URLs or ids of
podcasts that are not shared, never put progress, history, counters or
device names into a card. A local share-off or unsubscribe asks for an
immediate pass (`Reconciler::revoke_now`), which quitting waits for, and
privacy confirmations change only through `publication::set_shared` /
`ShareConfirmations` (bound to the share decision, never synced). Nothing
is published before `DeviceSync::podcast_registers_current` (a restarted
device may hold a revoked share decision); passes before it only revoke.
Public cards found by search are publisher claims:
subscribe and preview only through `podcasts::discovery`, which uses the
card's origin URL (`PodcastSearchHit::feed_url`), never a claimed URL, and
never stores card metadata. Queue items are identified by `state::track_key`
/ `TrackItem::key`, never by numeric id (every episode has the same sentinel
id); music-only code must skip `TrackItem::is_podcast()` items.
- `src/devices.rs` owns trusted-device replication, membership, and playback
coordination. Its wire types are the shared `music_dht::device_sync`
+97 -4
View File
@@ -398,6 +398,63 @@ The TUI owns what the contract leaves to clients:
one within the completion window, completes the episode and moves the
queue on; otherwise the last seen position is saved and playback stops on
the episode (`playback::played_to_the_end`).
- **Public discovery.** The federation node runs FRID's signed podcast
overlay (`music_dht::podcast_dht`, ALPN `furumi-fd/podcast-dht/1`, cache
`federation/podcast-dht.sqlite3`) next to the similarity overlay: it
serves the overlay, bootstraps, republishes and expires records, hands
every peer capability manifest to `note_peer_capabilities`, and advertises
`podcast_dht` in its own manifest only while the overlay runs. A cache
that cannot be opened is logged and only turns discovery off. What this
device publishes is decided by `podcasts::publication`: after local share
and unsubscribe actions (at once: `Reconciler::revoke_now`), received
podcast operations and feed refreshes (debounced 1 s), every overlay
(re)start and every 5 minutes it builds one
`PodcastShareState` per subscription (merged registers, a card from the
catalog for shared podcasts only, the local privacy confirmation) and
calls the declarative `PodcastDht::sync_shares`, which publishes what is
shared and tombstones every other own card. The share decision is the
synced `podcast_share_set` register, so share-off or unsubscribe on any
trusted device revokes every device's card and a stale device cannot
republish: until `DeviceSync::podcast_registers_current` turns true (a
sync exchange applied with a v4 device of the group after the podcast
store was attached, or no reachable v4 device in the group) a pass only
unpublishes the own cards its registers no longer share
(`publication::revoke_unshared`) and never calls `sync_shares`, whose
first call would re-send the cards FRID withholds from an earlier
session. Publication runs from each device's own identity. Privacy
confirmations of feed URLs that look private are device-local
(`podcast-share-confirmations.json`, mode 0600) and bound to the exact
URLs and to the share decision (the share register's operation): a newer
decision on any device drops them. Cards leave out artwork and web links
that look private, and both for a private-looking feed. Without a
readable podcast store this device revokes all its own cards. The report
of each pass lists the private podcasts whose own card is still live
(`unrevoked`: pending, failed or federation off) for the side panel; the
overlay peer count is refreshed every 10 s between passes. Before the
node stops on quit, `Reconciler::flush` waits up to 4 s for a revocation
requested just before. Logs carry counts only.
- **Finding and subscribing.** `Federation::search_podcasts`
(`podcasts::discovery::search`) runs `PodcastDht::search` as its own task,
bounded at 15 s including the overlay's bootstrap, apart from the music
search (`Federation::search`, unchanged), and delivers
`AppEvent::FedPodcastsLoaded` for the same search sequence, so music
results never wait for the overlay. The hits keep the podcast entries of
`merge_search_results` (exact titles first) as
`podcasts::discovery::PodcastHit`s. Off the UI thread each hit's origin
URL is resolved with
`PodcastStore::resolve_podcast_id`, and the "subscribed" mark compares
that id and the card's id with the subscribed podcasts, so a feed alias
counts. A card is a publisher's claim: only `PodcastSearchHit::feed_url`
(the origin URL the id is hashed from) is ever fetched, both for the
episode preview (`discovery::preview`, nothing stored) and for
«Подписаться» (`discovery::subscribe_from_hit` → `refresh::subscribe_url`),
which refuses a hit whose id does not match its URL and stores only what
the feed says. Claimed moved-feed URLs are displayed, never fetched or
recorded as aliases. The new subscription is private. Subscribing to an
address whose feed announces (`itunes:new-feed-url`) a newer one this
device already follows reports that subscription instead of adding a
second one, and the preview (`discovery::preview_for`) resolves the
address the feed moved to, so the card reads «Уже подписан» then.
- **Progress.** `podcasts::progress` runs one writer thread so every
progress write of this device is ordered. The app tick follows the
position and actual listening time and sends: an explicit start (or
@@ -424,6 +481,9 @@ rodio source
│
v
audio analyzer ──> normalized features + scope samples
│ (PCM history, channel levels)
v
display meter ───> third-octave spectrum, L/R levels, peak hold
│
v
Rhai render(input)
@@ -442,6 +502,36 @@ script implements `render(input)` and returns declarative commands such as
clear, cell, line, rectangle, trace, and text. Scripts never receive the
ratatui frame or audio engine directly.
Protocol v3 adds what front-panel displays need: a third-octave spectrum
(31 bands, 20 Hz to 20 kHz, nominal ISO labels with exact base-2 edges that
partition the FFT bins) with per-band peak hold, left/right RMS and held
sample peaks, the RMS of the side signal (L - R) / 2 and a
stereo/mono decision made on loud windows, the analyzed sample rate, and track, queue and transport
details (format, bit depth, bitrate, track number, queue position, repeat,
shuffle, source), and the local wall-clock time. The audio thread only appends mono samples to a lock-free
ring and accumulates per-window channel levels; the FFT (an ~85 ms window
whose length follows the sample rate) and all ballistics run when the UI
takes a snapshot, under a mutex the audio thread never touches. Ballistics
are time-based (fast attack, steady fall, hold then fall): they advance with
the clock rather than per snapshot. Audio arrives in device-callback bursts,
so a snapshot that sees no new samples reuses the last measurement; only when
the PCM write counter stays still for longer than a few callbacks (pause,
stop) does the meter fall to the floor instead of freezing. In the control
role, and briefly when a track starts, the host passes an empty analysis, so
the meter reads zero. Meter values report the decoded signal on a fixed dBFS
scale and are therefore not scaled by the output volume, unlike the v2
energy features. Scripts choose their own display range within that scale.
v3 also lets a script keep state: `render` may return
`#{ commands, state }`, and the host passes `state` back with `dt` and a frame
counter on the next frame. State lives in the host's script runtime, is reset
whenever the script is recompiled or the visualizer is opened, and is subject
to the same sandbox size limits as any other value. Thin drawing comes from braille `dots` and `line`
commands in a 2 x 4 dot grid per cell (dots merge with braille already in the
cell; lines are clipped to the area first, so far endpoints cost nothing) and
from optional bold/dim/italic/underline/reversed attributes, which each
command sets for its cells rather than adding to what was drawn before.
This command boundary is intentional:
- scripts remain independent of Rust UI internals;
@@ -481,8 +571,8 @@ is not a plugin mechanism for accessing the library, network, or player
controls.
Fullscreen execution currently happens synchronously during UI drawing, with a fresh
Rhai scope for each frame; scripts should derive motion from time and the
already-smoothed audio features rather than rely on retained mutable state.
Rhai scope for each frame; retained state is limited to the explicit `state`
value described above, and motion should still be derived from time and `dt`.
The 50 ms animation timer gives a nominal 20 FPS cadence (other events can
also trigger redraws). Operation limits are not wall-clock deadlines. The
host also checks the script modification time during drawing, so slow script
@@ -541,6 +631,8 @@ Furumi stores different kinds of state according to their lifetime:
| --- | --- | --- |
| Library, playlists, likes, history | SQLite | Durable local source of truth |
| Podcast subscriptions, episodes, progress | SQLite (`podcasts.sqlite3`, FRID store) | Durable personal state (synced with trusted devices) and a refreshable episode catalog |
| Podcast share confirmations | JSON next to `podcasts.sqlite3` | Device-local consent to publish feed URLs that look private |
| Public podcast cards (own and replicas) | SQLite (`federation/podcast-dht.sqlite3`) | Discovery overlay cache; replaceable |
| Device operation log and replicas | SQLite | Offline synchronization |
| Versioned track embeddings | SQLite | Durable, locally rebuildable similarity data |
| Federation catalog cache | SQLite/cache | Faster network browsing |
@@ -580,8 +672,9 @@ The source tree follows the architectural responsibilities:
- `federation/` owns DHT-facing search, peer catalogs, and audio exchange;
- `podcasts/` owns feed HTTP (conditional requests, redirects, limits),
refresh scheduling policy, the episode stream reader and the progress
writer; the podcast model, identity, merge rules and SQLite store come
from FRID;
writer, the publication of shared podcasts and subscribing from public
cards; the podcast model,
identity, merge rules, SQLite store and discovery overlay come from FRID;
- `devices.rs` owns trusted-device replication and playback coordination;
- `app/` owns state transitions and runtime orchestration;
- `ui/` renders the TUI;
+94 -2
View File
@@ -7,10 +7,96 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.4.0] - unreleased
### Added
- "VFD panel" visualization: a vacuum-fluorescent hi-fi front panel with
thin segment digits, a stereo peak level meter (bars or needle VU meters),
a 25-band analyzer with three levels of glow, a nonlinear scale and peak
hold, a peak frequency readout with hold, tone fans, a signal path
schematic with a travelling pulse (source, format, volume, sample rate,
stereo or mono, and the output level in dBFS), the transport word in segment letters,
mode lamps (REPEAT, SHUFFLE, source, LOUDNESS, MUTE, SEARCH, OVER), a tape
counter and a dot-matrix title line (Latin and Cyrillic). Effects: a
power-on segment test, a counter "search" on track changes, static on
track and source changes, a source block that relights with its new
value, colours that fade into unlit phosphor on pause, a night dimmer, a
slow filament "breath", slightly uneven digit brightness and a standby
clock when nothing is loaded. Display modes "full", "spectrum",
"minimal" and "deck" switch with Shift+M or can be pinned with
`DISPLAY_MODE()` at the top of the script, like the palettes ("classic",
"green", "amber", "ice"); a mode that does not fit the window steps down.
A switch looks like hardware: the time and L/R meters stay lit, the other
sections go dark and light up one by one, and a row of mode lamps shows
the choice for a moment. The analyzer's display range follows the
loudness of the music (the measurements stay absolute), and deck mode has
AMS, NR, AUTO REVERSE and REW/FF lamps with a counter that races during a
seek. Bars settle with a little inertia, the analyzer's
tint runs from warm amber in the bass to light yellow in the treble, peak
marks fall with a little gravity after their hold, and the transport word
uses 14-segment letters with faint unlit segments.
- `Shift+M` in the fullscreen visualizer switches its display mode; the
choice is saved in `visualizations.toml`.
- Visualization protocol v3: a real third-octave spectrum (31 bands) with
peak hold, left/right RMS and held peaks, the side-signal level
(`level_side`, the floor for mono) and `channel_mode` ("stereo" or
"mono"), the sample rate, and track,
queue and transport details in the script input; `render` may return
`#{ commands, state }` to keep state between frames (with `dt` and
`frame`); new braille `dots` and `line` commands for thin drawing; bold,
dim, italic, underline and reversed attributes on any command. v2 scripts
keep working unchanged. Scripts also get the local time as
`clock_hour`, `clock_minute`, `clock_second` and `clock_millis`, and the
display mode as `mode`, a counter each script takes modulo its own number
of modes.
### Fixed
- The visualization clock shows local time instead of UTC.
## [0.5.0] - 2026-11-20
### Added
- Sharing a podcast in the federation (`Shift+F` in the `podcasts` context,
off by default): the synced share decision makes each device publish a
signed public card of the podcast in the FRID discovery overlay
(`podcast_dht`, advertised in the capability manifest); share-off and
unsubscribe revoke it with a tombstone. Feed URLs that look private are
published only after a confirmation on that device. The list and side
panel show whether a podcast is shared and whether this device publishes
it.
- Turning sharing off or unsubscribing revokes this device's card at once,
and quitting waits up to 4 s for that (also for a change still being
saved); the side panel says when a private podcast's card is not revoked
yet (pending or failed) or may not be (federation off: a card of an
earlier session cannot be ruled out). A privacy confirmation covers one
share decision: turning sharing off (or on again after that) on any
trusted device asks again, and until then this device holds the podcast
back and revokes the card it published for the earlier decision. A
confirmation whose decision could not be saved is dropped. Cards leave out
artwork and web links with an access key in the query or a member-feed
host (random-looking path parts of public CDNs are fine), and both for a
feed whose URL looks private.
- A device with other devices in its group publishes its cards only after
it synced with one of them since it started (or once none is left that
syncs podcasts), so a device that was closed while sharing was turned off
elsewhere does not send that card again; until then it only revokes, and
the side panel says it waits for a sync.
- Search (`/`, with the federation running) also finds public podcast cards.
They are listed after the music results under "Podcasts · public cards" with
a `[podcast]` marker, the number of publishing devices, and "✓ subscribed"
when this device is subscribed (also through a feed alias). The podcast
search runs apart from the federated music search (bounded at 15 s), so
music results never wait for it; local-only search is unchanged.
- Enter on a podcast hit opens its card: title, author, categories,
description, episode count, newest episode, publishing devices, feed URL
and unverified moved-feed claims. `e` reads the seasons and episodes from
the feed without subscribing. «Подписаться» (Enter) subscribes privately
with the card's origin feed URL, so the podcast id is the card's, and
reads everything from the feed itself; «Уже подписан» opens the podcast
in the Podcasts tab instead, also when this device follows the feed under
the newer address it moved to (known once the feed was read), and
subscribing to such an older address adds no second subscription.
- A Podcasts tab on `4`: subscribe to RSS/Atom feeds by URL, browse
podcast → seasons → episodes with saved position, played state, duration and
date, search episodes, filter by listening state, change the order, mark
@@ -51,7 +137,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- `music-dht` 0.6.0 and `furumi-library` 0.3.0.
- `furumi-tui` 0.5.0.
- Use published `music-dht` 0.6.0 and `furumi-library` 0.3.0 from crates.io;
remove the temporary FRID fork patches.
- Self-update and release download links use the canonical
`Furumi-stack/furumi-tui` GitHub repository.
- Queue items are keyed by their source: podcast episodes by episode id,
library rows as `lib:<id>` instead of `local:<id>`. Likes, playlists,
music history, similarity, share links and metadata edits skip episodes.
@@ -89,6 +179,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Isolate log privacy and identity-lock lifecycle tests from process-wide
state and descriptor inheritance in parallel tests.
- The protocol version stored for another device came from this build's own
constant (on profile announcements and accepted pairings), not from the
device. Versions now come from the device's own reports; relayed profiles
Generated
+18 -14
View File
@@ -1143,7 +1143,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54e03a951783e8b327515db3f2a2fd0e3bed362a96b066f341ce66ed49b4ead"
dependencies = [
"data-encoding",
"syn 3.0.4",
"syn 1.0.109",
]
[[package]]
@@ -1269,7 +1269,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1455,7 +1455,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1559,7 +1559,8 @@ dependencies = [
[[package]]
name = "federation-net"
version = "0.3.1"
source = "git+https://gt.hexor.cy/Sanapach/frid.git?branch=podcasts%2Fstore#d2530dca6ca0905cab2704615b89c8b89c70c7cf"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01e5c2e6e5af020dc202d4924125ef57719aa21f8d2567e2d943914386bc8980"
dependencies = [
"blake3",
"data-encoding",
@@ -1698,7 +1699,8 @@ dependencies = [
[[package]]
name = "furumi-library"
version = "0.3.0"
source = "git+https://gt.hexor.cy/Sanapach/frid.git?branch=podcasts%2Fstore#d2530dca6ca0905cab2704615b89c8b89c70c7cf"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e7eb785cc6ab5b59db8ef74ffa05d798afde45fbd86da08aecf356432a52d10"
dependencies = [
"anyhow",
"blake3",
@@ -1713,11 +1715,12 @@ dependencies = [
[[package]]
name = "furumi_tui"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"anyhow",
"base64",
"blake3",
"chrono",
"core-foundation 0.10.1",
"crokey",
"crossterm",
@@ -3238,7 +3241,8 @@ dependencies = [
[[package]]
name = "music-dht"
version = "0.6.0"
source = "git+https://gt.hexor.cy/Sanapach/frid.git?branch=podcasts%2Fstore#d2530dca6ca0905cab2704615b89c8b89c70c7cf"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce81f361952228654c28a46e41555f2c3d1520bf8c6c76562e7a53f70dd38e1"
dependencies = [
"async-trait",
"blake3",
@@ -3654,7 +3658,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -3739,7 +3743,7 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
dependencies = [
"proc-macro-crate 3.5.0",
"proc-macro-crate 1.3.1",
"proc-macro2",
"quote",
"syn 2.0.119",
@@ -4537,7 +4541,7 @@ dependencies = [
"once_cell",
"socket2 0.6.5",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5053,7 +5057,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5111,7 +5115,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5925,7 +5929,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.4",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -7029,7 +7033,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
+4 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "furumi_tui"
version = "0.4.0"
version = "0.5.0"
edition = "2024"
rust-version = "1.97"
description = "A federated P2P player for personal music libraries"
@@ -23,6 +23,8 @@ object = { version = "0.36", default-features = false, features = ["read", "std"
anyhow = "1.0.102"
blake3 = "1"
# Local wall-clock time for visualizations (the clock and its hour/minute).
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
crokey = "1.4.0"
crossterm = { version = "0.29.0", features = ["event-stream"] }
directories = "6.0.0"
@@ -33,7 +35,7 @@ lofty = "0.22"
# P2P federation: library index in a shared DHT + audio streaming between
# peers (same protocol as furumi-fd).
music-dht = { version = "0.6.0", features = ["podcast-feed"] }
ratatui = "0.30.1"
ratatui = { version = "0.30.1", features = ["unstable-rendered-line-info"] }
reqwest = { version = "0.12.28", default-features = false, features = ["rustls-tls", "stream", "blocking"] }
rhai = { version = "1", features = ["sync"] }
rodio = { version = "0.22.2", default-features = false, features = ["playback", "mp3", "flac", "vorbis", "wav", "symphonia-aac", "symphonia-isomp4", "symphonia-alac"] }
@@ -57,9 +59,6 @@ unicode-width = "0.2.2"
# souvlaki 0.8.3 still depends on the unmaintained block 0.1.6. Keep its API
# intact while using an opaque inhabited FFI type accepted by current Rust.
block = { path = "vendor/block" }
# Unpublished frid (MR-F1, MR-F2); remove once music-dht 0.6.0 and furumi-library 0.3.0 are on crates.io.
music-dht = { git = "https://gt.hexor.cy/Sanapach/frid.git", branch = "podcasts/store" }
furumi-library = { git = "https://gt.hexor.cy/Sanapach/frid.git", branch = "podcasts/store" }
[target.'cfg(target_os="macos")'.dependencies]
core-foundation = "0.10.1"
+100 -6
View File
@@ -67,7 +67,10 @@ context-aware bindings, and user-defined rebinding through TOML. Built-in
audio visualizations, OS media controls, gapless queue playback, and local
library management are included. Visualizations are runtime-loadable Rhai
scripts executed in a resource-limited sandbox, so they can be added or edited
without rebuilding the player.
without rebuilding the player. The bundled "VFD panel" preset draws a hi-fi
front panel from a real third-octave spectrum and stereo level meter; scripts
can use the same spectrum, levels, track details, thin braille lines and
per-frame state.
Optional similarity search calculates versioned embeddings for local tracks
in the background and keeps them in SQLite. It works offline; after a separate
@@ -98,7 +101,7 @@ furumi
### Linux, Windows, and other platforms
Download a prebuilt archive from the
[GitHub releases](https://github.com/house-of-vanity/furumi_tui/releases), or
[GitHub releases](https://github.com/Furumi-stack/furumi-tui/releases), or
build Furumi from source with Rust 1.97 or newer:
The repository selects the stable Rust toolchain. With rustup, run
@@ -208,6 +211,10 @@ never imported into the music library or offered to other peers.
- `Shift+U` (or `Shift+D`) unsubscribes after a confirmation. Listening
progress and history are kept, so subscribing again continues where you
left off.
- `Shift+F` shares the selected (or opened) podcast in the federation, or
makes it private again. The list marks shared podcasts with `shared`, and
the side panel says whether this device publishes the card (see
"Sharing a podcast" below).
Episodes play in the same queue as music:
@@ -251,8 +258,7 @@ Podcasts and your connected devices:
history are personal. They are synchronized only between your trusted
devices (Connected Devices), never published to the federation: no DHT
record, public catalog or search result contains them. Publishing a
podcast for discovery is a separate, explicit choice that this version
does not offer yet.
podcast for discovery is a separate, explicit choice (`Shift+F`, below).
- **Synchronized between trusted devices.** A podcast you subscribe to on
one device appears on the others without typing its URL again; each
device then checks the feed itself. Unsubscribing, "played", the saved
@@ -281,6 +287,94 @@ Podcasts and your connected devices:
or address), cannot add episodes to the host's queue and cannot seek in a
private item. They can still reorder the queue and skip.
Sharing a podcast (public discovery):
- `Shift+F` turns "share in the federation" on for one podcast. The choice is
synchronized to your trusted devices like a subscription; each of your
devices that runs the federation then publishes a small public card of the
podcast under its own device key: the feed URL, title, author,
description, artwork and web links, the number of episodes and the date of
the newest one. The card never contains your progress, history, play
counts, device names or anything from podcasts you did not share. Artwork
and web links that look like they carry an access key (a token, key or
signature in the query, a member-feed host) are left out, and so are both
for a feed whose own URL looks private. Random-looking parts of their
path alone do not count: public podcast hosts name artwork that way.
- If the feed URL looks private (a token, key or signature in its query, a
member-feed host such as Patreon, a long random-looking part), Furumi asks
first and lists why (in Russian). Anyone who finds the card can read the
feed at that URL. The confirmation is stored only on this device
(`podcast-share-confirmations.json` next to `podcasts.sqlite3`) and covers
exactly the URLs shown and this one decision to share: another device of
yours asks again before it publishes, and so does this one if the feed
moves or if sharing is turned off (or turned on again after that) on any
of your devices. Until then the side panel says the publication is held
back, and a card this device published for the earlier decision is
revoked; press `Shift+F` there to confirm (or `x` in the dialog to stop
sharing). A confirmation whose decision could not be saved is dropped.
- `Shift+F` on a shared podcast, or unsubscribing, makes it private again on
every device in your group: each device replaces its card with a signed
removal record. This device sends its removal right away, and quitting
waits for it (up to 4 seconds, also when you quit before the change is
saved) and logs a warning when a card may still be live. While the
removal is not sent yet (or could not be sent), the side panel says the
public card is not revoked yet instead of just "private". With the
federation off this device cannot tell whether a card of an earlier
session is still live, so for a podcast that was shared the panel says
the card may not be revoked yet; the removal is sent the next time the
federation runs. Until then, and for a copy that missed the removal, the
card can still be found until it expires (at most 12 hours). Removing your card never touches other
people's subscriptions. An older device that comes back with the earlier
"share" decision does not publish it again: after starting, a device with
other devices in its group publishes nothing until it has synced with one
of them (the side panel says "waiting for a sync with your other
devices"); it still revokes at once what its own decisions no longer
share. Devices of your group that still run Furumi 0.3 (they do not sync
podcasts) and devices without an address are not waited for; remove a
device you no longer use under Connected Devices so this one stops
waiting for it.
- A device that left your device group, or was removed from it, no longer
receives your share decisions: it keeps publishing the podcasts it shares
until you turn sharing off (or unsubscribe) on that device itself.
- The card is signed with this device's federation key, which is also the
key of its public music library, so a shared podcast can be linked to
that library and to the device's network address.
- Publishing needs the federation to be running; the side panel shows
"not published" with the reason otherwise.
Finding public podcasts:
- The search (`/` outside the Podcasts tab, with the federation
running) also looks for public podcast cards. They are listed after the
music results under "Podcasts · public cards", each marked `[podcast]`,
with the number of devices that publish the card (devices, not
subscribers; anyone can create devices, so it is not a sign of trust) or
"✓ subscribed" when this device already follows the podcast, also when
you subscribed under an older address of the same feed that moved to the
card's address. When you follow the feed under a newer address than the
card's, the list cannot tell yet; the card can once its episodes are read
(`e`), and «Подписаться» never adds a second subscription for it. Your
query words go to the discovery peers, as they do for music search. The
podcast search runs apart from the music search (music results never wait
for it) and gives up after 15 seconds. With the federation off, search
stays local and shows no podcasts.
- Enter opens the card (in Russian): what its publishers claim (title,
author, categories, description, number of episodes and date of the
newest one), the feed URL, and addresses some publishers claim the feed
moved to, shown as unverified and never used. `e` reads the feed itself
and lists its seasons and episodes without subscribing; this is a request
to the podcast's own server, not to the publisher.
- «Подписаться» (Enter) subscribes with the card's feed URL, the address
the podcast's id is derived from, so the podcast is the same one the
publisher shares. Furumi then reads the feed from its own server and
stores only what the feed says; the publisher does not need to stay
online, and nothing from the card is kept. The new subscription is
private like any other: it is not shared until you press `Shift+F`, and
your progress is your own. «Уже подписан» means this device is already
subscribed (under the card's address, an older one, or — once the feed
was read — the newer address the feed moved to); Enter then opens the
podcast in the Podcasts tab.
Podcast data lives in `podcasts.sqlite3` in the platform data directory (the
same file the earlier podcast test build used; it is upgraded in place). If
that file was written by a newer Furumi or is not a podcast database, the tab
@@ -367,8 +461,8 @@ owner_timeout_ms = 120000
All clients must support the new coordination envelope for eventual single
output ownership. frid's `PLAYBACK_PROTOCOL.md` describes the protocol, adapter
contract and rollout. Local Cargo patches are only for development; publish
frid and bump the client dependency versions before releasing these changes.
contract and rollout. This release uses the published FRID crates
`music-dht 0.6.0` and `furumi-library 0.3.0` from crates.io.
Run the local protocol checks from the TUI repository:
+10 -2
View File
@@ -32,6 +32,7 @@ pub enum Action {
ToggleShuffle,
CycleRepeat,
ToggleVisualizer,
CycleVisualizerMode,
ToggleLike,
ToggleTrackSelection,
OpenTrackInfo,
@@ -75,6 +76,9 @@ pub enum Action {
UnsubscribePodcast,
/// Podcasts: play the selected (or playing) episode from the beginning.
RestartEpisode,
/// Podcasts: turn "share in the federation" on or off for the selected
/// or opened podcast (asks first when its feed URL looks private).
TogglePodcastShare,
}
/// Help-window sections, in display order.
@@ -126,6 +130,7 @@ impl Action {
| Action::ToggleShuffle
| Action::CycleRepeat
| Action::ToggleVisualizer
| Action::CycleVisualizerMode
| Action::OpenConnectedDevices
| Action::OpenListenHistory => Category::Playback,
Action::QueueAddNext
@@ -168,7 +173,8 @@ impl Action {
| Action::CycleEpisodeFilter
| Action::ToggleEpisodePlayed
| Action::UnsubscribePodcast
| Action::RestartEpisode => Category::Podcasts,
| Action::RestartEpisode
| Action::TogglePodcastShare => Category::Podcasts,
Action::OpenSearch | Action::OpenCommandLine => Category::Search,
Action::ToggleHelp | Action::Quit => Category::System,
}
@@ -224,6 +230,7 @@ impl Action {
Action::ToggleShuffle => "Toggle shuffle".into(),
Action::CycleRepeat => "Cycle repeat mode".into(),
Action::ToggleVisualizer => "Toggle fullscreen visualizer".into(),
Action::CycleVisualizerMode => "Next visualizer display mode".into(),
Action::ToggleLike => "Like / unlike".into(),
Action::ToggleTrackSelection => "Track line selection".into(),
Action::OpenTrackInfo => "Track info".into(),
@@ -245,7 +252,7 @@ impl Action {
Action::CycleSourceMode => "Cycle source mode: Local / My / Global".into(),
Action::OpenLibraryFilters => "Library filters…".into(),
Action::OpenCommandLine => "Command line (:help for commands)".into(),
Action::OpenSearch => "Search artists, releases, tracks".into(),
Action::OpenSearch => "Search artists, releases, tracks, public podcasts".into(),
Action::EditSelected => "Edit the selected item".into(),
Action::DeleteSelected => "Delete the selected item".into(),
Action::AddPodcast => "Add podcast (RSS URL)".into(),
@@ -257,6 +264,7 @@ impl Action {
Action::ToggleEpisodePlayed => "Mark played / unplayed".into(),
Action::UnsubscribePodcast => "Unsubscribe (keeps progress)".into(),
Action::RestartEpisode => "Play episode from the start".into(),
Action::TogglePodcastShare => "Share podcast in the federation on/off".into(),
}
}
}
+44
View File
@@ -109,7 +109,9 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) {
state.search.results = None;
state.search.fed_tracks.clear();
state.search.fed_artists.clear();
state.search.fed_podcasts.clear();
state.search.fed_loading = false;
state.search.fed_podcasts_loading = false;
return;
}
let library = Arc::clone(&runtime.library);
@@ -132,7 +134,9 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) {
// node is up); its results render as a separate, marked section.
state.search.fed_tracks.clear();
state.search.fed_artists.clear();
state.search.fed_podcasts.clear();
state.search.fed_loading = false;
state.search.fed_podcasts_loading = false;
if runtime.federation.settings().enabled {
state.search.fed_loading = true;
let fed = Arc::clone(&runtime.federation);
@@ -147,9 +151,47 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) {
let result = fed.search(&query).await.map_err(|err| format!("{err:#}"));
let _ = tx.send(AppEvent::FedSearchLoaded { seq, result });
});
schedule_podcast_search(state, runtime, seq);
}
}
/// Public podcast cards for the live search `seq`, as their own task and
/// event: the overlay search (bounded, bootstrap included) never holds back
/// the music results.
fn schedule_podcast_search(state: &mut AppState, runtime: &Runtime, seq: u64) {
state.search.fed_podcasts_loading = true;
let fed = Arc::clone(&runtime.federation);
let query = state.search.query.clone();
let tx = runtime.event_tx.clone();
let latest = Arc::clone(&runtime.search_seq);
let podcast_store = runtime
.podcasts
.as_ref()
.map(|podcasts| Arc::clone(&podcasts.services.store));
tokio::spawn(async move {
tokio::time::sleep(SEARCH_DEBOUNCE).await;
if latest.load(Ordering::SeqCst) != seq {
return;
}
let mut hits = fed.search_podcasts(&query).await;
// Which public podcasts this device already knows (feed aliases
// included), for the "subscribed" mark.
if let Some(store) = podcast_store
&& !hits.is_empty()
{
hits = tokio::task::spawn_blocking(move || {
if let Err(err) = crate::podcasts::discovery::resolve_local_ids(&store, &mut hits) {
tracing::warn!("podcast search: feed aliases not resolved: {err:#}");
}
hits
})
.await
.unwrap_or_default();
}
let _ = tx.send(AppEvent::FedPodcastsLoaded { seq, hits });
});
}
pub(super) fn schedule_similarity_search(
state: &mut AppState,
runtime: &Runtime,
@@ -171,7 +213,9 @@ pub(super) fn schedule_similarity_search(
state.search.results = None;
state.search.fed_tracks.clear();
state.search.fed_artists.clear();
state.search.fed_podcasts.clear();
state.search.fed_loading = false;
state.search.fed_podcasts_loading = false;
state.active_tab = crate::app::state::Tab::Global;
if let Some(crate::app::state::GlobalView::Search { cursor }) = state.global.stack.last_mut() {
*cursor = 0;
+27
View File
@@ -138,6 +138,13 @@ pub enum AppEvent {
seq: u64,
result: Result<crate::federation::FedSearchResults, String>,
},
/// Public podcast cards for the same live search (`seq`), delivered on
/// their own so the music results never wait for the overlay. Already
/// resolved against the podcast store.
FedPodcastsLoaded {
seq: u64,
hits: Vec<crate::podcasts::discovery::PodcastHit>,
},
/// A federated artist card finished assembling.
FedArtistLoaded {
name: String,
@@ -268,4 +275,24 @@ pub enum AppEvent {
PodcastRefreshTick,
/// Feeds due for a background refresh.
PodcastsDue(Result<Vec<(music_dht::podcast::PodcastId, music_dht::podcast::FeedUrl)>, String>),
/// What sharing a podcast would publish (`Effect::PodcastPrepareShare`).
PodcastSharePrepared {
podcast_id: music_dht::podcast::PodcastId,
title: String,
result: Result<crate::podcasts::publication::ShareCheck, String>,
},
/// The share decision was written (`Effect::PodcastSetShared`).
PodcastShareSet {
podcast_id: music_dht::podcast::PodcastId,
title: String,
shared: bool,
result: Result<(), String>,
},
/// The publication reconciler finished a pass.
PodcastPublication(crate::podcasts::publication::PublicationReport),
/// A public card's feed was read for a preview (`Effect::PodcastPreview`).
PodcastPreviewLoaded {
podcast_id: music_dht::podcast::PodcastId,
result: Result<Box<crate::podcasts::discovery::FeedPreview>, String>,
},
}
+18 -2
View File
@@ -1734,7 +1734,12 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
| Effect::PodcastSubscribe(_)
| Effect::PodcastRefresh { .. }
| Effect::PodcastUnsubscribe { .. }
| Effect::PodcastSetPlayed { .. } => {}
| Effect::PodcastSetPlayed { .. }
| Effect::PodcastPrepareShare { .. }
| Effect::PodcastSetShared { .. }
| Effect::PodcastPublicationSync
| Effect::PodcastSubscribeFromCard(_)
| Effect::PodcastPreview { .. } => {}
Effect::LoadListenHistory => {
let library = Arc::clone(&runtime.library);
let devices = Arc::clone(&runtime.devices);
@@ -3531,7 +3536,11 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
| AppEvent::PodcastEpisodeStarted { .. }
| AppEvent::PodcastEpisodeFailed { .. }
| AppEvent::PodcastRefreshTick
| AppEvent::PodcastsDue(_) => {}
| AppEvent::PodcastsDue(_)
| AppEvent::PodcastSharePrepared { .. }
| AppEvent::PodcastShareSet { .. }
| AppEvent::PodcastPublication(_)
| AppEvent::PodcastPreviewLoaded { .. } => {}
AppEvent::StatusVisualizationReady(ready) => {
runtime.status_visualizer.busy = false;
state.status_visualizer.apply(ready);
@@ -3796,6 +3805,13 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
Err(message) => tracing::warn!(%message, "federated search failed"),
}
}
AppEvent::FedPodcastsLoaded { seq, hits } => {
if runtime.search_seq.load(std::sync::atomic::Ordering::SeqCst) != seq {
return;
}
state.search.fed_podcasts_loading = false;
state.search.fed_podcasts = hits;
}
AppEvent::FedSimilaritySearchLoaded { seq, result } => {
if runtime.search_seq.load(std::sync::atomic::Ordering::SeqCst) != seq {
return;
+253 -12
View File
@@ -12,13 +12,15 @@ use music_dht::podcast::{PodcastEpisodeRef, reaches_completion};
use super::event::AppEvent;
use super::state::{AppState, PodcastRow};
use super::update::{Effect, podcasts};
use super::update::{Effect, podcast_discovery, podcasts};
use super::{Runtime, err_string, perform_effect};
use crate::library::models::TrackItem;
use crate::podcasts::discovery;
use crate::podcasts::playback::{self, StartAt};
use crate::podcasts::progress::{
CHECKPOINT_INTERVAL, ProgressCommand, ProgressEvent, ProgressWriter,
};
use crate::podcasts::publication::{self, Reconciler, ShareConfirmations};
use crate::podcasts::refresh::{self, Services};
use crate::podcasts::stream::{CancelToken, StreamEnd, StreamProbe};
@@ -31,6 +33,9 @@ const SCHEDULER_FIRST_DELAY: Duration = Duration::from_secs(10);
const MAX_CONCURRENT_REFRESHES: usize = 4;
/// Feeds started per scheduler pass.
const MAX_DUE_PER_PASS: usize = 16;
/// How long quitting waits for a pending revocation (share turned off or
/// unsubscribed just before) to be signed and pushed.
const PUBLICATION_FLUSH_TIMEOUT: Duration = Duration::from_secs(4);
/// Podcast services available once the store opened.
pub struct PodcastRuntime {
@@ -39,6 +44,8 @@ pub struct PodcastRuntime {
/// Writes progress in order on its own thread; `None` if it could not
/// start (episodes then play without saving progress).
progress: Option<ProgressWriter>,
/// Publishes shared podcasts to public discovery and revokes the rest.
publication: Reconciler,
}
/// The episode this device is playing (or starting), as the progress
@@ -124,6 +131,53 @@ fn spawn_scheduler(tx: tokio::sync::mpsc::UnboundedSender<AppEvent>) {
});
}
/// Starts the publication reconciler. Without a store every own public
/// card is revoked (see `publication::reconcile`). Nothing is published
/// before device sync says the share registers are current
/// (`DeviceSync::podcast_registers_current`).
fn spawn_publication(
runtime: &Runtime,
store: Option<Arc<PodcastStore>>,
confirmations: Arc<ShareConfirmations>,
) -> Reconciler {
let tx = runtime.event_tx.clone();
publication::spawn(
runtime.federation.podcast_dht(),
runtime.devices.podcast_registers_current(),
store,
confirmations,
move |report| {
let _ = tx.send(AppEvent::PodcastPublication(report));
},
)
}
/// Asks the publication reconciler for a pass (share decisions, feed
/// metadata or subscriptions changed).
fn wake_publication(runtime: &Runtime) {
if let Some(podcasts) = &runtime.podcasts {
podcasts.publication.wake();
}
}
/// A card may have to be revoked (sharing turned off or unsubscribed here):
/// the write about to start ends with an immediate reconciler pass
/// ([`publication::RevocationTicket::done`]), and quitting waits for both,
/// bounded ([`PUBLICATION_FLUSH_TIMEOUT`]), even when it is handled before
/// the write finished.
fn begin_revocation(runtime: &Runtime) -> Option<publication::RevocationTicket> {
runtime
.podcasts
.as_ref()
.map(|podcasts| podcasts.publication.begin_revocation())
}
/// Whether `podcast_id` is shared now (a card from this device may be
/// live), read before a share-off or unsubscribe is written. Blocking.
fn shared_now(services: &Services, podcast_id: &music_dht::podcast::PodcastId) -> bool {
matches!(services.store.podcast(podcast_id), Ok(Some(summary)) if summary.shared)
}
fn services(runtime: &Runtime) -> Option<Services> {
runtime
.podcasts
@@ -140,9 +194,24 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O
state.podcasts.refreshing.remove(id);
}
}
if matches!(effect, Effect::PodcastSubscribe(_)) {
if matches!(
effect,
Effect::PodcastSubscribe(_) | Effect::PodcastSubscribeFromCard(_)
) {
state.podcasts.subscribing = false;
}
if let Effect::PodcastPreview { podcast_id, .. } = &effect {
podcast_discovery::preview_loaded(
state,
podcast_id.clone(),
Err("podcasts are unavailable".into()),
);
}
if let Effect::PodcastPrepareShare { podcast_id, .. }
| Effect::PodcastSetShared { podcast_id, .. } = &effect
{
state.podcasts.share_busy.remove(podcast_id);
}
state.status_message = Some("podcasts are unavailable (see the Podcasts tab)".into());
return None;
}
@@ -181,6 +250,26 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O
let _ = tx.send(AppEvent::PodcastSubscribed(result));
});
}
Effect::PodcastSubscribeFromCard(hit) => {
tokio::spawn(async move {
let result = discovery::subscribe_from_hit(&services, &hit, now_ms())
.await
.map_err(err_string);
let _ = tx.send(AppEvent::PodcastSubscribed(result));
});
}
Effect::PodcastPreview {
podcast_id,
feed_url,
} => {
tokio::spawn(async move {
let result = discovery::preview_for(&services, &feed_url)
.await
.map(Box::new)
.map_err(err_string);
let _ = tx.send(AppEvent::PodcastPreviewLoaded { podcast_id, result });
});
}
Effect::PodcastRefresh { targets, manual } => {
let slots = runtime
.podcasts
@@ -206,13 +295,28 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O
}
}
Effect::PodcastUnsubscribe { podcast_id, title } => {
let revocation = begin_revocation(runtime);
tokio::task::spawn_blocking(move || {
let store = Arc::clone(&services.store);
let id = podcast_id.clone();
let was_shared = shared_now(&services, &podcast_id);
let result = services
.log
.record(&mut |stamps| store.unsubscribe(stamps, &id))
.map_err(err_string);
// Unsubscribing also revoked the share decision: sharing
// after subscribing again asks again.
if result.is_ok()
&& let Err(err) = services.confirmations.forget(&podcast_id)
{
tracing::warn!("podcast share confirmation not removed: {err:#}");
}
// Unsubscribing revokes this device's card, right away.
if let Some(revocation) = revocation
&& result.is_ok()
{
revocation.done(was_shared.then_some(&podcast_id));
}
let _ = tx.send(AppEvent::PodcastUnsubscribed {
podcast_id,
title,
@@ -235,11 +339,75 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O
}
}
}
Effect::PodcastPrepareShare { podcast_id, title } => {
tokio::task::spawn_blocking(move || {
let result =
publication::check_share(&services.store, &services.confirmations, &podcast_id)
.map_err(err_string);
let _ = tx.send(AppEvent::PodcastSharePrepared {
podcast_id,
title,
result,
});
});
}
Effect::PodcastSetShared {
podcast_id,
title,
shared,
confirm,
} => {
let revocation = if shared {
None
} else {
begin_revocation(runtime)
};
tokio::task::spawn_blocking(move || {
let was_shared = !shared && shared_now(&services, &podcast_id);
let result =
set_shared(&services, &podcast_id, shared, confirm).map_err(err_string);
if let Some(revocation) = revocation
&& result.is_ok()
{
revocation.done(was_shared.then_some(&podcast_id));
}
let _ = tx.send(AppEvent::PodcastShareSet {
podcast_id,
title,
shared,
result,
});
});
}
Effect::PodcastPublicationSync => wake_publication(runtime),
other => return Some(other),
}
None
}
/// Writes a share decision and keeps the local privacy confirmation bound
/// to it (`publication::set_shared`). Blocking.
fn set_shared(
services: &Services,
podcast_id: &music_dht::podcast::PodcastId,
shared: bool,
confirm: Option<publication::ConfirmedUrls>,
) -> anyhow::Result<()> {
let store = Arc::clone(&services.store);
publication::set_shared(
&services.store,
&services.confirmations,
podcast_id,
shared,
confirm,
|| {
services
.log
.record(&mut |stamps| store.set_shared(stamps, podcast_id, shared))
},
)
}
fn is_podcast_effect(effect: &Effect) -> bool {
matches!(
effect,
@@ -250,6 +418,11 @@ fn is_podcast_effect(effect: &Effect) -> bool {
| Effect::PodcastRefresh { .. }
| Effect::PodcastUnsubscribe { .. }
| Effect::PodcastSetPlayed { .. }
| Effect::PodcastPrepareShare { .. }
| Effect::PodcastSetShared { .. }
| Effect::PodcastPublicationSync
| Effect::PodcastSubscribeFromCard(_)
| Effect::PodcastPreview { .. }
)
}
@@ -274,6 +447,11 @@ pub fn handle_event(
) -> Option<AppEvent> {
let effects: Vec<Effect> = match event {
AppEvent::PodcastStoreOpened(result) => {
if result.is_err() {
// This device can no longer tell what is shared: revoke its
// own public cards (fail-safe for privacy).
let _ = spawn_publication(runtime, None, Arc::new(ShareConfirmations::in_memory()));
}
let result = result.map(|services| {
let tx = runtime.event_tx.clone();
let progress = ProgressWriter::spawn(services.clone(), move |event| {
@@ -291,10 +469,16 @@ pub fn handle_event(
tracing::warn!("podcast sync: {err:#}");
}
});
let publication = spawn_publication(
runtime,
Some(Arc::clone(&services.store)),
Arc::clone(&services.confirmations),
);
runtime.podcasts = Some(PodcastRuntime {
services,
refresh_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_REFRESHES)),
progress,
publication,
});
spawn_scheduler(runtime.event_tx.clone());
});
@@ -323,17 +507,59 @@ pub fn handle_event(
podcast_id,
result,
manual,
} => podcasts::refreshed(state, podcast_id, result, manual),
} => {
// The card of a shared podcast follows its feed metadata.
if result.is_ok() {
wake_publication(runtime);
}
podcasts::refreshed(state, podcast_id, result, manual)
}
AppEvent::PodcastUnsubscribed {
podcast_id,
title,
result,
} => podcasts::unsubscribed(state, podcast_id, title, result)
} => {
// The blocking write already asked for the revocation pass.
podcasts::unsubscribed(state, podcast_id, title, result)
.into_iter()
.collect()
}
AppEvent::PodcastSharePrepared {
podcast_id,
title,
result,
} => podcasts::share_prepared(state, podcast_id, title, result)
.into_iter()
.collect(),
AppEvent::PodcastShareSet {
podcast_id,
title,
shared,
result,
} => {
// A share-off already asked for its revocation pass when it
// was written.
if shared || result.is_err() {
wake_publication(runtime);
}
podcasts::share_set(state, podcast_id, title, shared, result)
.into_iter()
.collect()
}
AppEvent::PodcastPreviewLoaded { podcast_id, result } => {
podcast_discovery::preview_loaded(state, podcast_id, result);
Vec::new()
}
AppEvent::PodcastPublication(report) => {
podcasts::publication_reported(state, report);
Vec::new()
}
AppEvent::PodcastProgress(event) => progress_event(state, runtime, event),
AppEvent::PodcastsSynced { progress, changed } => {
if changed {
// Share or subscription decisions of another device: publish
// or revoke this device's own cards accordingly.
wake_publication(runtime);
// A subscription that came from another device has no
// episodes here until its feed is fetched: check now.
let _ = runtime.event_tx.send(AppEvent::PodcastRefreshTick);
@@ -916,18 +1142,33 @@ fn progress_event(
}
}
/// Before exit: end the playing episode's session and give the progress
/// writer a moment to save it.
/// Before exit (before the federation node stops): end the playing
/// episode's session and give the progress writer a moment to save it, and
/// let a revocation requested just before (sharing turned off, unsubscribed;
/// also one still being written) reach the overlay. Logs a warning when a
/// card of a private podcast may still be live.
pub(crate) async fn shutdown(runtime: &mut Runtime) {
end_playback(runtime);
let Some(mut progress) = runtime
.podcasts
.as_mut()
.and_then(|podcasts| podcasts.progress.take())
else {
let Some(podcasts) = runtime.podcasts.as_mut() else {
return;
};
let _ = tokio::task::spawn_blocking(move || progress.close(Duration::from_secs(3))).await;
let publication = podcasts.publication.clone();
let progress = podcasts.progress.take();
let flush = async {
if !publication.flush(PUBLICATION_FLUSH_TIMEOUT).await {
tracing::warn!(
"podcast publication: a public card may not be revoked yet; \
it is revoked on the next start with federation on"
);
}
};
let close = async {
if let Some(mut progress) = progress {
let _ =
tokio::task::spawn_blocking(move || progress.close(Duration::from_secs(3))).await;
}
};
tokio::join!(flush, close);
}
#[cfg(test)]
+14
View File
@@ -124,6 +124,20 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) {
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => {}
_ => state.popup = Some(Popup::ConfirmPodcastUnsubscribe { podcast_id, title }),
},
popup @ Popup::PodcastCard { .. } => {
if let Some(effect) =
crate::app::update::podcast_discovery::card_key(state, popup, key.code)
{
super::perform_effect(state, runtime, effect);
}
}
popup @ Popup::ConfirmPodcastShare { .. } => {
if let Some(effect) =
crate::app::update::podcasts::share_confirmation_key(state, popup, key.code)
{
super::perform_effect(state, runtime, effect);
}
}
Popup::SimilarityPrivacyConsent { enable_federation } => match key.code {
KeyCode::Enter | KeyCode::Char('y') => {
state.similarity.settings.federation_consent = true;
+62
View File
@@ -768,6 +768,32 @@ pub enum Popup {
podcast_id: music_dht::podcast::PodcastId,
title: String,
},
/// Sharing a podcast whose feed URL looks private: the user confirms
/// publishing exactly `urls`. Enter/y publishes, Esc/n cancels; when the
/// podcast is already shared (publication held back on this device),
/// `x` turns sharing off.
ConfirmPodcastShare {
podcast_id: music_dht::podcast::PodcastId,
title: String,
urls: crate::podcasts::publication::ConfirmedUrls,
/// Russian descriptions of the privacy warnings.
warnings: Vec<String>,
already_shared: bool,
},
/// A public podcast card from the search results: its claims, an
/// optional episode preview read from the feed, and "Подписаться" (or
/// "Уже подписан" when this device is subscribed under any of its ids).
PodcastCard {
hit: Box<crate::podcasts::discovery::PodcastHit>,
/// `None` until the user asks for the episodes (`e`).
preview: Option<Loadable<crate::podcasts::discovery::FeedPreview>>,
/// First body line shown.
scroll: u16,
/// Largest useful `scroll` at the last draw (the wrapped body
/// height minus the visible rows); scroll keys stop there.
/// `u16::MAX` until the card was drawn.
max_scroll: std::cell::Cell<u16>,
},
/// Enabling network similarity reveals an embedding query to peers.
SimilarityPrivacyConsent { enable_federation: bool },
/// Derived data is safe to recreate but potentially expensive.
@@ -1420,7 +1446,14 @@ pub struct SearchState {
/// Artists a federated card can be opened for — from artist records and
/// from the artist names of matching tracks.
pub fed_artists: Vec<crate::federation::FedArtistHit>,
/// Public podcast cards (type `podcast`), listed after the federated
/// tracks; Enter opens the card.
pub fed_podcasts: Vec<crate::podcasts::discovery::PodcastHit>,
/// The federated music search is running.
pub fed_loading: bool,
/// The podcast search in the discovery overlay is running (separately,
/// so the music results never wait for it).
pub fed_podcasts_loading: bool,
/// Present only for a track-seeded search; text-search refreshes must not
/// replace this page with a title query.
pub similarity_source: Option<i64>,
@@ -1433,6 +1466,24 @@ pub struct SearchState {
}
impl SearchState {
/// Rows the cursor can reach in a text search: local artists, releases
/// and tracks, then federated artists, tracks and podcasts.
pub fn total_len(&self) -> usize {
self.results.as_ref().map_or(0, SearchResults::len)
+ self.fed_artists.len()
+ self.fed_tracks.len()
+ self.fed_podcasts.len()
}
/// Something federated is shown (or still loading).
pub fn has_federated(&self) -> bool {
!self.fed_tracks.is_empty()
|| !self.fed_artists.is_empty()
|| !self.fed_podcasts.is_empty()
|| self.fed_loading
|| self.fed_podcasts_loading
}
pub fn similarity_len(&self) -> usize {
usize::from(self.similarity_source_track.is_some()) + self.similarity_tracks.len()
}
@@ -1796,6 +1847,10 @@ pub struct PodcastsTab {
pub pending_select: Option<music_dht::podcast::PodcastId>,
/// Last episode request sequence handed out.
pub episode_seq: u64,
/// This device's public discovery publications (last reconciler pass).
pub publication: crate::podcasts::publication::PublicationReport,
/// A share check or share decision is being written.
pub share_busy: HashSet<music_dht::podcast::PodcastId>,
}
impl PodcastsTab {
@@ -1810,6 +1865,13 @@ impl PodcastsTab {
self.podcasts().iter().find(|row| row.id() == id)
}
/// This device is subscribed to the podcast of a public card: under the
/// card's id or under the id its origin URL resolves to here (a feed
/// alias of a podcast subscribed earlier).
pub fn subscribed_to(&self, hit: &crate::podcasts::discovery::PodcastHit) -> bool {
hit.ids().into_iter().any(|id| self.podcast(id).is_some())
}
pub fn list_rows(&self) -> Vec<PodcastListRow> {
let mut rows = vec![PodcastListRow::Add, PodcastListRow::RefreshAll];
rows.extend((0..self.podcasts().len()).map(PodcastListRow::Podcast));
+56 -9
View File
@@ -136,6 +136,32 @@ pub enum Effect {
episode_id: music_dht::podcast::EpisodeId,
played: bool,
},
/// Check what sharing a podcast would publish (privacy warnings) before
/// turning sharing on or confirming a held-back publication.
PodcastPrepareShare {
podcast_id: music_dht::podcast::PodcastId,
title: String,
},
/// Turn sharing on or off (synced decision). `confirm` records, on this
/// device only, that the user confirmed publishing these feed URLs
/// despite privacy warnings.
PodcastSetShared {
podcast_id: music_dht::podcast::PodcastId,
title: String,
shared: bool,
confirm: Option<crate::podcasts::publication::ConfirmedUrls>,
},
/// Reconcile this device's public podcast cards now.
PodcastPublicationSync,
/// Subscribe to the podcast of a public card with its origin feed URL
/// (`podcasts::discovery::subscribe_from_hit`); reported as
/// `AppEvent::PodcastSubscribed`.
PodcastSubscribeFromCard(Box<music_dht::podcast_dht::PodcastSearchHit>),
/// Read a public card's feed for an episode preview (nothing stored).
PodcastPreview {
podcast_id: music_dht::podcast::PodcastId,
feed_url: music_dht::podcast::FeedUrl,
},
}
pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
@@ -363,6 +389,18 @@ pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
}
None
}
Action::CycleVisualizerMode => {
if state.visualizer.active {
if let Err(err) = state.visualizer.cycle_mode() {
// the fullscreen visualizer hides the status line
tracing::warn!(error = %format!("{err:#}"), "saving the visualizer mode failed");
state.status_message = Some(format!("visualization settings: {err:#}"));
}
} else {
state.status_message = Some("open the visualizer first (Shift+L)".into());
}
None
}
Action::Select => select_current(state),
Action::Back if state.visualizer.active => {
state.visualizer.close();
@@ -541,7 +579,8 @@ pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
| Action::CycleEpisodeSort
| Action::CycleEpisodeFilter
| Action::ToggleEpisodePlayed
| Action::UnsubscribePodcast => {
| Action::UnsubscribePodcast
| Action::TogglePodcastShare => {
state.status_message = Some(format!(
"open the Podcasts tab ({}) for this command",
Tab::Podcasts.index() + 1
@@ -2050,9 +2089,7 @@ fn move_selection(state: &mut AppState, dx: isize, dy: isize) {
let total = if state.search.similarity_source.is_some() {
state.search.similarity_len()
} else {
state.search.results.as_ref().map_or(0, |r| r.len())
+ state.search.fed_artists.len()
+ state.search.fed_tracks.len()
state.search.total_len()
} as isize;
if total == 0 {
return;
@@ -2176,9 +2213,7 @@ fn current_view_len(state: &AppState) -> usize {
if state.search.similarity_source.is_some() {
state.search.similarity_len()
} else {
state.search.results.as_ref().map_or(0, |r| r.len())
+ state.search.fed_artists.len()
+ state.search.fed_tracks.len()
state.search.total_len()
}
}
Some(GlobalView::FedArtist { .. }) => fed_card_len(state),
@@ -2614,6 +2649,10 @@ fn select_current(state: &mut AppState) -> Option<Effect> {
state.active_tab = Tab::Global;
Some(Effect::FedOpenArtist(name))
}
Outcome::OpenPodcastCard(index) => {
podcast_discovery::open_card(state, index);
None
}
Outcome::OpenFedRelease { name, card, index } => {
let start =
if card.releases.get(index).is_some_and(|release| {
@@ -2855,6 +2894,7 @@ enum Outcome {
start: usize,
},
OpenFedArtist(String),
OpenPodcastCard(usize),
OpenFedRelease {
name: String,
card: crate::federation::FedArtistCard,
@@ -2865,7 +2905,8 @@ enum Outcome {
}
/// Enter inside the federated section of the search results: artists open
/// their card, tracks queue up like a local track list.
/// their card, tracks queue up like a local track list, podcasts open their
/// public card.
fn fed_outcome(state: &AppState, fed_index: usize) -> Outcome {
let artists = &state.search.fed_artists;
if fed_index < artists.len() {
@@ -2873,7 +2914,12 @@ fn fed_outcome(state: &AppState, fed_index: usize) -> Outcome {
}
let start = fed_index - artists.len();
if start >= state.search.fed_tracks.len() {
return Outcome::Nothing;
let podcast = start - state.search.fed_tracks.len();
return if podcast < state.search.fed_podcasts.len() {
Outcome::OpenPodcastCard(podcast)
} else {
Outcome::Nothing
};
}
Outcome::Play {
tracks: state
@@ -3378,6 +3424,7 @@ fn not_yet(state: &mut AppState, what: &str) {
state.status_message = Some(format!("{what}: coming in a later milestone"));
}
pub(crate) mod podcast_discovery;
pub(crate) mod podcasts;
#[cfg(test)]
+135
View File
@@ -0,0 +1,135 @@
//! Public podcast cards opened from the search results.
//!
//! The card shows what its publishers claim. "Подписаться" subscribes with
//! the card's origin feed URL only (`Effect::PodcastSubscribeFromCard`); the
//! subscription is private and its metadata comes from the feed. When this
//! device is already subscribed (under the card's id or a feed alias), the
//! action reads «Уже подписан» and Enter opens the podcast instead.
use crossterm::event::KeyCode;
use music_dht::podcast::PodcastId;
use super::Effect;
use super::podcasts::{display_title, reveal_podcast, store_ready};
use crate::app::state::{AppState, Loadable, Popup};
use crate::podcasts::discovery::{FeedPreview, PodcastHit};
/// Lines a page key scrolls the card by.
const PAGE: u16 = 10;
/// Enter on a podcast hit of the search results.
pub fn open_card(state: &mut AppState, index: usize) {
let Some(hit) = state.search.fed_podcasts.get(index) else {
return;
};
state.popup = Some(Popup::PodcastCard {
hit: Box::new(hit.clone()),
preview: None,
scroll: 0,
max_scroll: std::cell::Cell::new(u16::MAX),
});
}
/// A key in [`Popup::PodcastCard`] (the popup was taken out of the state):
/// Enter/s subscribes (or opens the subscribed podcast), `e` reads the
/// episodes from the feed, arrows and page keys scroll, Esc/q closes.
pub fn card_key(state: &mut AppState, popup: Popup, key: KeyCode) -> Option<Effect> {
let Popup::PodcastCard {
hit,
mut preview,
mut scroll,
max_scroll,
} = popup
else {
state.popup = Some(popup);
return None;
};
let mut effect = None;
match key {
KeyCode::Esc | KeyCode::Char('q') => return None,
KeyCode::Enter | KeyCode::Char('s') => {
if let Some(id) = subscribed_id(state, &hit, preview.as_ref()) {
// «Уже подписан»: show the subscription instead.
return reveal_podcast(state, id, hit.title());
}
effect = subscribe(state, &hit);
}
KeyCode::Char('e') => {
if !matches!(preview, Some(Loadable::Loading | Loadable::Ready(_))) {
preview = Some(Loadable::Loading);
effect = Some(Effect::PodcastPreview {
podcast_id: hit.hit.podcast_id.clone(),
feed_url: hit.hit.feed_url.clone(),
});
}
}
KeyCode::Up | KeyCode::Char('k') => scroll = scroll.saturating_sub(1),
KeyCode::Down | KeyCode::Char('j') => scroll = scroll.saturating_add(1),
KeyCode::PageUp => scroll = scroll.saturating_sub(PAGE),
KeyCode::PageDown => scroll = scroll.saturating_add(PAGE),
KeyCode::Home | KeyCode::Char('g') => scroll = 0,
_ => {}
}
// Never past the end the last draw measured, so scrolling back moves
// the view at once.
scroll = scroll.min(max_scroll.get());
state.popup = Some(Popup::PodcastCard {
hit,
preview,
scroll,
max_scroll,
});
effect
}
/// The id under which this device is subscribed to the card's podcast: the
/// card's id, the id its origin URL resolves to here (a feed alias), or —
/// once the feed was read — the podcast followed under the newer address
/// the feed moved to.
pub fn subscribed_id(
state: &AppState,
hit: &PodcastHit,
preview: Option<&Loadable<FeedPreview>>,
) -> Option<PodcastId> {
let moved = match preview {
Some(Loadable::Ready(preview)) => preview.subscribed_as.as_ref(),
_ => None,
};
hit.ids()
.into_iter()
.chain(moved)
.find(|id| state.podcasts.podcast(id).is_some())
.cloned()
}
fn subscribe(state: &mut AppState, hit: &PodcastHit) -> Option<Effect> {
if !store_ready(state) {
return None;
}
if state.podcasts.subscribing {
state.status_message = Some("podcasts: a subscription is already being added".into());
return None;
}
state.podcasts.subscribing = true;
state.status_message = Some(format!(
"podcasts: reading the feed of {}…",
display_title(hit.title())
));
Some(Effect::PodcastSubscribeFromCard(Box::new(hit.hit.clone())))
}
/// The preview of an open card arrived (ignored when another card is open).
pub fn preview_loaded(
state: &mut AppState,
podcast_id: PodcastId,
result: Result<Box<FeedPreview>, String>,
) {
if let Some(Popup::PodcastCard { hit, preview, .. }) = &mut state.popup
&& hit.hit.podcast_id == podcast_id
{
*preview = Some(match result {
Ok(feed) => Loadable::Ready(*feed),
Err(err) => Loadable::Failed(err),
});
}
}
+246 -3
View File
@@ -18,6 +18,7 @@ use crate::app::state::{
PODCAST_EPISODE_PAGE, PodcastListRow, PodcastRow, PodcastStoreStatus, Popup, SeasonRow, Tab,
};
use crate::library::models::TrackItem;
use crate::podcasts::publication::{Publication, PublicationReport, ShareCheck, warning_ru};
use crate::podcasts::refresh::{RefreshReport, SubscribeReport};
/// The next page starts loading when the cursor is this close to the end.
@@ -59,13 +60,14 @@ pub(super) fn handle(state: &mut AppState, action: &Action) -> Option<Option<Eff
Action::CycleEpisodeFilter => cycle_played_filter(state),
Action::ToggleEpisodePlayed => toggle_played(state),
Action::RestartEpisode => restart_selected(state),
Action::TogglePodcastShare => toggle_share(state),
_ => return None,
};
Some(effect)
}
/// Whether podcast actions may run; explains why not in the status bar.
fn store_ready(state: &mut AppState) -> bool {
pub(super) fn store_ready(state: &mut AppState) -> bool {
match &state.podcasts.store {
PodcastStoreStatus::Ready => true,
PodcastStoreStatus::Opening => {
@@ -369,6 +371,15 @@ pub fn reveal_episode_podcast(state: &mut AppState, track: &TrackItem) -> Option
let episode = track.podcast_episode_ref()?;
let podcast_id = episode.podcast_id.clone();
let title = episode.podcast_title.clone();
reveal_podcast(state, podcast_id, &title)
}
/// Switches to the Podcasts tab and opens a subscribed podcast.
pub(super) fn reveal_podcast(
state: &mut AppState,
podcast_id: PodcastId,
title: &str,
) -> Option<Effect> {
state.active_tab = Tab::Podcasts;
state.help_visible = false;
state.track_selection.clear();
@@ -398,7 +409,7 @@ pub fn reveal_episode_podcast(state: &mut AppState, track: &TrackItem) -> Option
None => {
state.status_message = Some(format!(
"podcasts: {} is not subscribed on this device",
display_title(&title)
display_title(title)
));
None
}
@@ -616,6 +627,237 @@ fn confirm_unsubscribe(state: &mut AppState) {
});
}
/// Shift-F: share the selected or opened podcast in the federation, or stop
/// sharing it.
///
/// Turning sharing on first checks the card it would publish
/// ([`Effect::PodcastPrepareShare`]); a feed URL that looks private asks for
/// confirmation in [`Popup::ConfirmPodcastShare`] ([`share_prepared`]).
/// A shared podcast whose publication is held back on this device (the URL
/// changed or was shared from another device) asks again instead of turning
/// sharing off; the dialog can still turn it off.
fn toggle_share(state: &mut AppState) -> Option<Effect> {
if !store_ready(state) {
return None;
}
let Some(row) = state.podcasts.current_podcast() else {
state.status_message = Some("podcasts: select a podcast to share".into());
return None;
};
let podcast_id = row.id().clone();
let title = row.title().to_string();
let shared = row.summary.shared;
if state.podcasts.share_busy.contains(&podcast_id) {
state.status_message = Some("podcasts: still saving the share setting".into());
return None;
}
let held = matches!(
state.podcasts.publication.podcasts.get(&podcast_id),
Some(Publication::HeldBack(_))
);
state.podcasts.share_busy.insert(podcast_id.clone());
if shared && !held {
state.status_message = Some(format!(
"podcasts: stopping sharing {}…",
display_title(&title)
));
return Some(Effect::PodcastSetShared {
podcast_id,
title,
shared: false,
confirm: None,
});
}
Some(Effect::PodcastPrepareShare { podcast_id, title })
}
/// The card check of [`toggle_share`] arrived: share right away, or ask
/// about the privacy warnings first.
pub fn share_prepared(
state: &mut AppState,
podcast_id: PodcastId,
title: String,
result: Result<ShareCheck, String>,
) -> Option<Effect> {
let check = match result {
Ok(check) => check,
Err(err) => {
state.podcasts.share_busy.remove(&podcast_id);
state.status_message = Some(format!("podcasts: cannot share: {err}"));
return None;
}
};
let already_shared = state
.podcasts
.podcast(&podcast_id)
.is_some_and(|row| row.summary.shared);
if check.needs_confirmation() || (already_shared && !check.warnings.is_empty()) {
// Wait for the user; nothing is written until they confirm.
state.podcasts.share_busy.remove(&podcast_id);
state.popup = Some(Popup::ConfirmPodcastShare {
podcast_id,
title,
urls: check.urls,
warnings: check.warnings.iter().map(warning_ru).collect(),
already_shared,
});
return None;
}
if already_shared {
// Held back without warnings any more: the next pass publishes it.
state.podcasts.share_busy.remove(&podcast_id);
state.status_message = Some(format!(
"podcasts: {} is shared; publishing…",
display_title(&title)
));
return Some(Effect::PodcastPublicationSync);
}
state.status_message = Some(format!("podcasts: sharing {}…", display_title(&title)));
Some(Effect::PodcastSetShared {
podcast_id,
title,
shared: true,
// Already confirmed earlier for exactly these URLs (or no warning).
confirm: None,
})
}
/// A key in [`Popup::ConfirmPodcastShare`]: Enter/y publishes exactly the
/// URLs shown (and remembers that confirmation on this device), `x` stops
/// sharing a podcast that is already shared, Esc/n/q cancels (nothing is
/// written). Other keys keep the dialog open.
pub fn share_confirmation_key(
state: &mut AppState,
popup: Popup,
code: crossterm::event::KeyCode,
) -> Option<Effect> {
use crossterm::event::KeyCode;
let Popup::ConfirmPodcastShare {
podcast_id,
title,
urls,
warnings,
already_shared,
} = popup
else {
state.popup = Some(popup);
return None;
};
match code {
KeyCode::Enter | KeyCode::Char('y') => {
state.podcasts.share_busy.insert(podcast_id.clone());
state.status_message = Some(format!("podcasts: sharing {}…", display_title(&title)));
Some(Effect::PodcastSetShared {
podcast_id,
title,
shared: true,
confirm: Some(urls),
})
}
KeyCode::Char('x') if already_shared => {
state.podcasts.share_busy.insert(podcast_id.clone());
state.status_message = Some(format!(
"podcasts: stopping sharing {}…",
display_title(&title)
));
Some(Effect::PodcastSetShared {
podcast_id,
title,
shared: false,
confirm: None,
})
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => {
state.status_message = Some(if already_shared {
"podcasts: not published from this device until you confirm".into()
} else {
"podcasts: the podcast stays private".into()
});
None
}
_ => {
state.popup = Some(Popup::ConfirmPodcastShare {
podcast_id,
title,
urls,
warnings,
already_shared,
});
None
}
}
}
/// The share decision was written; the reconciler publishes or revokes.
pub fn share_set(
state: &mut AppState,
podcast_id: PodcastId,
title: String,
shared: bool,
result: Result<(), String>,
) -> Option<Effect> {
state.podcasts.share_busy.remove(&podcast_id);
let title = display_title(&title);
match result {
Ok(()) if shared => {
state.status_message = Some(format!(
"podcasts: {title} is shared in the federation (publishing from this device)"
));
Some(Effect::PodcastsReload)
}
Ok(()) => {
note_revocation(state, &podcast_id);
state.status_message = Some(format!(
"podcasts: {title} is private again; the public card is being revoked"
));
Some(Effect::PodcastsReload)
}
Err(err) => {
state.status_message = Some(format!("podcasts: cannot change sharing: {err}"));
None
}
}
}
/// Sharing of `podcast_id` was turned off or it was unsubscribed here: its
/// card counts as not revoked until a pass says otherwise
/// (`PublicationReport::note_revocation`; the row is not reloaded yet, so it
/// still says whether the podcast was shared).
fn note_revocation(state: &mut AppState, podcast_id: &PodcastId) {
let was_shared = state
.podcasts
.podcast(podcast_id)
.is_some_and(|row| row.summary.shared);
state
.podcasts
.publication
.note_revocation(podcast_id, was_shared);
}
/// A publication reconciler pass finished. Errors go to the status bar
/// when they are new (the log has them too).
pub fn publication_reported(state: &mut AppState, report: PublicationReport) {
let previous = std::mem::replace(&mut state.podcasts.publication, report);
let report = &state.podcasts.publication;
if let Some(error) = &report.error
&& previous.error.as_ref() != Some(error)
{
state.status_message = Some(format!("podcasts: public discovery: {error}"));
}
for (podcast_id, publication) in &report.podcasts {
if let Publication::Failed(error) = publication
&& previous.podcasts.get(podcast_id) != Some(publication)
{
let title = state
.podcasts
.podcast(podcast_id)
.map(|row| display_title(row.title()))
.unwrap_or_else(|| "a shared podcast".to_string());
state.status_message = Some(format!("podcasts: cannot publish {title}: {error}"));
}
}
}
fn refresh_targets(state: &mut AppState, rows: Vec<&PodcastRow>) -> Vec<(PodcastId, FeedUrl)> {
rows.into_iter()
.filter(|row| !state.podcasts.refreshing.contains(row.id()))
@@ -859,7 +1101,7 @@ pub fn subscribed(state: &mut AppState, result: Result<SubscribeReport, String>)
}
}
fn display_title(title: &str) -> String {
pub(super) fn display_title(title: &str) -> String {
if title.trim().is_empty() {
"the podcast".to_string()
} else {
@@ -926,6 +1168,7 @@ pub fn unsubscribed(
) -> Option<Effect> {
match result {
Ok(()) => {
note_revocation(state, &podcast_id);
state.status_message = Some(format!(
"podcasts: unsubscribed from {}; progress and history are kept",
display_title(&title)
+607
View File
@@ -776,6 +776,20 @@ fn visualizer_requires_current_track() {
);
}
#[test]
fn visualizer_mode_needs_an_open_visualizer() {
let mut state = AppState::default();
let mode = state.visualizer.config.mode;
assert_eq!(update(&mut state, Action::CycleVisualizerMode), None);
assert_eq!(state.visualizer.config.mode, mode);
assert_eq!(
state.status_message.as_deref(),
Some("open the visualizer first (Shift+L)")
);
}
#[test]
fn visualizer_toggles_and_back_closes_it() {
let mut state = AppState::default();
@@ -1834,6 +1848,335 @@ mod podcast_tab {
Some(Effect::PodcastLoadEpisodes { .. })
));
}
// --- Sharing in the federation (MR-T3) ---
use crate::podcasts::publication::{
ConfirmedUrls, Discovery, Publication, PublicationReport, ShareCheck,
};
use crossterm::event::KeyCode;
fn urls() -> ConfirmedUrls {
ConfirmedUrls {
feed_url: FeedUrl::parse("https://example.test/feed.xml").unwrap(),
id_feed_url: None,
}
}
fn check(warnings: bool, confirmed: bool) -> ShareCheck {
ShareCheck {
urls: urls(),
warnings: if warnings {
vec![
music_dht::podcast_dht::FeedUrlPrivacyWarning::SecretQueryParameter {
name: "token".into(),
},
]
} else {
Vec::new()
},
confirmed,
}
}
fn set_shared(shared: bool, confirm: Option<ConfirmedUrls>) -> Option<Effect> {
Some(Effect::PodcastSetShared {
podcast_id: podcast_id(),
title: "Show".into(),
shared,
confirm,
})
}
fn shared_row() -> crate::app::state::PodcastRow {
let mut row = fx::row("Show", 0, 1, 0);
row.summary.shared = true;
row
}
#[test]
fn sharing_a_podcast_checks_its_card_first_and_shares_without_warnings() {
let mut state = ready(vec![fx::row("Show", 0, 1, 0)]);
assert_eq!(
update(&mut state, Action::TogglePodcastShare),
Some(Effect::PodcastPrepareShare {
podcast_id: podcast_id(),
title: "Show".into(),
})
);
// A second press while the check runs does nothing.
assert_eq!(update(&mut state, Action::TogglePodcastShare), None);
let effect = podcasts::share_prepared(
&mut state,
podcast_id(),
"Show".into(),
Ok(check(false, false)),
);
assert_eq!(effect, set_shared(true, None));
assert!(state.popup.is_none());
// Also inside the opened podcast.
let mut state = ready(vec![fx::row("Show", 0, 1, 0)]);
let (seq, _) = episode_request(update(&mut state, Action::Select));
podcasts::episodes_loaded(&mut state, seq, 0, Ok(page(1)));
assert!(matches!(
update(&mut state, Action::TogglePodcastShare),
Some(Effect::PodcastPrepareShare { .. })
));
// Already confirmed for exactly these URLs: no dialog.
let effect = podcasts::share_prepared(
&mut state,
podcast_id(),
"Show".into(),
Ok(check(true, true)),
);
assert_eq!(effect, set_shared(true, None));
}
#[test]
fn a_private_looking_feed_url_is_shared_only_after_confirmation() {
let mut state = ready(vec![fx::row("Show", 0, 1, 0)]);
update(&mut state, Action::TogglePodcastShare);
let effect = podcasts::share_prepared(
&mut state,
podcast_id(),
"Show".into(),
Ok(check(true, false)),
);
assert_eq!(effect, None, "nothing is written before the user confirms");
let Some(Popup::ConfirmPodcastShare {
warnings,
already_shared,
urls: shown,
..
}) = &state.popup
else {
panic!("expected the share confirmation, got {:?}", state.popup);
};
assert_eq!(
warnings,
&vec!["в адресе ленты есть параметр «token», похожий на ключ доступа".to_string()]
);
assert!(!already_shared);
assert_eq!(shown, &urls());
assert!(state.podcasts.share_busy.is_empty());
// Esc keeps the podcast private; other keys keep the dialog.
let popup = state.popup.take().unwrap();
assert_eq!(
podcasts::share_confirmation_key(&mut state, popup, KeyCode::Char('j')),
None
);
assert!(state.popup.is_some());
let popup = state.popup.take().unwrap();
assert_eq!(
podcasts::share_confirmation_key(&mut state, popup, KeyCode::Char('x')),
None
);
assert!(state.popup.is_some(), "x only stops an existing share");
let popup = state.popup.take().unwrap();
assert_eq!(
podcasts::share_confirmation_key(&mut state, popup, KeyCode::Esc),
None
);
assert!(state.popup.is_none());
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("stays private"))
);
// Enter confirms exactly the URLs shown.
update(&mut state, Action::TogglePodcastShare);
podcasts::share_prepared(
&mut state,
podcast_id(),
"Show".into(),
Ok(check(true, false)),
);
let popup = state.popup.take().unwrap();
assert_eq!(
podcasts::share_confirmation_key(&mut state, popup, KeyCode::Enter),
set_shared(true, Some(urls()))
);
assert!(state.podcasts.share_busy.contains(&podcast_id()));
assert_eq!(
podcasts::share_set(&mut state, podcast_id(), "Show".into(), true, Ok(())),
Some(Effect::PodcastsReload)
);
assert!(state.podcasts.share_busy.is_empty());
}
#[test]
fn stopping_sharing_needs_no_dialog_and_a_held_publication_asks_again() {
let mut state = ready(vec![shared_row()]);
assert_eq!(
update(&mut state, Action::TogglePodcastShare),
set_shared(false, None)
);
state
.podcasts
.publication
.podcasts
.insert(podcast_id(), Publication::Published);
let effect = podcasts::share_set(&mut state, podcast_id(), "Show".into(), false, Ok(()));
assert_eq!(effect, Some(Effect::PodcastsReload));
assert!(state.podcasts.publication.podcasts.is_empty());
assert!(state.podcasts.publication.unrevoked.contains(&podcast_id()));
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("private again"))
);
// The federation is off (since the start, or the app was restarted
// since the card was published): no pass knows whether a card from
// an earlier session is live, so one that was shared counts as not
// revoked yet, for share-off and unsubscribe alike.
for discovery in [
Discovery::Off("federation is off".into()),
Discovery::Starting,
] {
let mut state = ready(vec![shared_row()]);
state.podcasts.publication.discovery = discovery.clone();
podcasts::share_set(&mut state, podcast_id(), "Show".into(), false, Ok(()));
assert!(state.podcasts.publication.unrevoked.contains(&podcast_id()));
let mut state = ready(vec![shared_row()]);
state.podcasts.publication.discovery = discovery.clone();
podcasts::unsubscribed(&mut state, podcast_id(), "Show".into(), Ok(()));
assert!(state.podcasts.publication.unrevoked.contains(&podcast_id()));
// A podcast that was not shared has no card to revoke.
let mut state = ready(vec![fx::row("Show", 0, 1, 0)]);
state.podcasts.publication.discovery = discovery;
podcasts::unsubscribed(&mut state, podcast_id(), "Show".into(), Ok(()));
assert!(state.podcasts.publication.unrevoked.is_empty());
}
// Shared (for example from another device) but held back here: the
// key asks for this device's confirmation instead of unsharing.
let mut state = ready(vec![shared_row()]);
state.podcasts.publication.podcasts.insert(
podcast_id(),
Publication::HeldBack(check(true, false).warnings),
);
assert!(matches!(
update(&mut state, Action::TogglePodcastShare),
Some(Effect::PodcastPrepareShare { .. })
));
podcasts::share_prepared(
&mut state,
podcast_id(),
"Show".into(),
Ok(check(true, false)),
);
assert!(matches!(
&state.popup,
Some(Popup::ConfirmPodcastShare {
already_shared: true,
..
})
));
let popup = state.popup.take().unwrap();
assert_eq!(
podcasts::share_confirmation_key(&mut state, popup, KeyCode::Char('x')),
set_shared(false, None)
);
// Or confirms it (sharing is already on; the confirmation is new).
state.podcasts.share_busy.clear();
podcasts::share_prepared(
&mut state,
podcast_id(),
"Show".into(),
Ok(check(true, false)),
);
let popup = state.popup.take().unwrap();
assert_eq!(
podcasts::share_confirmation_key(&mut state, popup, KeyCode::Char('y')),
set_shared(true, Some(urls()))
);
// Held without warnings any more: just reconcile again.
state.podcasts.share_busy.clear();
assert_eq!(
podcasts::share_prepared(
&mut state,
podcast_id(),
"Show".into(),
Ok(check(false, false))
),
Some(Effect::PodcastPublicationSync)
);
}
#[test]
fn share_errors_and_publication_failures_are_shown() {
let mut state = ready(vec![fx::row("Show", 0, 1, 0)]);
update(&mut state, Action::TogglePodcastShare);
assert_eq!(
podcasts::share_prepared(&mut state, podcast_id(), "Show".into(), Err("boom".into())),
None
);
assert!(state.podcasts.share_busy.is_empty());
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("cannot share: boom"))
);
assert_eq!(
podcasts::share_set(
&mut state,
podcast_id(),
"Show".into(),
true,
Err("db".into())
),
None
);
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("cannot change sharing: db"))
);
state.status_message = None;
let mut report = PublicationReport {
discovery: Discovery::Running { peers: 3 },
..PublicationReport::default()
};
report
.podcasts
.insert(podcast_id(), Publication::Failed("signing failed".into()));
podcasts::publication_reported(&mut state, report.clone());
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("cannot publish \"Show\": signing failed"))
);
// The same failure again is not repeated in the status bar.
state.status_message = None;
podcasts::publication_reported(&mut state, report);
assert_eq!(state.status_message, None);
assert_eq!(
state.podcasts.publication.discovery,
Discovery::Running { peers: 3 }
);
}
#[test]
fn share_actions_outside_the_tab_only_explain() {
let mut state = fx::ready_state(vec![fx::row("Show", 0, 1, 0)]);
state.active_tab = Tab::Global;
assert_eq!(update(&mut state, Action::TogglePodcastShare), None);
assert!(state.podcasts.share_busy.is_empty());
let mut opening = AppState {
active_tab: Tab::Podcasts,
..AppState::default()
};
assert_eq!(update(&mut opening, Action::TogglePodcastShare), None);
}
}
/// Podcast episodes in the shared queue: identity by episode id (never the
@@ -2220,3 +2563,267 @@ mod podcast_queue {
assert!(crate::app::update::podcasts::synced(&mut opening, Vec::new(), true).is_empty());
}
}
mod podcast_discovery {
use crossterm::event::KeyCode;
use music_dht::podcast::{FeedUrl, PodcastId};
use music_dht::podcast_dht::ClaimedFeedUrl;
use super::*;
use crate::app::podcast_fixtures::{self as fx, podcast_id};
use crate::app::state::{Loadable, PODCAST_ACTION_ROWS, Popup};
use crate::app::update::podcast_discovery::{card_key, preview_loaded};
use crate::podcasts::discovery::{FeedPreview, PodcastHit, test_hit};
const ORIGIN: &str = "https://feeds.example.test/origin.xml";
const CLAIMED: &str = "https://elsewhere.example.test/claimed.xml";
/// A card whose publisher also claims the feed moved elsewhere.
fn claimed_hit() -> PodcastHit {
let mut hit = test_hit(ORIGIN, "Rust Radio");
let claimed = FeedUrl::parse(CLAIMED).unwrap();
hit.claimed_feed_urls = vec![ClaimedFeedUrl {
feed_url: claimed.clone(),
publishers: hit.publishers.clone(),
}];
hit.card.feed_url = claimed;
hit.card.id_feed_url = Some(FeedUrl::parse(ORIGIN).unwrap());
PodcastHit::new(hit)
}
/// The search view with one local track, a federated artist and the
/// given podcast hits; the podcast store is ready with `rows`.
fn search_state(rows: Vec<crate::app::state::PodcastRow>, hits: Vec<PodcastHit>) -> AppState {
let mut state = fx::ready_state(rows);
state.active_tab = Tab::Global;
state.search.query = "rust radio".into();
state.search.results = Some(crate::library::models::SearchResults {
tracks: vec![test_track(1)],
..Default::default()
});
state.search.fed_artists = vec![crate::federation::FedArtistHit {
name: "Rust Radio Band".into(),
peers: 2,
}];
state.search.fed_podcasts = hits;
state.global.stack.push(GlobalView::Search { cursor: 0 });
state
}
fn open_card_at(state: &mut AppState, cursor: usize) -> Popup {
if let Some(GlobalView::Search { cursor: at }) = state.global.stack.last_mut() {
*at = cursor;
}
assert_eq!(update(state, Action::Select), None);
state.popup.take().expect("the card opens")
}
#[test]
fn the_cursor_reaches_podcast_hits_after_the_music_results() {
let mut state = search_state(Vec::new(), vec![claimed_hit()]);
assert_eq!(state.search.total_len(), 3);
update(&mut state, Action::SelectLast);
assert!(matches!(
state.global.stack.last(),
Some(GlobalView::Search { cursor: 2 })
));
// Enter on a podcast opens its card; nothing is played or queued.
assert_eq!(update(&mut state, Action::Select), None);
assert!(state.player.queue.is_empty());
assert!(matches!(
&state.popup,
Some(Popup::PodcastCard { hit, preview: None, scroll: 0, .. }) if hit.title() == "Rust Radio"
));
// The music rows keep their behavior.
let mut state = search_state(Vec::new(), vec![claimed_hit()]);
assert_eq!(
update(&mut state, Action::Select),
Some(Effect::PlayCurrent)
);
}
#[test]
fn subscribing_from_a_card_uses_the_origin_url_only() {
let mut state = search_state(Vec::new(), vec![claimed_hit()]);
let popup = open_card_at(&mut state, 2);
let effect = card_key(&mut state, popup, KeyCode::Enter);
let Some(Effect::PodcastSubscribeFromCard(hit)) = effect else {
panic!("expected a subscription, got {effect:?}");
};
assert_eq!(hit.feed_url.as_str(), ORIGIN);
assert_eq!(
hit.podcast_id,
PodcastId::from_feed_url(&FeedUrl::parse(ORIGIN).unwrap())
);
assert!(state.podcasts.subscribing);
assert!(matches!(state.popup, Some(Popup::PodcastCard { .. })));
// One subscription at a time.
let popup = state.popup.take().unwrap();
assert_eq!(card_key(&mut state, popup, KeyCode::Char('s')), None);
assert!(
state
.status_message
.as_deref()
.is_some_and(|message| message.contains("already being added"))
);
// Esc closes without anything else.
state.podcasts.subscribing = false;
let popup = state.popup.take().unwrap();
assert_eq!(card_key(&mut state, popup, KeyCode::Esc), None);
assert!(state.popup.is_none());
// Without a podcast store nothing is requested.
let mut state = search_state(Vec::new(), vec![claimed_hit()]);
state.podcasts.store = crate::app::state::PodcastStoreStatus::Opening;
let popup = open_card_at(&mut state, 2);
assert_eq!(card_key(&mut state, popup, KeyCode::Enter), None);
assert!(!state.podcasts.subscribing);
}
#[test]
fn already_subscribed_cards_open_the_podcast_instead() {
// Subscribed under the card's own id.
let mut hit = test_hit("https://example.test/feed.xml", "Test Show");
hit.card.episode_count = None;
let mut state = search_state(
vec![fx::row("Test Show", 0, 3, 0)],
vec![PodcastHit::new(hit)],
);
assert!(state.podcasts.subscribed_to(&state.search.fed_podcasts[0]));
let popup = open_card_at(&mut state, 2);
let effect = card_key(&mut state, popup, KeyCode::Enter);
assert!(
matches!(&effect, Some(Effect::PodcastLoadEpisodes { query, .. }) if query.podcast_id == podcast_id()),
"{effect:?}"
);
assert_eq!(state.active_tab, Tab::Podcasts);
assert_eq!(state.podcasts.selected, PODCAST_ACTION_ROWS);
assert!(state.popup.is_none());
assert!(!state.podcasts.subscribing);
// Subscribed under another id: the card's origin URL is a feed
// alias of that podcast here (resolved by the search task).
let mut aliased = claimed_hit();
assert_ne!(aliased.hit.podcast_id, podcast_id());
aliased.local_id = podcast_id();
let mut state = search_state(vec![fx::row("Test Show", 0, 3, 0)], vec![aliased]);
assert!(state.podcasts.subscribed_to(&state.search.fed_podcasts[0]));
let popup = open_card_at(&mut state, 2);
let effect = card_key(&mut state, popup, KeyCode::Enter);
assert!(
!matches!(effect, Some(Effect::PodcastSubscribeFromCard(_))),
"{effect:?}"
);
assert_eq!(state.active_tab, Tab::Podcasts);
// Subscribed under the newer address the card's feed moved to:
// known once the feed was read (`e`), then Enter opens it too.
let unknown = claimed_hit();
assert!(!unknown.ids().contains(&&podcast_id()));
let mut state = search_state(vec![fx::row("Test Show", 0, 3, 0)], vec![unknown]);
assert!(!state.podcasts.subscribed_to(&state.search.fed_podcasts[0]));
let popup = open_card_at(&mut state, 2);
let card_id = state.search.fed_podcasts[0].hit.podcast_id.clone();
assert!(matches!(
card_key(&mut state, popup, KeyCode::Char('e')),
Some(Effect::PodcastPreview { .. })
));
preview_loaded(
&mut state,
card_id,
Ok(Box::new(FeedPreview {
title: "Test Show".into(),
episode_count: 1,
seasons: Vec::new(),
episodes: Vec::new(),
moved_to: Some(FeedUrl::parse("https://example.test/feed.xml").unwrap()),
subscribed_as: Some(podcast_id()),
})),
);
let popup = state.popup.take().unwrap();
let effect = card_key(&mut state, popup, KeyCode::Enter);
assert!(
matches!(&effect, Some(Effect::PodcastLoadEpisodes { query, .. }) if query.podcast_id == podcast_id()),
"{effect:?}"
);
assert!(!state.podcasts.subscribing);
// Not subscribed: an unsubscribed podcast is not in the rows.
let state = search_state(Vec::new(), vec![claimed_hit()]);
assert!(!state.podcasts.subscribed_to(&state.search.fed_podcasts[0]));
}
#[test]
fn the_episode_preview_is_requested_once_and_folded_in() {
let mut state = search_state(Vec::new(), vec![claimed_hit()]);
let popup = open_card_at(&mut state, 2);
let effect = card_key(&mut state, popup, KeyCode::Char('e'));
let Some(Effect::PodcastPreview {
podcast_id: card_id,
feed_url,
}) = effect
else {
panic!("expected a preview request, got {effect:?}");
};
assert_eq!(feed_url.as_str(), ORIGIN, "never the claimed URL");
let popup = state.popup.take().unwrap();
assert_eq!(card_key(&mut state, popup, KeyCode::Char('e')), None);
assert!(matches!(
state.popup,
Some(Popup::PodcastCard {
preview: Some(Loadable::Loading),
..
})
));
// Scrolling keeps the card.
let popup = state.popup.take().unwrap();
assert_eq!(card_key(&mut state, popup, KeyCode::Down), None);
assert!(matches!(
state.popup,
Some(Popup::PodcastCard { scroll: 1, .. })
));
let feed = FeedPreview {
title: "Rust Radio".into(),
episode_count: 0,
seasons: Vec::new(),
episodes: Vec::new(),
moved_to: None,
subscribed_as: None,
};
// A preview of another card is ignored.
preview_loaded(&mut state, podcast_id(), Ok(Box::new(feed.clone())));
assert!(matches!(
state.popup,
Some(Popup::PodcastCard {
preview: Some(Loadable::Loading),
..
})
));
preview_loaded(
&mut state,
card_id.clone(),
Err("HTTP 404 Not Found".into()),
);
assert!(matches!(
state.popup,
Some(Popup::PodcastCard {
preview: Some(Loadable::Failed(_)),
..
})
));
// A failed preview may be asked again.
let popup = state.popup.take().unwrap();
assert!(matches!(
card_key(&mut state, popup, KeyCode::Char('e')),
Some(Effect::PodcastPreview { .. })
));
preview_loaded(&mut state, card_id, Ok(Box::new(feed.clone())));
assert!(matches!(
&state.popup,
Some(Popup::PodcastCard { preview: Some(Loadable::Ready(ready)), .. }) if *ready == feed
));
}
}
+9
View File
@@ -223,6 +223,10 @@ command = "CycleRepeat"
key_sequence = "shift-l"
command = "ToggleVisualizer"
[[keymaps]]
key_sequence = "shift-m"
command = "CycleVisualizerMode"
[[keymaps]]
key_sequence = "shift-h"
command = "OpenListenHistory"
@@ -319,3 +323,8 @@ context = "podcasts"
key_sequence = "b"
command = "RestartEpisode"
context = "podcasts"
[[keymaps]]
key_sequence = "shift-f"
command = "TogglePodcastShare"
context = "podcasts"
+6
View File
@@ -584,6 +584,11 @@ mod tests {
km.resolve(shift_l, KeyContext::Library),
KeyResolution::Action(Action::ToggleVisualizer)
);
let shift_m = KeyCombination::new(KeyCode::Char('M'), KeyModifiers::SHIFT);
assert_eq!(
km.resolve(shift_m, KeyContext::Library),
KeyResolution::Action(Action::CycleVisualizerMode)
);
}
#[test]
@@ -904,6 +909,7 @@ mod tests {
(key!(m), Action::ToggleEpisodePlayed),
(shift('U'), Action::UnsubscribePodcast),
(key!(b), Action::RestartEpisode),
(shift('F'), Action::TogglePodcastShare),
];
for (key, action) in cases {
assert_eq!(
+79 -1
View File
@@ -142,6 +142,9 @@ struct PodcastLink {
/// Other podcast state (subscriptions, shares, feed URLs, sessions)
/// changed since the last notification.
changed: bool,
/// Whether the podcast registers are current enough to publish public
/// cards from ([`DeviceSync::podcast_registers_current`]).
registers_current: tokio::sync::watch::Sender<bool>,
}
/// Converts queue items to and from the shared wire form
@@ -844,13 +847,76 @@ impl DeviceSync {
tracing::info!(applied, "applied podcast operations received earlier");
}
self.flush_podcast_changes();
Ok(())
self.check_podcast_registers_without_peers()
}
fn podcast_store(&self) -> Option<Arc<PodcastStore>> {
lock(&self.podcasts).store.clone()
}
/// Becomes `true` once the share and subscription registers in the
/// attached podcast store are current enough to publish this device's
/// public podcast cards from, and stays `true` for the process.
///
/// A device that was closed or offline may hold a "share" decision that
/// another trusted device revoked meanwhile. Its registers count as
/// current once it exchanged sync messages (in either direction) with a
/// trusted device that syncs podcasts (protocol v4 or newer) after the
/// store was attached, or when it has no such device it can reach (no
/// device in its group, only older ones, or none with an address): then
/// nobody can bring it a newer decision. Until then
/// `podcasts::publication` only revokes and publishes nothing.
pub fn podcast_registers_current(&self) -> tokio::sync::watch::Receiver<bool> {
lock(&self.podcasts).registers_current.subscribe()
}
fn set_podcast_registers_current(&self, why: &str) {
let link = lock(&self.podcasts);
let opened = link.registers_current.send_if_modified(|current| {
let opened = !*current;
*current = true;
opened
});
if opened {
tracing::info!("podcast share decisions are current: {why}");
}
}
/// A sync exchange with `device_id` was applied. `store_attached`: the
/// podcast store was attached before the received state was applied, so
/// the received podcast operations and snapshot sections reached it.
fn podcast_exchange_applied(&self, device_id: &str, store_attached: bool) -> Result<()> {
if store_attached
&& music_dht::device_sync::supports_podcasts(self.peer_protocol_version(device_id)?)
{
self.set_podcast_registers_current("synced with a trusted device");
}
Ok(())
}
/// Marks the podcast registers current when the store is attached and
/// no trusted device that syncs podcasts can be reached to bring newer
/// decisions (see [`DeviceSync::podcast_registers_current`]).
fn check_podcast_registers_without_peers(&self) -> Result<()> {
{
let link = lock(&self.podcasts);
if link.store.is_none() || *link.registers_current.borrow() {
return Ok(());
}
}
for device in self.active_remote_devices()? {
if !device.endpoint_ticket.trim().is_empty()
&& music_dht::device_sync::supports_podcasts(
self.peer_protocol_version(&device.device_id)?,
)
{
return Ok(());
}
}
self.set_podcast_registers_current("no trusted device syncs podcasts");
Ok(())
}
/// Merges a received podcast operation into the podcast store, or keeps
/// it for [`DeviceSync::attach_podcast_store`]. A podcast store problem
/// never fails music sync: the operation stays in the log either way.
@@ -1097,7 +1163,9 @@ impl DeviceSync {
}
}
self.apply_device_profiles(&devices, Some(&invite.device_id))?;
let store_attached = self.podcast_store().is_some();
self.apply_received(snapshot, ops)?;
self.podcast_exchange_applied(&invite.device_id, store_attached)?;
self.record_local_op(SyncOpPayload::DeviceTrusted {
target_device_id: invite.device_id.clone(),
})?;
@@ -1600,7 +1668,9 @@ impl DeviceSync {
if let Some(playback) = playback {
self.apply_playback_snapshot(&device.device_id, playback)?;
}
let store_attached = self.podcast_store().is_some();
self.apply_received(snapshot, ops)?;
self.podcast_exchange_applied(&device.device_id, store_attached)?;
self.note_peer_vector(&device.device_id, &vector)?;
self.mark_seen(&device.device_id, Some(peer.to_string()))?;
self.set_last_sync(Some(format!("synced {}", short_id(&device.device_id))))?;
@@ -3404,6 +3474,10 @@ pub async fn sync_loop(
if let Err(err) = sync.gc_tombstones() {
tracing::debug!("personal sync cleanup failed: {err:#}");
}
// A device removed from the group is no longer waited for.
if let Err(err) = sync.check_podcast_registers_without_peers() {
tracing::debug!("podcast sync state not checked: {err:#}");
}
}
Some(completed) = polls.join_next_with_id(), if !polls.is_empty() => {
let (task, result) = match completed {
@@ -3646,7 +3720,9 @@ async fn handle_pair_request(
if let Some(playback) = playback {
sync.apply_playback_snapshot(&profile.device_id, playback)?;
}
let store_attached = sync.podcast_store().is_some();
sync.apply_received(snapshot, ops)?;
sync.podcast_exchange_applied(&profile.device_id, store_attached)?;
sync.note_peer_vector(&profile.device_id, &vector)?;
{
let conn = lock(&sync.conn);
@@ -3740,7 +3816,9 @@ async fn handle_hello(
if let Some(playback) = playback {
sync.apply_playback_snapshot(&profile.device_id, playback)?;
}
let store_attached = sync.podcast_store().is_some();
sync.apply_received(snapshot, ops)?;
sync.podcast_exchange_applied(&profile.device_id, store_attached)?;
sync.note_peer_vector(&profile.device_id, &vector)?;
sync.mark_seen(&profile.device_id, Some(stream.peer_id.to_string()))?;
sync.set_last_sync(Some(format!("synced {}", short_id(&profile.device_id))))?;
+103
View File
@@ -111,7 +111,10 @@ pub(super) fn receive(to: &DeviceSync, json: &str) {
to.apply_playback_snapshot(&profile.device_id, playback)
.unwrap();
}
let store_attached = to.podcast_store().is_some();
to.apply_received(snapshot, ops).unwrap();
to.podcast_exchange_applied(&profile.device_id, store_attached)
.unwrap();
to.note_peer_vector(&profile.device_id, &vector).unwrap();
}
@@ -441,6 +444,83 @@ fn operations_received_before_the_store_opens_are_applied_when_it_does() {
assert_eq!(pending, 0);
}
/// Trusts `b` on `a` and the other way round like [`pair`], with an
/// address for each, so either can sync with the other.
fn pair_reachable(a: &Device, b: &Device) {
b.sync
.set_group_id(&a.sync.ensure_identity().unwrap().group_id)
.unwrap();
for (left, right) in [(a, b), (b, a)] {
let mut profile = right.sync.own_profile("").unwrap();
profile.endpoint_ticket = format!("ticket-of-{}", right.id);
left.sync
.apply_device_profile(
&profile,
true,
VersionReport::SelfReported(Some(profile.protocol_version)),
)
.unwrap();
}
}
fn current(registers: &tokio::sync::watch::Receiver<bool>) -> bool {
*registers.borrow()
}
/// Interop scenario 7c (a device restarted with a "share" decision another
/// device revoked meanwhile): the publication reconciler waits for
/// `podcast_registers_current`, which needs a sync with a device of the
/// group that syncs podcasts, unless there is none to wait for.
#[test]
fn podcast_registers_are_current_after_a_sync_with_the_group() {
// A device alone: current as soon as its store is attached.
let alone = device_with_store(Arc::new(PodcastStore::open_in_memory().unwrap()), false);
let registers = alone.sync.podcast_registers_current();
assert!(!current(&registers), "not before the store is attached");
alone
.sync
.attach_podcast_store(Arc::clone(&alone.store))
.unwrap();
assert!(current(&registers));
// Only an older device (v3) in the group: it never brings podcast
// decisions, so it is not waited for.
let with_old = device_with_store(Arc::new(PodcastStore::open_in_memory().unwrap()), false);
trust_old_device(&with_old);
with_old
.sync
.attach_podcast_store(Arc::clone(&with_old.store))
.unwrap();
assert!(current(&with_old.sync.podcast_registers_current()));
// B restarts in a group with A: it waits for a sync with A.
let a = device();
let b = device_with_store(Arc::new(PodcastStore::open_in_memory().unwrap()), false);
pair_reachable(&a, &b);
let registers = b.sync.podcast_registers_current();
// A sync that reaches B before its store is attached leaves the
// podcast snapshot sections out: it does not count.
deliver(&a, &b);
b.sync.attach_podcast_store(Arc::clone(&b.store)).unwrap();
assert!(!current(&registers), "A can be reached: B waits for it");
b.sync.check_podcast_registers_without_peers().unwrap();
assert!(!current(&registers));
// A's sync with B (`handle_hello`; B's own `sync_device` does the same
// with A's response) now merges A's decisions into the store.
deliver(&a, &b);
assert!(current(&registers));
// A device of the group removed meanwhile is no longer waited for.
let d = device_with_store(Arc::new(PodcastStore::open_in_memory().unwrap()), false);
pair_reachable(&a, &d);
d.sync.attach_podcast_store(Arc::clone(&d.store)).unwrap();
let registers = d.sync.podcast_registers_current();
assert!(!current(&registers));
d.sync.revoke_device(&a.id).unwrap();
d.sync.check_podcast_registers_without_peers().unwrap();
assert!(current(&registers));
}
#[test]
fn podcast_operations_are_relayed_to_devices_that_were_not_online() {
let a = device();
@@ -1161,6 +1241,29 @@ fn only_bare_music_items_from_old_devices_count_as_echoed_placeholders() {
/// the Logs tab) never prints them.
#[test]
fn podcast_payloads_are_not_written_to_the_debug_log() {
// Tracing caches callsite interest globally. Other tests can change it
// while this thread-local subscriber is active, making an expected
// event disappear. Keep the real log assertions in an isolated process.
const ISOLATED: &str = "FURUMI_TEST_ISOLATED_PODCAST_LOG";
if std::env::var_os(ISOLATED).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"devices::podcast_sync_tests::podcast_payloads_are_not_written_to_the_debug_log",
"--nocapture",
])
.env(ISOLATED, "1")
.output()
.unwrap();
assert!(
output.status.success(),
"isolated log capture failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
return;
}
use std::io::Write;
use tracing_subscriber::Layer as _;
use tracing_subscriber::layer::SubscriberExt as _;
+23
View File
@@ -482,6 +482,29 @@ fn test_sync() -> DeviceSync {
#[test]
fn device_identity_has_one_coordinator_across_installation_paths() {
// Other tests spawn processes in parallel. A child can briefly inherit
// this test's locked file before exec closes it, delaying release after
// drop(first). Keep the lock lifecycle in its own test process.
const ISOLATED: &str = "FURUMI_TEST_ISOLATED_IDENTITY_LOCK";
if std::env::var_os(ISOLATED).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"devices::tests::device_identity_has_one_coordinator_across_installation_paths",
"--nocapture",
])
.env(ISOLATED, "1")
.output()
.unwrap();
assert!(
output.status.success(),
"isolated identity lock test failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
return;
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sync.sqlite3");
let first = acquire_identity_lock(&path).unwrap();
+59 -13
View File
@@ -10,6 +10,7 @@ use music_dht::capabilities::{
CAPABILITIES_PROTOCOL_VERSION, CapabilityManifest, CapabilityMessage, read_message,
write_message,
};
use music_dht::podcast_dht::PodcastDht;
use music_dht::{ByteStream, EndpointId, MusicDhtService, StreamAcceptor};
const PROBE_INTERVAL: Duration = Duration::from_secs(30);
@@ -30,8 +31,10 @@ pub struct NewerProtocol {
}
impl ProtocolVersions {
pub fn snapshot(observed: &ObservedVersions) -> Self {
let local = local_manifest().protocols;
/// `podcast_dht`: whether this node runs the podcast-discovery overlay
/// (it is advertised only then).
pub fn snapshot(observed: &ObservedVersions, podcast_dht: bool) -> Self {
let local = local_manifest(podcast_dht).protocols;
let observed_versions = lock(&observed.versions).clone();
let newer = observed_versions
.iter()
@@ -59,27 +62,35 @@ pub struct ObservedVersions {
peers: Mutex<BTreeMap<String, String>>,
}
fn local_manifest() -> CapabilityManifest {
CapabilityManifest::frid("furumi", env!("CARGO_PKG_VERSION"))
.with_protocol("audio", super::audio::AUDIO_PROTOCOL_VERSION)
/// This node's manifest. The podcast-discovery overlay is opt-in in FRID:
/// it is advertised only when this node serves it (`podcast_dht`), so
/// peers never dial an overlay that failed to open here.
fn local_manifest(podcast_dht: bool) -> CapabilityManifest {
let manifest = CapabilityManifest::frid("furumi", env!("CARGO_PKG_VERSION"))
.with_protocol("audio", super::audio::AUDIO_PROTOCOL_VERSION);
if podcast_dht {
manifest.with_podcast_dht()
} else {
manifest
}
}
pub async fn serve(mut acceptor: StreamAcceptor) {
pub async fn serve(mut acceptor: StreamAcceptor, podcast_dht: bool) {
while let Some(stream) = acceptor.accept().await {
tokio::spawn(async move {
if let Err(error) = serve_one(stream).await {
if let Err(error) = serve_one(stream, podcast_dht).await {
tracing::debug!("capability stream failed: {error:#}");
}
});
}
}
async fn serve_one(mut stream: ByteStream) -> Result<()> {
async fn serve_one(mut stream: ByteStream, podcast_dht: bool) -> Result<()> {
let response = match read_message(&mut stream).await? {
CapabilityMessage::Get {
version: CAPABILITIES_PROTOCOL_VERSION,
} => CapabilityMessage::Manifest {
manifest: local_manifest(),
manifest: local_manifest(podcast_dht),
},
CapabilityMessage::Get { version } => CapabilityMessage::Error {
message: format!("unsupported capability protocol {version}"),
@@ -94,7 +105,14 @@ async fn serve_one(mut stream: ByteStream) -> Result<()> {
Ok(())
}
pub async fn probe_loop(service: Arc<MusicDhtService>, observed: Arc<ObservedVersions>) {
/// Polls the manifests of known peers. With the podcast-discovery overlay
/// running, every manifest is handed to `PodcastDht::note_peer_capabilities`,
/// which stops dialing peers that do not serve the overlay.
pub async fn probe_loop(
service: Arc<MusicDhtService>,
observed: Arc<ObservedVersions>,
podcast_dht: Option<Arc<PodcastDht>>,
) {
let mut interval = tokio::time::interval(PROBE_INTERVAL);
loop {
interval.tick().await;
@@ -109,7 +127,8 @@ pub async fn probe_loop(service: Arc<MusicDhtService>, observed: Arc<ObservedVer
)
.collect::<std::collections::BTreeSet<_>>();
for peer in peers {
if let Err(error) = probe_peer(&service, peer, &observed).await {
if let Err(error) = probe_peer(&service, peer, &observed, podcast_dht.as_deref()).await
{
tracing::trace!(%peer, "peer capability probe unavailable: {error:#}");
}
}
@@ -120,6 +139,7 @@ async fn probe_peer(
service: &MusicDhtService,
peer: EndpointId,
observed: &ObservedVersions,
podcast_dht: Option<&PodcastDht>,
) -> Result<()> {
let mut stream = service.open_stream(peer, CAPABILITIES_ALPN).await?;
write_message(
@@ -137,6 +157,11 @@ async fn probe_peer(
anyhow::bail!("peer did not return a capability manifest");
};
manifest.validate()?;
if let Some(podcast_dht) = podcast_dht
&& let Err(error) = podcast_dht.note_peer_capabilities(peer, &manifest).await
{
tracing::debug!(%peer, "podcast DHT capability note failed: {error:#}");
}
{
let mut versions = lock(&observed.versions);
for (id, version) in manifest.protocols {
@@ -162,7 +187,7 @@ mod tests {
#[test]
fn local_manifest_lists_every_player_protocol() {
let manifest = local_manifest();
let manifest = local_manifest(true);
for id in [
"federation_net",
"ticket",
@@ -174,10 +199,31 @@ mod tests {
"similarity_dht",
"device_sync",
"jam",
"podcast_dht",
] {
assert!(manifest.protocols.contains_key(id), "missing {id}");
}
manifest.validate().unwrap();
assert!(manifest.supports_podcast_dht());
}
#[test]
fn podcast_discovery_is_advertised_only_when_it_runs() {
let manifest = local_manifest(false);
assert!(!manifest.supports_podcast_dht());
assert!(!manifest.protocols.contains_key("podcast_dht"));
manifest.validate().unwrap();
let observed = ObservedVersions::default();
assert!(
!ProtocolVersions::snapshot(&observed, false)
.local
.contains_key("podcast_dht")
);
assert!(
ProtocolVersions::snapshot(&observed, true)
.local
.contains_key("podcast_dht")
);
}
#[test]
@@ -185,7 +231,7 @@ mod tests {
let observed = ObservedVersions::default();
lock(&observed.versions).insert("music_dht".to_string(), 99);
lock(&observed.versions).insert("jam".to_string(), crate::jam::PROTOCOL_VERSION);
let snapshot = ProtocolVersions::snapshot(&observed);
let snapshot = ProtocolVersions::snapshot(&observed, true);
assert_eq!(snapshot.newer.len(), 1);
assert_eq!(snapshot.newer[0].id, "music_dht");
}
+113 -18
View File
@@ -25,6 +25,7 @@ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use music_dht::podcast_dht::{PODCAST_DHT_ALPN, PodcastDht};
use music_dht::similarity_dht::SimilarityDht;
use music_dht::similarity_lsh::SIMILARITY_DHT_ALPN;
use music_dht::{
@@ -44,6 +45,10 @@ pub use capabilities::ProtocolVersions;
pub use catalog::{CATALOG_ALPN, FedAppearsOn, FedArtistCard, FedCardTrack, FedRelease};
pub use similarity::SIMILARITY_ALPN;
/// Cache of the public podcast-discovery overlay (`music_dht::podcast_dht`),
/// next to the similarity overlay's cache in the federation data directory.
pub const PODCAST_DHT_CACHE_FILE: &str = "podcast-dht.sqlite3";
/// How often the published library is re-synchronized with the local index.
const SYNC_INTERVAL: Duration = Duration::from_secs(60);
/// How often the application checks whether the shared transport needs a
@@ -412,6 +417,9 @@ pub struct NetworkLibrarySource {
struct Running {
service: Arc<MusicDhtService>,
similarity_dht: Arc<SimilarityDht>,
/// Public podcast discovery; `None` when its cache could not be opened
/// (discovery is then off and the overlay is not advertised).
podcast_dht: Option<Arc<PodcastDht>>,
network_name: String,
network_id: NetworkId,
tasks: Vec<tokio::task::JoinHandle<()>>,
@@ -438,6 +446,9 @@ pub struct Federation {
last_error: std::sync::Mutex<Option<String>>,
transport_stats: Arc<TransportStats>,
observed_protocols: Arc<capabilities::ObservedVersions>,
/// The running podcast-discovery overlay, for the podcast publication
/// reconciler (`podcasts::publication`); `None` while federation is off.
podcast_dht: tokio::sync::watch::Sender<Option<Arc<PodcastDht>>>,
}
#[derive(Debug, Clone)]
@@ -572,9 +583,17 @@ impl Federation {
last_error: std::sync::Mutex::new(initial_error),
transport_stats: Arc::new(TransportStats::default()),
observed_protocols: Arc::new(capabilities::ObservedVersions::default()),
podcast_dht: tokio::sync::watch::Sender::new(None),
})
}
/// Follows the podcast-discovery overlay of the running node: `Some`
/// while federation runs with the overlay, `None` otherwise. Every
/// (re)start publishes a new value.
pub fn podcast_dht(&self) -> tokio::sync::watch::Receiver<Option<Arc<PodcastDht>>> {
self.podcast_dht.subscribe()
}
pub fn settings(&self) -> FedSettings {
lock(&self.settings).clone()
}
@@ -730,6 +749,7 @@ impl Federation {
} else if recovery_only {
return Ok(false);
}
self.podcast_dht.send_replace(None);
stop_running(guard.take()).await;
} else if recovery_only {
tracing::warn!(network = %network_name, "retrying stopped federation service");
@@ -756,6 +776,8 @@ impl Federation {
.stream_protocol(crate::jam::JAM_ALPN)
// Signed LSH summaries form their own upgrade-safe DHT overlay.
.schema_independent_stream_protocol(SIMILARITY_DHT_ALPN)
// Public cards of podcasts the user chose to share.
.schema_independent_stream_protocol(PODCAST_DHT_ALPN)
// Informational application/protocol versions.
.schema_independent_stream_protocol(capabilities::CAPABILITIES_ALPN)
.build()
@@ -788,6 +810,18 @@ impl Federation {
Arc::clone(&self.similarity),
Arc::clone(&self.library),
));
// Public podcast discovery: serving, bootstrap, republishing and
// expiry run here; what to publish is decided by the podcast
// publication reconciler from the user's share decisions.
let mut podcast_dht_tasks = Vec::new();
let podcast_dht =
open_podcast_dht(&service, &self.data_dir)
.await
.map(|(dht, acceptor)| {
podcast_dht_tasks.push(tokio::spawn(Arc::clone(&dht).serve(acceptor)));
podcast_dht_tasks.push(tokio::spawn(Arc::clone(&dht).maintenance()));
dht
});
// Drain DHT events into the log; the channel is bounded.
let event_task = tokio::spawn(async move {
@@ -861,33 +895,41 @@ impl Federation {
let capabilities_acceptor = service
.stream_acceptor(capabilities::CAPABILITIES_ALPN)
.map_err(|err| anyhow::anyhow!("failed to take capabilities acceptor: {err}"))?;
let capabilities_serve_task = tokio::spawn(capabilities::serve(capabilities_acceptor));
let capabilities_serve_task = tokio::spawn(capabilities::serve(
capabilities_acceptor,
podcast_dht.is_some(),
));
let capabilities_probe_task = tokio::spawn(capabilities::probe_loop(
Arc::clone(&service),
Arc::clone(&self.observed_protocols),
podcast_dht.clone(),
));
let mut tasks = podcast_dht_tasks;
tasks.extend([
event_task,
sync_task,
audio_task,
catalog_task,
similarity_task,
device_sync_task,
device_tick_task,
jam_serve_task,
jam_poll_task,
capabilities_serve_task,
capabilities_probe_task,
similarity_dht_serve_task,
similarity_dht_maintenance_task,
similarity_dht_sync_task,
]);
self.podcast_dht.send_replace(podcast_dht.clone());
*guard = Some(Running {
service,
similarity_dht,
podcast_dht,
network_name,
network_id,
tasks: vec![
event_task,
sync_task,
audio_task,
catalog_task,
similarity_task,
device_sync_task,
device_tick_task,
jam_serve_task,
jam_poll_task,
capabilities_serve_task,
capabilities_probe_task,
similarity_dht_serve_task,
similarity_dht_maintenance_task,
similarity_dht_sync_task,
],
tasks,
});
self.set_error(None);
Ok(true)
@@ -895,6 +937,7 @@ impl Federation {
async fn stop(&self) {
let mut guard = self.running.lock().await;
self.podcast_dht.send_replace(None);
stop_running(guard.take()).await;
}
@@ -1088,7 +1131,12 @@ impl Federation {
recovery_count: self.recovery_count.load(Ordering::Relaxed),
last_sync: lock(&self.last_sync).clone(),
last_error: lock(&self.last_error).clone(),
protocols: ProtocolVersions::snapshot(&self.observed_protocols),
protocols: ProtocolVersions::snapshot(
&self.observed_protocols,
guard
.as_ref()
.is_some_and(|running| running.podcast_dht.is_some()),
),
..FedStatus::default()
};
if let Some(running) = guard.as_ref() {
@@ -1214,6 +1262,10 @@ impl Federation {
/// Searches the federated network: matching tracks plus the artists a
/// card can be assembled for (from artist records and from the artist
/// names of matching tracks/releases).
///
/// Public podcast cards are searched separately
/// ([`Federation::search_podcasts`]), so the music results never wait
/// for the discovery overlay.
pub async fn search(&self, query: &str) -> Result<FedSearchResults> {
let service = self.service().await?;
let normalized = music_dht::normalize_name(query);
@@ -1309,6 +1361,24 @@ impl Federation {
Ok(FedSearchResults { artists, tracks })
}
/// Public podcast cards matching `query` in the discovery overlay
/// (explicit type `podcast`), bounded by
/// [`crate::podcasts::discovery::PODCAST_SEARCH_TIMEOUT`] including the
/// overlay's bootstrap. Empty while the overlay is not running, on an
/// error or on timeout.
pub async fn search_podcasts(
&self,
query: &str,
) -> Vec<crate::podcasts::discovery::PodcastHit> {
let podcast_dht = self.podcast_dht.borrow().clone();
crate::podcasts::discovery::search(
podcast_dht.as_deref(),
query,
crate::podcasts::discovery::PODCAST_SEARCH_TIMEOUT,
)
.await
}
/// Bounded fan-out to known peers using the exact model/profile
/// fingerprint carried with the query. No DHT records are written.
pub async fn search_similar(
@@ -2804,6 +2874,31 @@ async fn similarity_route_sync_loop(
}
}
/// Opens the podcast-discovery overlay and takes its stream acceptor. A
/// failure (unreadable or newer cache, …) is logged and only disables public
/// podcast discovery: the acceptor is dropped so the overlay's ALPN refuses
/// streams, and the overlay is not advertised.
async fn open_podcast_dht(
service: &Arc<MusicDhtService>,
data_dir: &Path,
) -> Option<(Arc<PodcastDht>, music_dht::StreamAcceptor)> {
let acceptor = match service.stream_acceptor(PODCAST_DHT_ALPN) {
Ok(acceptor) => acceptor,
Err(err) => {
tracing::warn!("podcast discovery is off: cannot take its acceptor: {err}");
return None;
}
};
match PodcastDht::open(Arc::clone(service), data_dir.join(PODCAST_DHT_CACHE_FILE)).await {
Ok(dht) => Some((dht, acceptor)),
Err(err) => {
tracing::warn!("podcast discovery is off: cannot open its cache: {err}");
drop(acceptor);
None
}
}
}
async fn stop_running(running: Option<Running>) {
let Some(running) = running else { return };
for task in &running.tasks {
+32
View File
@@ -135,3 +135,35 @@ fn artist_catalog_discovery_prioritizes_matching_owners_and_bounds_fanout() {
);
}
}
/// The podcast-discovery overlay opens next to the other overlay caches; a
/// cache that cannot be opened only turns discovery off.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn podcast_discovery_opens_or_turns_itself_off() {
async fn service(dir: &Path) -> Arc<MusicDhtService> {
let config = MusicDhtConfig::builder()
.data_dir(dir)
.network_id(NetworkId::from_name("furumi-tui-podcast-dht-open-test"))
.schema_independent_stream_protocol(PODCAST_DHT_ALPN)
.build()
.unwrap();
let (service, mut events) = MusicDhtService::start(config).await.unwrap();
tokio::spawn(async move { while events.recv().await.is_some() {} });
Arc::new(service)
}
let ok_dir = tempfile::tempdir().unwrap();
let ok = service(ok_dir.path()).await;
let opened = open_podcast_dht(&ok, ok_dir.path()).await;
assert!(opened.is_some());
assert!(ok_dir.path().join(PODCAST_DHT_CACHE_FILE).is_file());
drop(opened);
ok.shutdown().await.unwrap();
// A directory where the cache file belongs cannot be opened as SQLite.
let broken_dir = tempfile::tempdir().unwrap();
std::fs::create_dir(broken_dir.path().join(PODCAST_DHT_CACHE_FILE)).unwrap();
let broken = service(broken_dir.path()).await;
assert!(open_podcast_dht(&broken, broken_dir.path()).await.is_none());
broken.shutdown().await.unwrap();
}
+265 -15
View File
@@ -1,10 +1,12 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicI16, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::time::Duration;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use rodio::source::SeekError;
use rodio::{ChannelCount, Sample, SampleRate, Source};
use super::spectrum::{Meter, PCM_SAMPLES, StereoReading};
const LEVEL_SCALE: f32 = 1_000_000.0;
const SCOPE_SAMPLES: usize = 256;
const SCOPE_SAMPLE_SCALE: f32 = i16::MAX as f32;
@@ -20,6 +22,26 @@ pub struct AudioAnalysisSnapshot {
pub treble: f64,
pub beat: f64,
pub scope: Vec<f64>,
/// Third-octave band levels (see `spectrum::BAND_CENTERS_HZ`), 0.0..1.0
/// over `spectrum::FLOOR_DB`..0 dBFS, with analyzer ballistics.
pub spectrum: Vec<f64>,
/// Per-band peak-hold markers on the same scale as `spectrum`.
pub spectrum_peaks: Vec<f64>,
/// Left/right RMS levels and held sample peaks on the same dB scale.
/// Mono sources report the same value for both channels.
pub level_l: f64,
pub level_r: f64,
pub peak_l: f64,
pub peak_r: f64,
/// RMS of the side signal (L - R) / 2 on the same scale: the floor for
/// mono sources and for stereo files that carry the same signal twice.
pub level_side: f64,
/// Whether the channels carry different signals: decided on loud windows
/// only (side within 30 dB of the louder channel), `None` until then.
pub stereo: Option<bool>,
/// Sample rate of the analyzed stream in Hz (0 when nothing has played
/// since the player last stopped).
pub sample_rate: u32,
}
#[derive(Debug)]
@@ -32,6 +54,20 @@ pub struct AnalyzerShared {
beat: AtomicU32,
scope_write: AtomicUsize,
scope: Box<[AtomicI16]>,
/// Full-rate mono history for the spectrum; written by the audio thread.
pcm_write: AtomicUsize,
pcm: Box<[AtomicI16]>,
sample_rate: AtomicU32,
/// Per-window channel levels (linear, `LEVEL_SCALE`). Peaks accumulate
/// with `fetch_max` until the meter consumes them.
rms_l: AtomicU32,
rms_r: AtomicU32,
rms_side: AtomicU32,
peak_l: AtomicU32,
peak_r: AtomicU32,
/// Ballistics and FFT state. Only snapshot readers (the UI side) lock it;
/// the audio thread never does.
meter: Mutex<Meter>,
}
impl Default for AnalyzerShared {
@@ -44,14 +80,27 @@ impl Default for AnalyzerShared {
treble: AtomicU32::new(0),
beat: AtomicU32::new(0),
scope_write: AtomicUsize::new(0),
scope: (0..SCOPE_SAMPLES)
.map(|_| AtomicI16::new(0))
.collect::<Vec<_>>()
.into_boxed_slice(),
scope: atomic_ring(SCOPE_SAMPLES),
pcm_write: AtomicUsize::new(0),
pcm: atomic_ring(PCM_SAMPLES),
sample_rate: AtomicU32::new(0),
rms_l: AtomicU32::new(0),
rms_r: AtomicU32::new(0),
rms_side: AtomicU32::new(0),
peak_l: AtomicU32::new(0),
peak_r: AtomicU32::new(0),
meter: Mutex::new(Meter::default()),
}
}
}
fn atomic_ring(len: usize) -> Box<[AtomicI16]> {
(0..len)
.map(|_| AtomicI16::new(0))
.collect::<Vec<_>>()
.into_boxed_slice()
}
impl AnalyzerShared {
pub fn clear(&self) {
self.energy.store(0, Ordering::Relaxed);
@@ -63,10 +112,37 @@ impl AnalyzerShared {
for sample in self.scope.iter() {
sample.store(0, Ordering::Relaxed);
}
self.pcm_write.store(0, Ordering::Relaxed);
for sample in self.pcm.iter() {
sample.store(0, Ordering::Relaxed);
}
for level in [
&self.rms_l,
&self.rms_r,
&self.rms_side,
&self.peak_l,
&self.peak_r,
] {
level.store(0, Ordering::Relaxed);
}
self.sequence.store(0, Ordering::Relaxed);
}
/// Like [`Self::clear`], and also forgets the sample rate: nothing is
/// loaded any more.
pub fn reset(&self) {
self.clear();
self.sample_rate.store(0, Ordering::Relaxed);
}
pub fn snapshot(&self) -> AudioAnalysisSnapshot {
self.snapshot_at(Instant::now())
}
/// Like [`Self::snapshot`] with an explicit clock, so meter ballistics are
/// deterministic in tests. Ballistics are time-based: how often callers
/// read does not change how fast bars rise or fall.
pub fn snapshot_at(&self, now: Instant) -> AudioAnalysisSnapshot {
let write = self.scope_write.load(Ordering::Relaxed);
let len = self.scope.len().max(1);
let scope = (0..self.scope.len())
@@ -76,6 +152,25 @@ impl AnalyzerShared {
})
.collect();
let sample_rate = self.sample_rate.load(Ordering::Relaxed);
let pcm_write = self.pcm_write.load(Ordering::Relaxed);
let stereo = StereoReading {
rms_l: load_norm(&self.rms_l) as f32,
rms_r: load_norm(&self.rms_r) as f32,
rms_side: load_norm(&self.rms_side) as f32,
peak_l: f64::from(self.peak_l.swap(0, Ordering::Relaxed)) as f32 / LEVEL_SCALE,
peak_r: f64::from(self.peak_r.swap(0, Ordering::Relaxed)) as f32 / LEVEL_SCALE,
};
let reading = {
let mut meter = self
.meter
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
meter.update(now, pcm_write, sample_rate, stereo, |out| {
self.copy_pcm(pcm_write, out)
})
};
AudioAnalysisSnapshot {
sequence: self.sequence.load(Ordering::Relaxed),
energy: load_norm(&self.energy),
@@ -84,6 +179,31 @@ impl AnalyzerShared {
treble: load_norm(&self.treble),
beat: load_norm(&self.beat),
scope,
spectrum: reading.spectrum,
spectrum_peaks: reading.spectrum_peaks,
level_l: reading.level_l,
level_r: reading.level_r,
peak_l: reading.peak_l,
peak_r: reading.peak_r,
level_side: reading.level_side,
stereo: reading.stereo,
sample_rate,
}
}
/// Copies the newest `out.len()` mono samples, oldest first. Slots not
/// written since the last clear read as silence.
fn copy_pcm(&self, write: usize, out: &mut [f32]) {
let len = self.pcm.len();
let count = out.len().min(len);
let start = write.wrapping_sub(count);
for (offset, slot) in out.iter_mut().enumerate() {
*slot = if offset < count && write >= count - offset {
let index = start.wrapping_add(offset) % len;
f32::from(self.pcm[index].load(Ordering::Relaxed)) / SCOPE_SAMPLE_SCALE
} else {
0.0
};
}
}
@@ -96,6 +216,22 @@ impl AnalyzerShared {
self.sequence.fetch_add(1, Ordering::Relaxed);
}
fn push_pcm(&self, sample: f32) {
let index = self.pcm_write.fetch_add(1, Ordering::Relaxed) % self.pcm.len();
let value = (sample.clamp(-1.0, 1.0) * SCOPE_SAMPLE_SCALE).round() as i16;
self.pcm[index].store(value, Ordering::Relaxed);
}
fn store_channels(&self, sample_rate: f32, rms: [f32; 3], peak: [f32; 2]) {
self.sample_rate
.store(sample_rate.round() as u32, Ordering::Relaxed);
store_norm(&self.rms_l, rms[0]);
store_norm(&self.rms_r, rms[1]);
store_norm(&self.rms_side, rms[2]);
self.peak_l.fetch_max(norm_bits(peak[0]), Ordering::Relaxed);
self.peak_r.fetch_max(norm_bits(peak[1]), Ordering::Relaxed);
}
fn push_scope(&self, sample: f32) {
let index = self.scope_write.fetch_add(1, Ordering::Relaxed) % self.scope.len();
let value = (sample.clamp(-1.0, 1.0) * SCOPE_SAMPLE_SCALE).round() as i16;
@@ -181,6 +317,12 @@ struct AnalyzerState {
mid_alpha: f32,
channel_index: usize,
frame_sum: f32,
/// Left/right of the current frame (mono feeds both).
frame_lr: [f32; 2],
channel_sq: [f32; 2],
/// Sum of squared side samples (L - R) / 2 in the current window.
side_sq: f32,
channel_peak: [f32; 2],
frame_count: usize,
window_frames: usize,
scope_counter: usize,
@@ -208,6 +350,10 @@ impl AnalyzerState {
mid_alpha: 0.0,
channel_index: 0,
frame_sum: 0.0,
frame_lr: [0.0; 2],
channel_sq: [0.0; 2],
side_sq: 0.0,
channel_peak: [0.0; 2],
frame_count: 0,
window_frames: 0,
scope_counter: 0,
@@ -252,6 +398,10 @@ impl AnalyzerState {
fn reset_filters(&mut self) {
self.channel_index = 0;
self.frame_sum = 0.0;
self.frame_lr = [0.0; 2];
self.channel_sq = [0.0; 2];
self.side_sq = 0.0;
self.channel_peak = [0.0; 2];
self.frame_count = 0;
self.scope_counter = 0;
self.low_bass = 0.0;
@@ -275,10 +425,23 @@ impl AnalyzerState {
0.0
};
self.frame_sum += sample;
// First channel is left, second right; extra channels only feed mono.
if self.channel_index < 2 {
self.frame_lr[self.channel_index] = sample;
}
self.channel_index += 1;
if self.channel_index < self.channels {
return;
}
if self.channels == 1 {
self.frame_lr[1] = self.frame_lr[0];
}
for (channel, value) in self.frame_lr.iter().enumerate() {
self.channel_sq[channel] += value * value;
self.channel_peak[channel] = self.channel_peak[channel].max(value.abs());
}
let side = (self.frame_lr[0] - self.frame_lr[1]) * 0.5;
self.side_sq += side * side;
let mono = self.frame_sum / self.channels as f32;
self.channel_index = 0;
@@ -299,6 +462,7 @@ impl AnalyzerState {
self.mid_sq += mid * mid;
self.treble_sq += treble * treble;
self.frame_count += 1;
shared.push_pcm(sample);
self.scope_counter += 1;
if self.scope_counter >= self.scope_stride {
@@ -339,10 +503,23 @@ impl AnalyzerState {
self.smooth_beat,
);
shared.store_channels(
self.sample_rate,
[
(self.channel_sq[0] / frames).sqrt(),
(self.channel_sq[1] / frames).sqrt(),
(self.side_sq / frames).sqrt(),
],
self.channel_peak,
);
self.full_sq = 0.0;
self.bass_sq = 0.0;
self.mid_sq = 0.0;
self.treble_sq = 0.0;
self.channel_sq = [0.0; 2];
self.side_sq = 0.0;
self.channel_peak = [0.0; 2];
self.frame_count = 0;
}
}
@@ -361,10 +538,11 @@ fn smooth_level(previous: f32, next: f32, attack: f32, release: f32) -> f32 {
}
fn store_norm(target: &AtomicU32, value: f32) {
target.store(
(value.clamp(0.0, 1.0) * LEVEL_SCALE).round() as u32,
Ordering::Relaxed,
);
target.store(norm_bits(value), Ordering::Relaxed);
}
fn norm_bits(value: f32) -> u32 {
(value.clamp(0.0, 1.0) * LEVEL_SCALE).round() as u32
}
fn load_norm(source: &AtomicU32) -> f64 {
@@ -384,19 +562,24 @@ mod tests {
impl TestSource {
fn sine(frames: usize, channels: u16, sample_rate: u32, frequency: f32) -> Self {
let channels_count = channels.max(1);
let mut samples = Vec::with_capacity(frames * usize::from(channels_count));
let gains = vec![1.0; usize::from(channels.max(1))];
Self::sine_gains(frames, sample_rate, frequency, &gains)
}
/// A sine with a gain per channel (one entry per channel).
fn sine_gains(frames: usize, sample_rate: u32, frequency: f32, gains: &[f32]) -> Self {
let mut samples = Vec::with_capacity(frames * gains.len());
for frame in 0..frames {
let time = frame as f32 / sample_rate as f32;
let sample = (std::f32::consts::TAU * frequency * time).sin() * 0.5;
for _ in 0..channels_count {
samples.push(sample as Sample);
for gain in gains {
samples.push((sample * gain) as Sample);
}
}
Self {
samples,
cursor: 0,
channels: ChannelCount::new(channels_count).unwrap(),
channels: ChannelCount::new(u16::try_from(gains.len()).unwrap()).unwrap(),
sample_rate: SampleRate::new(sample_rate).unwrap(),
}
}
@@ -452,4 +635,71 @@ mod tests {
assert!(snapshot.bass > 0.0);
assert!(snapshot.scope.iter().any(|sample| sample.abs() > 0.001));
}
#[test]
fn analyzed_source_feeds_the_spectrum_and_channel_meters() {
let shared = Arc::new(AnalyzerShared::default());
let source = TestSource::sine(48_000, 2, 48_000, 1_000.0);
let analyzed = AnalyzedSource::new(source, Arc::clone(&shared));
for _ in analyzed {}
let snapshot = shared.snapshot();
assert_eq!(snapshot.sample_rate, 48_000);
let bands = crate::player::BAND_CENTERS_HZ;
let at_1k = bands.iter().position(|hz| *hz == 1_000.0).unwrap();
let loudest = snapshot
.spectrum
.iter()
.enumerate()
.max_by(|left, right| left.1.total_cmp(right.1))
.map(|(index, _)| index);
assert_eq!(loudest, Some(at_1k));
assert!(snapshot.level_l > 0.5 && (snapshot.level_l - snapshot.level_r).abs() < 1e-6);
// the same signal in both channels has no side component
assert_eq!(snapshot.level_side, 0.0);
assert_eq!(snapshot.stereo, Some(false));
assert!(snapshot.peak_l >= snapshot.level_l);
}
#[test]
fn analyzed_source_measures_the_side_signal() {
let measure = |gains: &[f32]| {
let shared = Arc::new(AnalyzerShared::default());
let source = TestSource::sine_gains(48_000, 48_000, 1_000.0, gains);
for _ in AnalyzedSource::new(source, Arc::clone(&shared)) {}
shared.snapshot()
};
// R = -L: the side signal (L - R) / 2 equals L
let opposite = measure(&[1.0, -1.0]);
assert!(opposite.level_side > 0.5);
assert!((opposite.level_side - opposite.level_l).abs() < 1e-3);
assert_eq!(opposite.stereo, Some(true));
// mono duplicates L into R
let mono = measure(&[1.0]);
assert_eq!(mono.level_side, 0.0);
assert_eq!(mono.stereo, Some(false));
// a third channel only feeds the mono sum
let surround = measure(&[1.0, 0.0, 1.0]);
assert!(surround.level_side > 0.0 && surround.level_side < surround.level_l);
}
#[test]
fn pcm_history_reads_newest_samples_and_silence_before_the_first() {
let shared = AnalyzerShared::default();
for value in [0.25_f32, 0.5, -0.5] {
shared.push_pcm(value);
}
let mut out = [1.0_f32; 5];
shared.copy_pcm(shared.pcm_write.load(Ordering::Relaxed), &mut out);
let rounded: Vec<f32> = out
.iter()
.map(|value| (value * 4.0).round() / 4.0)
.collect();
assert_eq!(rounded, [0.0, 0.0, 0.25, 0.5, -0.5]);
shared.clear();
shared.copy_pcm(shared.pcm_write.load(Ordering::Relaxed), &mut out);
assert!(out.iter().all(|value| *value == 0.0));
}
}
+3 -1
View File
@@ -6,6 +6,7 @@
mod analyzer;
mod opus;
mod spectrum;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -15,6 +16,7 @@ use std::time::Duration;
use rodio::{Decoder, DeviceSinkBuilder, Player, Source, stream::MixerDeviceSink};
pub use analyzer::AudioAnalysisSnapshot;
pub use spectrum::{BAND_CENTERS_HZ, FLOOR_DB};
pub trait TrackReadSeek: std::io::Read + std::io::Seek + Send + Sync {}
@@ -453,7 +455,7 @@ fn handle(
if let Some(out) = output.take() {
out.player.stop();
}
shared.analysis.clear();
shared.analysis.reset();
playing.track_loaded = false;
playing.base = Duration::ZERO;
}
+650
View File
@@ -0,0 +1,650 @@
//! Display meter for visualizations: a third-octave spectrum and stereo levels
//! with analyzer ballistics (fast attack, steady fall, peak hold).
//!
//! The audio thread only writes samples and per-window channel levels into
//! `AnalyzerShared`; the FFT and all smoothing run here, on the reader side,
//! when a snapshot is taken. Ballistics are time-based: rises and falls
//! advance with the clock, not with the number of snapshots.
use std::sync::Arc;
use std::time::Instant;
use rustfft::num_complex::Complex;
use rustfft::{Fft, FftPlanner};
/// Mono samples kept for the spectrum: enough for an ~85 ms window at
/// 192 kHz. The FFT uses the newest `fft_len(rate)` of them.
pub const PCM_SAMPLES: usize = 16_384;
/// Bottom of the display scale: values are normalized from `FLOOR_DB`..0 dBFS
/// to 0.0..1.0, so a full-scale sine reads 1.0.
pub const FLOOR_DB: f32 = -60.0;
/// Nominal ISO third-octave band centres (Hz), 20 Hz .. 20 kHz. These are
/// labels; band edges come from the exact base-2 centres (see `exact_center`)
/// so neighbouring bands meet without gaps or overlaps.
pub const BAND_CENTERS_HZ: [f32; 31] = [
20.0, 25.0, 31.5, 40.0, 50.0, 63.0, 80.0, 100.0, 125.0, 160.0, 200.0, 250.0, 315.0, 400.0,
500.0, 630.0, 800.0, 1_000.0, 1_250.0, 1_600.0, 2_000.0, 2_500.0, 3_150.0, 4_000.0, 5_000.0,
6_300.0, 8_000.0, 10_000.0, 12_500.0, 16_000.0, 20_000.0,
];
const BANDS: usize = BAND_CENTERS_HZ.len();
/// Index of the 1 kHz band.
const KHZ_BAND: i32 = 17;
const MIN_FFT: usize = 4096;
const BAND_ATTACK_SECS: f32 = 0.025;
const BAND_FALL_DB_PER_SEC: f32 = 36.0;
const PEAK_HOLD_SECS: f32 = 1.2;
const PEAK_FALL_DB_PER_SEC: f32 = 18.0;
const LEVEL_ATTACK_SECS: f32 = 0.05;
const LEVEL_RELEASE_SECS: f32 = 0.3;
/// A window counts as stereo when its side signal (L - R) / 2 is no more
/// than this far below the louder channel: lossy coding of a mono recording
/// leaves a side signal far below that, real stereo mixes sit well above it.
const STEREO_SIDE_DB: f32 = -30.0;
/// Only windows this far above the floor decide; quieter ones keep the last
/// decision, since their side signal is lost in the floor.
const STEREO_DECIDE_ABOVE_FLOOR_DB: f32 = 30.0;
/// Longest step applied at once; a stalled reader must not fast-forward a
/// whole second of decay in one frame.
const MAX_STEP_SECS: f32 = 0.25;
/// Audio arrives in device-callback bursts (rodio uses ~46 ms buffers), so a
/// snapshot may see no new samples while playback runs. Only a longer stall
/// (pause, stop) counts as silence.
const STALL_SECS: f32 = 0.15;
/// FFT length for a sample rate: ~85 ms of audio, a power of two.
fn fft_len(sample_rate: u32) -> usize {
(sample_rate as usize * MIN_FFT / 48_000)
.next_power_of_two()
.clamp(MIN_FFT, PCM_SAMPLES)
}
/// Exact base-2 third-octave centre of band `index` (1 kHz at index 17).
fn exact_center(index: usize) -> f32 {
1_000.0 * 2f32.powf((index as i32 - KHZ_BAND) as f32 / 3.0)
}
/// Linear channel levels of the latest analysis window.
#[derive(Debug, Clone, Copy, Default)]
pub struct StereoReading {
pub rms_l: f32,
pub rms_r: f32,
/// RMS of the side signal (L - R) / 2.
pub rms_side: f32,
/// Highest sample peaks since the previous reading.
pub peak_l: f32,
pub peak_r: f32,
}
#[derive(Debug, Clone, Default)]
pub struct MeterReading {
pub spectrum: Vec<f64>,
pub spectrum_peaks: Vec<f64>,
pub level_l: f64,
pub level_r: f64,
pub peak_l: f64,
pub peak_r: f64,
pub level_side: f64,
/// Whether the two channels carry different signals (see
/// `STEREO_SIDE_DB`); `None` until a loud enough window was measured.
pub stereo: Option<bool>,
}
struct Hold {
db: f32,
age: f32,
}
impl Hold {
fn new() -> Self {
Self {
db: FLOOR_DB,
age: 0.0,
}
}
fn update(&mut self, value_db: f32, dt: f32) {
if value_db >= self.db {
self.db = value_db;
self.age = 0.0;
return;
}
self.age += dt;
if self.age > PEAK_HOLD_SECS {
self.db = (self.db - PEAK_FALL_DB_PER_SEC * dt).max(value_db);
}
}
}
/// FFT plan, window and band bin ranges for one sample rate.
struct Analysis {
sample_rate: u32,
fft: Arc<dyn Fft<f32>>,
window: Vec<f32>,
/// Sum of squared window weights, for power normalization.
window_power: f32,
pcm: Vec<f32>,
buffer: Vec<Complex<f32>>,
scratch: Vec<Complex<f32>>,
/// Inclusive bin range per band; `None` above Nyquist.
bins: [Option<(usize, usize)>; BANDS],
}
impl Analysis {
fn new(sample_rate: u32) -> Self {
let len = fft_len(sample_rate);
let fft = FftPlanner::<f32>::new().plan_fft_forward(len);
let scratch = vec![Complex::default(); fft.get_inplace_scratch_len()];
let window: Vec<f32> = (0..len)
.map(|index| {
let phase = std::f32::consts::TAU * index as f32 / len as f32;
0.5 - 0.5 * phase.cos()
})
.collect();
let window_power = window.iter().map(|weight| weight * weight).sum();
Self {
sample_rate,
fft,
window,
window_power,
pcm: vec![0.0; len],
buffer: vec![Complex::default(); len],
scratch,
bins: band_bins(sample_rate, len),
}
}
/// Band power in dBFS (a full-scale sine reads 0 dB in its band). The
/// caller has filled `pcm`.
fn band_targets(&mut self) -> [f32; BANDS] {
for ((slot, sample), weight) in self.buffer.iter_mut().zip(&self.pcm).zip(&self.window) {
*slot = Complex::new(sample * weight, 0.0);
}
self.fft
.process_with_scratch(&mut self.buffer, &mut self.scratch);
// One-sided power per bin, normalized so the bins of a sine sum to
// its mean square (A^2 / 2); doubled below so the sine reads 0 dB.
let scale = 2.0 / (self.buffer.len() as f32 * self.window_power);
let mut out = [FLOOR_DB; BANDS];
for (slot, range) in out.iter_mut().zip(self.bins) {
if let Some((first, last)) = range {
let power: f32 = self.buffer[first..=last]
.iter()
.map(|bin| bin.norm_sqr() * scale)
.sum();
*slot = to_db_power(2.0 * power);
}
}
out
}
}
/// Partitions the FFT bins between the bands: each bin belongs to exactly one
/// band, from the first bin at or above the band's lower edge up to the bin
/// before the next band starts. A band narrower than one bin (deep bass at
/// short windows) reads the bin that contains its centre, which it then shares
/// with its neighbour.
fn band_bins(sample_rate: u32, len: usize) -> [Option<(usize, usize)>; BANDS] {
let bin_hz = sample_rate as f32 / len as f32;
let last_bin = len / 2 - 1;
let nyquist = sample_rate as f32 / 2.0;
let edge = 2f32.powf(1.0 / 6.0);
let first_bin = |index: usize| ((exact_center(index) / edge / bin_hz).ceil() as usize).max(1);
std::array::from_fn(|index| {
let low = exact_center(index) / edge;
if low >= nyquist {
return None;
}
let first = first_bin(index);
let last = if index + 1 < BANDS {
first_bin(index + 1).saturating_sub(1)
} else {
((exact_center(index) * edge / bin_hz).floor() as usize).max(first)
}
.min(last_bin);
if first <= last {
Some((first, last))
} else {
let center = ((exact_center(index) / bin_hz).round() as usize).clamp(1, last_bin);
Some((center, center))
}
})
}
pub struct Meter {
analysis: Option<Analysis>,
bands_db: [f32; BANDS],
band_peaks: [Hold; BANDS],
/// Left, right and side RMS levels.
level_db: [f32; 3],
level_peaks: [Hold; 2],
last_update: Option<Instant>,
last_write: usize,
/// When the PCM counter last moved, and what that audio measured; reused
/// between device callbacks until `STALL_SECS` pass.
last_fresh: Option<Instant>,
held_targets: [f32; BANDS],
held_rms: [f32; 3],
/// Last stereo decision; kept through silence, pauses and stalls.
stereo: Option<bool>,
}
impl std::fmt::Debug for Meter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Meter")
.field("bands_db", &self.bands_db)
.field("level_db", &self.level_db)
.finish_non_exhaustive()
}
}
impl Default for Meter {
fn default() -> Self {
Self {
analysis: None,
bands_db: [FLOOR_DB; BANDS],
band_peaks: std::array::from_fn(|_| Hold::new()),
level_db: [FLOOR_DB; 3],
level_peaks: std::array::from_fn(|_| Hold::new()),
last_update: None,
last_write: 0,
last_fresh: None,
held_targets: [FLOOR_DB; BANDS],
held_rms: [0.0; 3],
stereo: None,
}
}
}
impl Meter {
/// Advances the meter to `now`. `write` is the analyzer's PCM write
/// counter: while it keeps moving the newest audio is measured; once it
/// has not moved for `STALL_SECS` (paused, stopped) the meter is fed
/// silence and falls instead of freezing. `fill_pcm` copies the newest
/// `out.len()` mono samples, oldest first.
pub fn update(
&mut self,
now: Instant,
write: usize,
sample_rate: u32,
stereo: StereoReading,
fill_pcm: impl FnOnce(&mut [f32]),
) -> MeterReading {
let dt = self
.last_update
.map(|last| now.saturating_duration_since(last).as_secs_f32())
.unwrap_or(MAX_STEP_SECS)
.min(MAX_STEP_SECS);
self.last_update = Some(now);
let fresh = write != self.last_write;
self.last_write = write;
let (targets, rms, peaks) = if fresh && sample_rate > 0 {
if self
.analysis
.as_ref()
.is_none_or(|analysis| analysis.sample_rate != sample_rate)
{
self.analysis = Some(Analysis::new(sample_rate));
}
let analysis = self.analysis.as_mut().expect("analysis was just set");
fill_pcm(&mut analysis.pcm);
self.held_targets = analysis.band_targets();
self.held_rms = [stereo.rms_l, stereo.rms_r, stereo.rms_side];
// decided on the raw window, before ballistics: smoothed levels
// converge on the floor together and would read as stereo
let loud = stereo.rms_l.max(stereo.rms_r);
if to_db(loud) > FLOOR_DB + STEREO_DECIDE_ABOVE_FLOOR_DB {
self.stereo = Some(to_db(stereo.rms_side) > to_db(loud) + STEREO_SIDE_DB);
}
self.last_fresh = Some(now);
(
self.held_targets,
self.held_rms,
[stereo.peak_l, stereo.peak_r],
)
} else if self
.last_fresh
.is_some_and(|last| now.saturating_duration_since(last).as_secs_f32() <= STALL_SECS)
{
(self.held_targets, self.held_rms, [0.0; 2])
} else {
([FLOOR_DB; BANDS], [0.0; 3], [0.0; 2])
};
for ((current, target), peak) in self
.bands_db
.iter_mut()
.zip(targets)
.zip(self.band_peaks.iter_mut())
{
*current = follow_band(*current, target, dt);
peak.update(*current, dt);
}
for (level, value) in self.level_db.iter_mut().zip(rms) {
*level = follow_level(*level, to_db(value), dt);
}
for (hold, value) in self.level_peaks.iter_mut().zip(peaks) {
hold.update(to_db(value), dt);
}
MeterReading {
spectrum: self.bands_db.iter().map(|db| normalize(*db)).collect(),
spectrum_peaks: self
.band_peaks
.iter()
.map(|hold| normalize(hold.db))
.collect(),
level_l: normalize(self.level_db[0]),
level_r: normalize(self.level_db[1]),
peak_l: normalize(self.level_peaks[0].db),
peak_r: normalize(self.level_peaks[1].db),
level_side: normalize(self.level_db[2]),
stereo: self.stereo,
}
}
}
fn follow_band(current: f32, target: f32, dt: f32) -> f32 {
if target > current {
current + (target - current) * (1.0 - (-dt / BAND_ATTACK_SECS).exp())
} else {
(current - BAND_FALL_DB_PER_SEC * dt).max(target)
}
}
fn follow_level(current: f32, target: f32, dt: f32) -> f32 {
let tau = if target > current {
LEVEL_ATTACK_SECS
} else {
LEVEL_RELEASE_SECS
};
current + (target - current) * (1.0 - (-dt / tau).exp())
}
fn to_db(amplitude: f32) -> f32 {
if amplitude <= 0.0 || !amplitude.is_finite() {
FLOOR_DB
} else {
(20.0 * amplitude.log10()).max(FLOOR_DB)
}
}
fn to_db_power(power: f32) -> f32 {
if power <= 0.0 || !power.is_finite() {
FLOOR_DB
} else {
(10.0 * power.log10()).max(FLOOR_DB)
}
}
fn normalize(db: f32) -> f64 {
f64::from(((db - FLOOR_DB) / -FLOOR_DB).clamp(0.0, 1.0))
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
fn sine(frequency: f32, amplitude: f32, sample_rate: u32, len: usize) -> Vec<f32> {
(0..len)
.map(|index| {
let time = index as f32 / sample_rate as f32;
amplitude * (std::f32::consts::TAU * frequency * time).sin()
})
.collect()
}
fn band(center: f32) -> usize {
BAND_CENTERS_HZ
.iter()
.position(|value| *value == center)
.unwrap()
}
/// Feeds a steady tone for `steps` snapshots 50 ms apart.
fn settle(meter: &mut Meter, frequency: f32, sample_rate: u32, steps: u64) -> MeterReading {
let samples = sine(frequency, 0.5, sample_rate, PCM_SAMPLES);
let start = Instant::now();
let mut reading = MeterReading::default();
for step in 1..=steps {
reading = meter.update(
start + Duration::from_millis(50 * step),
step as usize,
sample_rate,
StereoReading::default(),
|out| out.copy_from_slice(&samples[..out.len()]),
);
}
reading
}
fn band_powers_db(frequency: f32, sample_rate: u32) -> [f32; BANDS] {
let mut analysis = Analysis::new(sample_rate);
let len = analysis.pcm.len();
analysis
.pcm
.copy_from_slice(&sine(frequency, 1.0, sample_rate, len));
analysis.band_targets()
}
#[test]
fn a_sine_lights_its_own_third_octave_band() {
let reading = settle(&mut Meter::default(), 1_000.0, 48_000, 10);
let at_1k = reading.spectrum[band(1_000.0)];
// -6 dBFS on a 60 dB scale reads 0.9.
assert!((at_1k - 0.9).abs() < 0.03, "1 kHz band read {at_1k}");
assert!(reading.spectrum[band(250.0)] < 0.2);
assert!(reading.spectrum[band(4_000.0)] < 0.2);
assert!(reading.spectrum_peaks[band(1_000.0)] >= at_1k);
}
#[test]
fn bands_cover_the_axis_without_gaps_or_double_counting() {
for sample_rate in [44_100, 48_000, 96_000] {
// Up to just below the top band's upper edge (~22.4 kHz) or
// Nyquist; 1/24-octave steps also land right on band edges.
let top = (sample_rate as f32 / 2.0 * 0.85).min(exact_center(BANDS - 1) * 1.1);
let mut frequency = 80.0_f32;
while frequency < top {
let powers = band_powers_db(frequency, sample_rate);
let loudest = powers.iter().copied().fold(FLOOR_DB, f32::max);
let total: f32 = powers
.iter()
.filter(|db| **db > FLOOR_DB)
.map(|db| 10f32.powf(db / 10.0))
.sum();
assert!(
(-3.5..=0.5).contains(&loudest),
"{frequency} Hz at {sample_rate}: loudest band {loudest} dB"
);
let total_db = 10.0 * total.log10();
assert!(
total_db.abs() < 0.5,
"{frequency} Hz at {sample_rate}: bands sum to {total_db} dB"
);
frequency *= 2f32.powf(1.0 / 24.0);
}
}
}
#[test]
fn deep_bass_reads_at_every_sample_rate() {
for sample_rate in [44_100, 48_000, 96_000, 192_000] {
let powers = band_powers_db(31.5, sample_rate);
assert!(
powers[band(31.5)] > -3.0,
"31.5 Hz at {sample_rate}: {} dB",
powers[band(31.5)]
);
assert!(powers[band(1_000.0)] < -40.0);
}
// Bands above Nyquist stay at the floor.
assert_eq!(band_powers_db(1_000.0, 32_000)[band(20_000.0)], FLOOR_DB);
}
#[test]
fn callback_gaps_keep_the_meter_steady_but_a_stall_falls() {
let mut meter = Meter::default();
let samples = sine(1_000.0, 0.5, 48_000, PCM_SAMPLES);
let tone = StereoReading {
rms_l: 0.35,
rms_r: 0.35,
rms_side: 0.0,
peak_l: 0.5,
peak_r: 0.5,
};
let start = Instant::now();
let mut write = 0;
let mut steady = MeterReading::default();
for step in 1..=40u64 {
// Every third snapshot lands between two device callbacks.
if step % 3 != 0 {
write += 1;
}
let reading = meter.update(
start + Duration::from_millis(50 * step),
write,
48_000,
tone,
|out| out.copy_from_slice(&samples[..out.len()]),
);
if step > 20 {
assert!(
(reading.level_l - steady.level_l).abs() < 0.02 || step == 21,
"level jumped at step {step}"
);
assert!(
(reading.spectrum[band(1_000.0)] - 0.9).abs() < 0.03,
"band jumped at step {step}"
);
}
steady = reading;
}
// The counter stops for longer than a callback gap: paused.
let index = band(1_000.0);
let paused_at = start + Duration::from_millis(2_000);
let first = meter.update(paused_at, write, 48_000, tone, |_| {});
let later = meter.update(
paused_at + Duration::from_millis(500),
write,
48_000,
tone,
|_| {},
);
assert!(later.spectrum[index] < first.spectrum[index]);
assert!(later.level_l < first.level_l);
// The peak marker holds for 1.2 s before it falls too.
assert!((later.spectrum_peaks[index] - 0.9).abs() < 0.03);
let mut reading = later;
for step in 1..=20u64 {
reading = meter.update(
paused_at + Duration::from_millis(500 + 250 * step),
write,
48_000,
tone,
|_| {},
);
}
assert_eq!(reading.spectrum[index], 0.0);
assert!(reading.spectrum_peaks[index] < 0.5);
}
#[test]
fn channel_levels_follow_rms_and_hold_peaks() {
let mut meter = Meter::default();
let start = Instant::now();
let loud_left = StereoReading {
rms_l: 0.5,
rms_r: 0.05,
rms_side: 0.2,
peak_l: 0.9,
peak_r: 0.1,
};
let mut reading = MeterReading::default();
for step in 1..=20 {
reading = meter.update(
start + Duration::from_millis(50 * step),
step as usize,
48_000,
loud_left,
|out| out.fill(0.0),
);
}
assert!(reading.level_l > reading.level_r);
assert!((reading.level_l - normalize(to_db(0.5))).abs() < 0.02);
assert!((reading.peak_l - normalize(to_db(0.9))).abs() < 0.01);
assert!(reading.peak_l >= reading.level_l);
assert!((reading.level_side - normalize(to_db(0.2))).abs() < 0.02);
assert_eq!(reading.stereo, Some(true));
}
#[test]
fn stereo_is_decided_on_loud_windows_and_kept_through_silence() {
let mut meter = Meter::default();
let start = Instant::now();
let mut read = |step: u64, stereo: StereoReading| {
meter.update(
start + Duration::from_millis(50 * step),
step as usize,
48_000,
stereo,
|out| out.fill(0.0),
)
};
let quiet = StereoReading {
rms_l: 0.0005,
rms_r: 0.0001,
rms_side: 0.0002,
..StereoReading::default()
};
assert_eq!(read(1, quiet).stereo, None);
let near_mono = StereoReading {
rms_l: 0.3,
rms_r: 0.3,
rms_side: 0.003,
..StereoReading::default()
};
assert_eq!(read(2, near_mono).stereo, Some(false));
// silence and then a stall keep the decision
assert_eq!(read(3, StereoReading::default()).stereo, Some(false));
let wide = StereoReading {
rms_side: 0.1,
..near_mono
};
assert_eq!(read(4, wide).stereo, Some(true));
let later = meter.update(
start + Duration::from_secs(5),
4,
48_000,
StereoReading::default(),
|out| out.fill(0.0),
);
assert_eq!(later.stereo, Some(true));
}
#[test]
fn silence_and_unknown_rate_read_the_floor() {
let mut meter = Meter::default();
let reading = meter.update(Instant::now(), 1, 0, StereoReading::default(), |_| {});
assert!(reading.spectrum.iter().all(|value| *value == 0.0));
assert_eq!(reading.level_l, 0.0);
assert_eq!(reading.level_side, 0.0);
assert_eq!(reading.spectrum.len(), BAND_CENTERS_HZ.len());
}
#[test]
fn fft_length_tracks_the_sample_rate() {
assert_eq!(fft_len(44_100), 4096);
assert_eq!(fft_len(48_000), 4096);
assert_eq!(fft_len(96_000), 8192);
assert_eq!(fft_len(192_000), 16_384);
assert_eq!(fft_len(0), 4096);
}
}
+257
View File
@@ -0,0 +1,257 @@
//! Public podcast cards found by federated search: their order next to the
//! music results, whether this device is already subscribed, an episode
//! preview read from the feed itself, and subscribing from a card.
//!
//! A card is a publisher's claim. Only its origin feed URL
//! ([`PodcastSearchHit::feed_url`]) is bound to the podcast id, so it is the
//! only URL this module ever fetches or subscribes with; the claimed moved
//! URLs are shown, never used. Nothing from the card is stored: subscribing
//! reads the feed from the podcast's own host like any other subscription,
//! and the new subscription is private.
use anyhow::{Result, bail};
use furumi_library::podcasts::PodcastStore;
use music_dht::LibraryItem;
use music_dht::podcast::{FeedUrl, PodcastId};
use music_dht::podcast_dht::{
FederatedSearchHit, PodcastDht, PodcastSearchHit, merge_search_results,
};
use super::fetch::{FeedBody, Fetcher, Validators};
use super::refresh::{self, Services, SubscribeReport};
/// Podcast hits asked from the discovery overlay per search.
pub const PODCAST_SEARCH_LIMIT: usize = 20;
/// Upper bound of one podcast search, the overlay's bootstrap included (the
/// overlay bounds only its lookups). The music lookup deadline.
pub const PODCAST_SEARCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
/// Episodes kept in a preview (newest first).
pub const PREVIEW_EPISODES: usize = 200;
/// One public podcast in the search results.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PodcastHit {
pub hit: PodcastSearchHit,
/// The id this device gives the hit's origin URL
/// (`PodcastStore::resolve_podcast_id`): the card's id, unless the URL
/// is a known alias of a podcast this device already has.
pub local_id: PodcastId,
}
impl PodcastHit {
/// A hit not yet resolved against the local store.
pub fn new(hit: PodcastSearchHit) -> Self {
let local_id = hit.podcast_id.clone();
Self { hit, local_id }
}
/// Ids under which this device may know the podcast.
pub fn ids(&self) -> [&PodcastId; 2] {
[&self.local_id, &self.hit.podcast_id]
}
pub fn title(&self) -> &str {
&self.hit.card.title
}
}
/// The podcast hits of a federated search, in the order of
/// [`merge_search_results`] (exact title matches first). The TUI keeps its
/// own sections for the music results and searches podcasts separately;
/// the order of the podcast entries does not depend on the music items
/// (the merge is a stable exact-title partition), so [`search`] passes none.
pub fn podcast_hits(
query: &str,
music: Vec<LibraryItem>,
podcasts: Vec<PodcastSearchHit>,
) -> Vec<PodcastHit> {
merge_search_results(query, music, podcasts)
.into_iter()
.filter_map(|hit| match hit {
FederatedSearchHit::Podcast(hit) => Some(PodcastHit::new(hit)),
FederatedSearchHit::Music(_) => None,
})
.collect()
}
/// Searches the discovery overlay for public podcast cards, independently
/// of the music search. Bounded by `timeout` (the overlay bootstraps first
/// when it knows no peers, which its own lookup deadline does not cover).
/// No overlay, an error or a timeout give no hits; the warning names
/// neither the query nor any URL.
pub async fn search(
dht: Option<&PodcastDht>,
query: &str,
timeout: std::time::Duration,
) -> Vec<PodcastHit> {
let Some(dht) = dht else {
return Vec::new();
};
match tokio::time::timeout(timeout, dht.search(query, PODCAST_SEARCH_LIMIT)).await {
Ok(Ok(hits)) => podcast_hits(query, Vec::new(), hits),
Ok(Err(err)) => {
tracing::warn!("podcast discovery search failed: {err}");
Vec::new()
}
Err(_) => {
tracing::warn!(
timeout_s = timeout.as_secs(),
"podcast discovery search timed out"
);
Vec::new()
}
}
}
/// Resolves each hit's origin URL against the local store (feed aliases
/// included). Blocking.
pub fn resolve_local_ids(store: &PodcastStore, hits: &mut [PodcastHit]) -> Result<()> {
for hit in hits {
hit.local_id = store.resolve_podcast_id(&hit.hit.feed_url)?;
}
Ok(())
}
/// Subscribes to the podcast of a public card with its origin URL, never a
/// claimed one. The feed is read from its own host (following its own
/// redirects and `itunes:new-feed-url`), the subscription is private and
/// none of the card's metadata is stored.
pub async fn subscribe_from_hit(
services: &Services,
hit: &PodcastSearchHit,
now_ms: i64,
) -> Result<SubscribeReport> {
if PodcastId::from_feed_url(&hit.feed_url) != hit.podcast_id {
bail!("the card's feed URL does not match its podcast id");
}
refresh::subscribe_url(services, hit.feed_url.clone(), now_ms).await
}
/// One episode of a preview.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreviewEpisode {
pub title: String,
pub season: Option<u32>,
pub episode_number: Option<u32>,
pub published_at_ms: Option<i64>,
pub duration_ms: Option<i64>,
}
/// What a podcast's own feed says, read without subscribing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FeedPreview {
/// Channel title in the feed (may differ from the card's claim).
pub title: String,
pub episode_count: usize,
/// Season number (`None`: episodes without one) and episode count,
/// seasons in ascending order, unnumbered last.
pub seasons: Vec<(Option<u32>, usize)>,
/// Newest first, at most [`PREVIEW_EPISODES`].
pub episodes: Vec<PreviewEpisode>,
/// The feed answered from, or announced, another address.
pub moved_to: Option<FeedUrl>,
/// This device is subscribed to the podcast under `moved_to` (it
/// followed the feed's newer address, the card names the older one):
/// the card shows «Уже подписан». Set by [`preview_for`].
pub subscribed_as: Option<PodcastId>,
}
/// Reads the feed at `url` (a card's origin URL) for a preview. Nothing is
/// stored and no fetch state is recorded.
pub async fn preview(fetcher: &Fetcher, url: &FeedUrl) -> Result<FeedPreview> {
let response = fetcher.fetch_feed(url, Validators::default()).await?;
let FeedBody::Modified { body, .. } = response.body else {
bail!("the server answered 304 Not Modified to an unconditional request");
};
let feed = refresh::parse(body, &response.final_url).await?;
let announced = feed
.new_feed_url
.as_deref()
.and_then(|url| FeedUrl::parse(url).ok());
let moved_to = response
.moved_permanently_to
.or(announced)
.filter(|moved| moved != url);
let mut seasons: std::collections::BTreeMap<(bool, u32), usize> = Default::default();
for episode in &feed.episodes {
let key = match episode.season {
Some(season) => (false, season),
None => (true, 0),
};
*seasons.entry(key).or_default() += 1;
}
let mut episodes: Vec<PreviewEpisode> = feed
.episodes
.iter()
.map(|episode| PreviewEpisode {
title: episode.title.clone(),
season: episode.season,
episode_number: episode.episode_number,
published_at_ms: episode.published_at_ms,
duration_ms: episode.duration_ms,
})
.collect();
episodes.sort_by_key(|episode| std::cmp::Reverse(episode.published_at_ms));
episodes.truncate(PREVIEW_EPISODES);
Ok(FeedPreview {
title: feed.title.clone(),
episode_count: feed.episodes.len(),
seasons: seasons
.into_iter()
.map(|((unnumbered, season), count)| ((!unnumbered).then_some(season), count))
.collect(),
episodes,
moved_to,
subscribed_as: None,
})
}
/// [`preview`], plus whether this device already follows the podcast under
/// the newer address the feed moved to (`subscribed_as`). The store is only
/// read.
pub async fn preview_for(services: &Services, url: &FeedUrl) -> Result<FeedPreview> {
let mut preview = preview(&services.fetcher, url).await?;
if let Some(moved) = preview.moved_to.clone() {
let store = std::sync::Arc::clone(&services.store);
preview.subscribed_as =
tokio::task::spawn_blocking(move || refresh::subscribed_podcast(&store, &moved))
.await??;
}
Ok(preview)
}
/// A search hit for `feed_url` as one publisher would announce it (tests of
/// the search UI and of subscribing from a card).
#[cfg(test)]
pub(crate) fn test_hit(feed_url: &str, title: &str) -> PodcastSearchHit {
let feed_url = FeedUrl::parse(feed_url).unwrap();
let podcast_id = PodcastId::from_feed_url(&feed_url);
let publisher = music_dht::SecretKey::from_bytes(&[7; 32]).public();
PodcastSearchHit {
podcast_id: podcast_id.clone(),
feed_url: feed_url.clone(),
card: music_dht::podcast_dht::PodcastCard {
version: 1,
network_id: music_dht::NetworkId::from_name("furumi-tui-discovery-test"),
publisher,
podcast_id,
feed_url,
id_feed_url: None,
title: title.to_string(),
author: Some("Ferris Crab".to_string()),
description: Some("Weekly news about Rust.".to_string()),
image_url: None,
link: None,
language: Some("en".to_string()),
categories: vec!["Technology".to_string()],
episode_count: Some(12),
latest_episode_at_ms: Some(1_718_445_600_000),
revision: 1,
issued_at_ms: 1,
expires_at_ms: 2,
},
publishers: vec![publisher],
claimed_feed_urls: Vec::new(),
}
}
+500
View File
@@ -0,0 +1,500 @@
//! Public podcast cards: their order in the search results, the "already
//! subscribed" mark, the feed preview, subscribing from a card, and an
//! end-to-end run over two loopback discovery nodes with a local feed
//! server (no internet, temp directories only).
use std::sync::Arc;
use std::time::Duration;
use furumi_library::podcasts::PodcastListFilter;
use music_dht::NetworkId;
use music_dht::podcast::{FeedUrl, PodcastId};
use music_dht::podcast_dht::{ClaimedFeedUrl, FederatedSearchHit, SearchHitKind};
use super::discovery::{
PODCAST_SEARCH_TIMEOUT, PodcastHit, podcast_hits, preview, preview_for, resolve_local_ids,
search, subscribe_from_hit, test_hit,
};
use super::publication::{Publication, check_share, reconcile, set_shared};
use super::publication_tests::{Node, wait_for};
use super::refresh::{refresh, subscribe};
use super::test_server::Route;
use super::tests::{NOW, fixture, rss};
#[test]
fn podcast_hits_put_exact_titles_first_and_keep_only_podcasts() {
let other = test_hit("https://feeds.example.test/weekly.xml", "Rust Radio Weekly");
let exact = test_hit("https://feeds.example.test/radio.xml", "Rust Radio");
let hits = podcast_hits("rust radio", Vec::new(), vec![other.clone(), exact.clone()]);
let ids: Vec<&PodcastId> = hits.iter().map(|hit| &hit.hit.podcast_id).collect();
assert_eq!(ids, [&exact.podcast_id, &other.podcast_id]);
// Unresolved hits use the card's id; the type marker is "podcast".
assert!(hits.iter().all(|hit| hit.local_id == hit.hit.podcast_id));
assert_eq!(hits[0].hit.kind(), SearchHitKind::Podcast);
assert_eq!(
FederatedSearchHit::Podcast(exact).kind().as_str(),
"podcast"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn podcast_search_is_bounded_and_empty_without_the_overlay() {
// Federation off (no overlay): no hits, nothing to wait for.
assert!(
search(None, "rust radio", PODCAST_SEARCH_TIMEOUT)
.await
.is_empty()
);
// An overlay that knows no overlay peers bootstraps from its music-DHT
// contacts before it searches, outside its own lookup deadline. With a
// contact that no longer answers, the search still ends at the bound.
let temp = tempfile::tempdir().unwrap();
let network = NetworkId::from_name("furumi-tui-podcast-search-bound-test");
let a = Node::start(&temp.path().join("a"), network).await;
let gone = Node::start(&temp.path().join("gone"), network).await;
a.service
.connect(gone.service.ticket().await.unwrap())
.await
.unwrap();
wait_for("a music DHT contact", async || {
(!a.service.known_peers().is_empty()).then_some(())
})
.await;
gone.stop().await;
assert_eq!(a.dht.known_peers(), 0);
let bound = Duration::from_millis(500);
let started = std::time::Instant::now();
let hits = search(Some(&a.dht), "rust radio", bound).await;
let elapsed = started.elapsed();
assert!(hits.is_empty());
assert!(elapsed < bound + Duration::from_secs(1), "took {elapsed:?}");
a.stop().await;
}
#[tokio::test]
async fn subscribing_from_a_card_matches_subscribing_by_url() {
let by_url = fixture();
let from_card = fixture();
by_url.server.set(
"/feed.xml",
Route::new(
rss(&[("a", "Pilot"), ("b", "Second")]),
"application/rss+xml",
),
);
let url = by_url.server.url("/feed.xml");
let typed = subscribe(&by_url.services, &url, NOW).await.unwrap();
let hit = test_hit(&url, "A card title that is only a claim");
let report = subscribe_from_hit(&from_card.services, &hit, NOW)
.await
.unwrap();
assert_eq!(report.podcast_id, typed.podcast_id);
assert_eq!(report.podcast_id, hit.podcast_id);
assert_eq!(report.new_episodes, 2);
// Metadata comes from the feed, never from the card.
assert_eq!(report.title, "Test Show");
// A private subscription: no share decision was written.
assert_eq!(from_card.log.kinds(), ["podcast_subscription_set"]);
let store = &from_card.services.store;
assert_eq!(store.share(&report.podcast_id).unwrap(), None);
let rows = store.list_podcasts(PodcastListFilter::Subscribed).unwrap();
assert_eq!(rows.len(), 1);
assert!(!rows[0].shared);
assert_eq!(rows[0].meta.title, "Test Show");
// Subscribing again from the card changes nothing.
let again = subscribe_from_hit(&from_card.services, &hit, NOW + 1)
.await
.unwrap();
assert!(again.already_subscribed);
assert_eq!(from_card.log.kinds().len(), 1);
}
#[tokio::test]
async fn subscribing_from_a_card_never_fetches_a_claimed_url() {
let f = fixture();
// The origin URL moved permanently; a publisher also claims a URL of its
// own choosing.
f.server.set(
"/origin.xml",
Route::redirect(301, &f.server.url("/moved.xml")),
);
f.server.set(
"/moved.xml",
Route::new(rss(&[("a", "Pilot")]), "application/rss+xml"),
);
f.server.set(
"/claimed.xml",
Route::new(rss(&[("x", "Imposter")]), "application/rss+xml"),
);
let origin = FeedUrl::parse(&f.server.url("/origin.xml")).unwrap();
let moved = FeedUrl::parse(&f.server.url("/moved.xml")).unwrap();
let claimed = FeedUrl::parse(&f.server.url("/claimed.xml")).unwrap();
let mut hit = test_hit(origin.as_str(), "Rust Radio");
hit.claimed_feed_urls = vec![ClaimedFeedUrl {
feed_url: claimed.clone(),
publishers: hit.publishers.clone(),
}];
hit.card.feed_url = claimed.clone();
hit.card.id_feed_url = Some(origin.clone());
let report = subscribe_from_hit(&f.services, &hit, NOW).await.unwrap();
assert_eq!(report.podcast_id, PodcastId::from_feed_url(&origin));
assert!(f.server.requests("/claimed.xml").is_empty());
let aliases = f.services.store.feed_aliases(&report.podcast_id).unwrap();
assert!(
aliases.contains(&moved),
"the feed's own redirect is an alias"
);
assert!(
!aliases.contains(&claimed),
"a claim never becomes an alias"
);
// A card whose id is not the hash of its origin URL is refused before
// anything is fetched or stored.
let other = fixture();
let mut forged = test_hit(&f.server.url("/moved.xml"), "Rust Radio");
forged.podcast_id = hit.podcast_id.clone();
let requests = f.server.requests("/moved.xml").len();
assert!(
subscribe_from_hit(&other.services, &forged, NOW)
.await
.is_err()
);
assert_eq!(f.server.requests("/moved.xml").len(), requests);
assert!(other.log.kinds().is_empty());
}
#[tokio::test]
async fn hits_resolve_to_the_podcast_a_feed_alias_belongs_to() {
let f = fixture();
f.server
.set("/old.xml", Route::redirect(301, &f.server.url("/new.xml")));
f.server.set(
"/new.xml",
Route::new(rss(&[("a", "Pilot")]), "application/rss+xml"),
);
let subscribed = subscribe(&f.services, &f.server.url("/old.xml"), NOW)
.await
.unwrap();
// Somebody else subscribed with the new address and shares that card.
let mut hits = vec![
PodcastHit::new(test_hit(&f.server.url("/new.xml"), "Test Show")),
PodcastHit::new(test_hit(
"https://feeds.example.test/unknown.xml",
"Unknown",
)),
];
assert_ne!(hits[0].hit.podcast_id, subscribed.podcast_id);
resolve_local_ids(&f.services.store, &mut hits).unwrap();
assert_eq!(hits[0].local_id, subscribed.podcast_id);
assert!(hits[0].ids().contains(&&subscribed.podcast_id));
assert_eq!(hits[1].local_id, hits[1].hit.podcast_id);
}
#[tokio::test]
async fn a_card_for_an_older_address_finds_the_subscription_under_the_newer_one() {
use furumi_library::podcasts::PodcastListFilter;
// The user follows the feed under its newer address; a long-standing
// publisher's card names the older one (the card's origin).
let f = fixture();
let feed = |announce: Option<&str>| {
let announce = announce
.map(|url| format!("<itunes:new-feed-url>{url}</itunes:new-feed-url>"))
.unwrap_or_default();
format!(
"<?xml version=\"1.0\"?><rss version=\"2.0\" \
xmlns:itunes=\"http://www.itunes.com/dtds/podcast-1.0.dtd\"><channel>\
<title>Test Show</title>{announce}{}</channel></rss>",
item("a", "Pilot", 1, "Sat, 01 Jun 2024 10:00:00 GMT"),
)
};
let subscribed_rows = || {
f.services
.store
.list_podcasts(PodcastListFilter::Subscribed)
.unwrap()
.len()
};
// 1. The old address redirects permanently to the new one.
f.server
.set("/old.xml", Route::redirect(301, &f.server.url("/new.xml")));
f.server
.set("/new.xml", Route::new(feed(None), "application/rss+xml"));
let followed = subscribe(&f.services, &f.server.url("/new.xml"), NOW)
.await
.unwrap();
let card = test_hit(&f.server.url("/old.xml"), "Test Show");
let url = card.feed_url.clone();
let preview = preview_for(&f.services, &url).await.unwrap();
assert_eq!(preview.subscribed_as.as_ref(), Some(&followed.podcast_id));
let report = subscribe_from_hit(&f.services, &card, NOW).await.unwrap();
assert!(report.already_subscribed);
assert_eq!(report.podcast_id, followed.podcast_id);
assert_eq!(subscribed_rows(), 1);
// 2. The old address only announces the new one (itunes:new-feed-url,
// no redirect): no second subscription for the same podcast.
let new_url = f.server.url("/new2.xml");
f.server
.set("/new2.xml", Route::new(feed(None), "application/rss+xml"));
f.server.set(
"/old2.xml",
Route::new(feed(Some(&new_url)), "application/rss+xml"),
);
let followed = subscribe(&f.services, &new_url, NOW).await.unwrap();
let kinds = f.log.kinds().len();
let card = test_hit(&f.server.url("/old2.xml"), "Test Show");
let url = card.feed_url.clone();
let preview = preview_for(&f.services, &url).await.unwrap();
assert_eq!(preview.moved_to, Some(FeedUrl::parse(&new_url).unwrap()));
assert_eq!(preview.subscribed_as.as_ref(), Some(&followed.podcast_id));
let report = subscribe_from_hit(&f.services, &card, NOW).await.unwrap();
assert!(report.already_subscribed);
assert_eq!(report.podcast_id, followed.podcast_id);
assert_eq!(subscribed_rows(), 2, "one row per podcast");
assert_eq!(f.log.kinds().len(), kinds, "nothing was written");
// A card whose feed moved to an address this device does not follow
// is not marked.
f.server.set(
"/elsewhere.xml",
Route::new(
feed(Some("https://feeds.example.test/unknown.xml")),
"application/rss+xml",
),
);
let url = FeedUrl::parse(&f.server.url("/elsewhere.xml")).unwrap();
let preview = preview_for(&f.services, &url).await.unwrap();
assert!(preview.moved_to.is_some());
assert_eq!(preview.subscribed_as, None);
}
#[tokio::test]
async fn preview_reads_seasons_and_episodes_without_storing_anything() {
let f = fixture();
let new_url = "https://feeds.example.test/new-home.xml";
let feed = format!(
"<?xml version=\"1.0\"?><rss version=\"2.0\" \
xmlns:itunes=\"http://www.itunes.com/dtds/podcast-1.0.dtd\"><channel>\
<title>Feed Title</title><itunes:new-feed-url>{new_url}</itunes:new-feed-url>\
{}{}{}{}</channel></rss>",
item("a", "One", 1, "Sat, 01 Jun 2024 10:00:00 GMT"),
item("b", "Two", 1, "Sat, 08 Jun 2024 10:00:00 GMT"),
item("c", "Three", 2, "Sat, 15 Jun 2024 10:00:00 GMT"),
"<item><title>Bonus</title><guid>d</guid>\
<pubDate>Sat, 22 Jun 2024 10:00:00 GMT</pubDate>\
<enclosure url=\"/d.mp3\" type=\"audio/mpeg\"/></item>",
);
f.server
.set("/feed.xml", Route::new(feed, "application/rss+xml"));
let url = FeedUrl::parse(&f.server.url("/feed.xml")).unwrap();
let preview = preview(&f.services.fetcher, &url).await.unwrap();
assert_eq!(preview.title, "Feed Title");
assert_eq!(preview.episode_count, 4);
assert_eq!(preview.seasons, [(Some(1), 2), (Some(2), 1), (None, 1)]);
let titles: Vec<&str> = preview.episodes.iter().map(|e| e.title.as_str()).collect();
assert_eq!(titles, ["Bonus", "Three", "Two", "One"]);
assert_eq!(preview.episodes[1].season, Some(2));
assert_eq!(preview.episodes[1].duration_ms, Some(45 * 60 * 1000));
assert_eq!(
preview.moved_to,
Some(FeedUrl::parse(new_url).unwrap()),
"the feed announced a new address"
);
// Nothing was stored: no podcast, no fetch state, no operation.
let store = &f.services.store;
assert!(
store
.list_podcasts(PodcastListFilter::All)
.unwrap()
.is_empty()
);
assert!(f.log.kinds().is_empty());
}
fn item(guid: &str, title: &str, season: u32, date: &str) -> String {
format!(
"<item><title>{title}</title><guid>{guid}</guid><pubDate>{date}</pubDate>\
<itunes:season>{season}</itunes:season><itunes:duration>45:00</itunes:duration>\
<enclosure url=\"/{guid}.mp3\" type=\"audio/mpeg\"/></item>"
)
}
// ---------------------------------------------------------------------------
// Two loopback nodes and a local feed server
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_stranger_finds_a_shared_card_subscribes_and_refreshes_from_the_feed() {
tokio::time::timeout(Duration::from_secs(240), stranger_subscribes())
.await
.unwrap();
}
async fn stranger_subscribes() {
let temp = tempfile::tempdir().unwrap();
let network = NetworkId::from_name("furumi-tui-podcast-discovery-test");
// A shares a podcast. B is another user's TUI outside A's
// trusted-device group: no device sync between them, only the overlay.
let a = Node::start(&temp.path().join("a"), network).await;
let b = Node::start(&temp.path().join("b"), network).await;
b.service
.connect(a.service.ticket().await.unwrap())
.await
.unwrap();
wait_for("music DHT contacts", async || {
(!a.service.known_peers().is_empty() && !b.service.known_peers().is_empty()).then_some(())
})
.await;
for node in [&a, &b] {
node.dht.bootstrap().await.unwrap();
}
wait_for("overlay contacts", async || {
(a.dht.known_peers() >= 1 && b.dht.known_peers() >= 1).then_some(())
})
.await;
// The podcast's own host (a local HTTP server).
let user_a = fixture();
let user_b = fixture();
let feed = &user_a.server;
feed.set(
"/show.xml",
Route::new(
rss(&[("a", "Pilot"), ("b", "Second")]),
"application/rss+xml",
),
);
let feed_url = FeedUrl::parse(&feed.url("/show.xml")).unwrap();
let private_url = feed.url("/diary.xml");
feed.set(
"/diary.xml",
Route::new(rss(&[("p", "Private entry")]), "application/rss+xml"),
);
// A subscribes to two podcasts and shares one. The local address looks
// private, so A confirms exactly these URLs first (the dialog).
let shared = subscribe(&user_a.services, feed_url.as_str(), NOW)
.await
.unwrap();
let private = subscribe(&user_a.services, &private_url, NOW)
.await
.unwrap();
let store_a = Arc::clone(&user_a.services.store);
let confirmations = Arc::clone(&user_a.services.confirmations);
let check = check_share(&store_a, &confirmations, &shared.podcast_id).unwrap();
set_shared(
&store_a,
&confirmations,
&shared.podcast_id,
true,
check.needs_confirmation().then_some(check.urls),
|| {
user_a
.services
.log
.record(&mut |stamps| store_a.set_shared(stamps, &shared.podcast_id, true))
},
)
.unwrap();
let report = reconcile(
&a.dht,
Some(Arc::clone(&store_a)),
Arc::clone(&confirmations),
)
.await;
assert_eq!(report.error, None);
assert_eq!(
report.podcasts.get(&shared.podcast_id),
Some(&Publication::Published)
);
// B searches like the search view does: overlay search, merged order,
// resolved against B's own store.
let mut hits = wait_for("the shared card", async || {
let found = search(Some(&b.dht), "test show", PODCAST_SEARCH_TIMEOUT).await;
(!found.is_empty()).then_some(found)
})
.await;
assert_eq!(hits.len(), 1, "the private subscription is not found");
resolve_local_ids(&user_b.services.store, &mut hits).unwrap();
let hit = hits.remove(0);
assert_eq!(hit.hit.kind(), SearchHitKind::Podcast);
assert_eq!(hit.hit.podcast_id, shared.podcast_id);
assert_eq!(hit.hit.feed_url, feed_url);
assert_eq!(hit.hit.publishers, vec![a.service.endpoint_id()]);
assert_eq!(hit.local_id, shared.podcast_id);
assert!(
b.dht
.lookup_podcast(&private.podcast_id)
.await
.unwrap()
.is_none()
);
// "Подписаться": B reads the feed from its host, not from A.
let before = feed.requests("/show.xml").len();
let subscribed = subscribe_from_hit(&user_b.services, &hit.hit, NOW)
.await
.unwrap();
assert_eq!(subscribed.podcast_id, shared.podcast_id, "same podcast id");
assert_eq!(subscribed.new_episodes, 2);
assert_eq!(feed.requests("/show.xml").len(), before + 1);
let store_b = &user_b.services.store;
assert_eq!(store_b.share(&subscribed.podcast_id).unwrap(), None);
assert_eq!(user_b.log.kinds(), ["podcast_subscription_set"]);
assert!(
b.dht.published().await.unwrap().is_empty(),
"B publishes nothing"
);
// B refreshes on its own from the feed.
feed.set(
"/show.xml",
Route::new(
rss(&[("a", "Pilot"), ("b", "Second"), ("c", "Third")]),
"application/rss+xml",
),
);
let refreshed = refresh(&user_b.services, &subscribed.podcast_id, &feed_url, NOW + 1)
.await
.unwrap();
assert_eq!(refreshed.new_episodes, 1);
// A stops sharing: the card disappears for B, B's subscription stays.
user_a
.services
.log
.record(&mut |stamps| store_a.set_shared(stamps, &shared.podcast_id, false))
.unwrap();
let report = reconcile(&a.dht, Some(Arc::clone(&store_a)), confirmations).await;
assert_eq!(report.podcasts.get(&shared.podcast_id), None);
assert!(
b.dht
.lookup_podcast(&shared.podcast_id)
.await
.unwrap()
.is_none()
);
assert!(
search(Some(&b.dht), "test show", PODCAST_SEARCH_TIMEOUT)
.await
.is_empty()
);
let rows = store_b
.list_podcasts(PodcastListFilter::Subscribed)
.unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].podcast_id, shared.podcast_id);
assert!(!rows[0].shared);
let refreshed = refresh(&user_b.services, &subscribed.podcast_id, &feed_url, NOW + 2)
.await
.unwrap();
assert_eq!(refreshed.new_episodes, 0);
a.stop().await;
b.stop().await;
}
+15 -1
View File
@@ -18,19 +18,30 @@
//! bounded HTTP Range reader, and [`playback`] resolves the current audio
//! URL and resume position, opens and positions it;
//! * [`progress`] writes resume positions, completions and listening
//! sessions in order on its own thread.
//! sessions in order on its own thread;
//! * [`publication`] publishes the podcasts the user chose to share to the
//! public discovery overlay (`music_dht::podcast_dht`) and revokes them;
//! * [`discovery`] handles public cards found by search: their order, the
//! "already subscribed" mark, an episode preview read from the feed and
//! subscribing from a card.
//!
//! Only RSS metadata is stored. Audio stays on the publisher's server.
pub mod discovery;
pub mod fetch;
pub mod playback;
pub mod progress;
pub mod publication;
pub mod refresh;
pub mod stream;
#[cfg(test)]
mod discovery_tests;
#[cfg(test)]
mod playback_tests;
#[cfg(test)]
mod publication_tests;
#[cfg(test)]
mod stream_tests;
#[cfg(test)]
mod test_server;
@@ -111,10 +122,13 @@ pub fn open_services(db_path: &Path, covers_dir: PathBuf, log: Arc<dyn OpLog>) -
Ok(_) => {}
Err(err) => tracing::debug!("reading the podcast import quarantine failed: {err:#}"),
}
let confirmations =
publication::ShareConfirmations::open(publication::confirmations_path(db_path));
Ok(Services {
store: Arc::new(store),
fetcher: Arc::new(Fetcher::new(covers_dir)?),
log,
confirmations: Arc::new(confirmations),
})
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+63 -19
View File
@@ -30,6 +30,8 @@ pub struct Services {
pub store: Arc<PodcastStore>,
pub fetcher: Arc<Fetcher>,
pub log: Arc<dyn OpLog>,
/// Device-local privacy confirmations for sharing (never synced).
pub confirmations: Arc<super::publication::ShareConfirmations>,
}
impl std::fmt::Debug for Services {
@@ -93,24 +95,22 @@ fn duration_ms(duration: Duration) -> i64 {
/// saved progress and history. The subscription is private.
pub async fn subscribe(services: &Services, input: &str, now_ms: i64) -> Result<SubscribeReport> {
let url = FeedUrl::from_user_input(input).map_err(|err| anyhow!("{err}"))?;
let store = Arc::clone(&services.store);
let lookup = url.clone();
let existing = blocking(move || {
let id = store.resolve_podcast_id(&lookup)?;
let subscribed = store
.subscription(&id)?
.is_some_and(|record| record.subscribed);
let title = store.podcast(&id)?.map(|summary| summary.meta.title);
Ok(subscribed.then_some((id, title)))
})
.await?;
if let Some((podcast_id, title)) = existing {
return Ok(SubscribeReport {
podcast_id,
title: title.unwrap_or_default(),
already_subscribed: true,
new_episodes: 0,
});
subscribe_url(services, url, now_ms).await
}
/// Subscribes to `url` exactly as given (see [`subscribe`]).
///
/// Subscribing from a public card passes the card's origin URL here
/// (`podcasts::discovery::subscribe_from_hit`): the id then matches the
/// card's `podcast_id` unless this device already knows the URL as an alias
/// of another podcast, and everything stored comes from the feed itself.
pub async fn subscribe_url(
services: &Services,
url: FeedUrl,
now_ms: i64,
) -> Result<SubscribeReport> {
if let Some(report) = already_subscribed(services, &url).await? {
return Ok(report);
}
let response = services
@@ -130,6 +130,18 @@ pub async fn subscribe(services: &Services, input: &str, now_ms: i64) -> Result<
// The feed's own address: where its permanent redirects lead.
let moved_permanently = response.moved_permanently_to.is_some();
let landed = response.moved_permanently_to.unwrap_or(final_url);
// An older address of a feed this device follows under the newer one it
// announces (`itunes:new-feed-url`, no redirect): the same podcast, not
// a second subscription. Nothing is written.
if let Some(announced) = feed
.new_feed_url
.as_deref()
.and_then(|announced| FeedUrl::parse(announced).ok())
.filter(|announced| *announced != url && *announced != landed)
&& let Some(report) = already_subscribed(services, &announced).await?
{
return Ok(report);
}
let store = Arc::clone(&services.store);
let log = Arc::clone(&services.log);
@@ -191,6 +203,38 @@ pub async fn subscribe(services: &Services, input: &str, now_ms: i64) -> Result<
Ok(report)
}
/// The subscription `url` belongs to on this device (directly or as a
/// known feed alias), as an "already subscribed" report.
async fn already_subscribed(services: &Services, url: &FeedUrl) -> Result<Option<SubscribeReport>> {
let store = Arc::clone(&services.store);
let lookup = url.clone();
blocking(move || {
let Some(podcast_id) = subscribed_podcast(&store, &lookup)? else {
return Ok(None);
};
let title = store
.podcast(&podcast_id)?
.map(|summary| summary.meta.title);
Ok(Some(SubscribeReport {
podcast_id,
title: title.unwrap_or_default(),
already_subscribed: true,
new_episodes: 0,
}))
})
.await
}
/// The podcast `url` resolves to on this device (feed aliases included),
/// when it is subscribed. Blocking.
pub(crate) fn subscribed_podcast(store: &PodcastStore, url: &FeedUrl) -> Result<Option<PodcastId>> {
let id = store.resolve_podcast_id(url)?;
let subscribed = store
.subscription(&id)?
.is_some_and(|record| record.subscribed);
Ok(subscribed.then_some(id))
}
fn knows(store: &PodcastStore, url: &FeedUrl) -> Result<bool> {
let id = store.resolve_podcast_id(url)?;
Ok(store.podcast(&id)?.is_some() || store.subscription(&id)?.is_some())
@@ -324,7 +368,7 @@ async fn fetch_and_apply(
/// Parses a feed document on the blocking pool; relative URLs resolve
/// against where the document was served from.
async fn parse(body: Vec<u8>, base: &FeedUrl) -> Result<ParsedFeed> {
pub(crate) async fn parse(body: Vec<u8>, base: &FeedUrl) -> Result<ParsedFeed> {
let base = base.as_str().to_string();
blocking(move || {
parse_feed_with_base(&body, Some(&base)).map_err(|err| anyhow!("unusable feed: {err}"))
+63 -17
View File
@@ -947,12 +947,7 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) {
let empty_results = SearchResults::default();
let results = match &search.results {
Some(results) => results,
None if !state.search.fed_tracks.is_empty()
|| !state.search.fed_artists.is_empty()
|| state.search.fed_loading =>
{
&empty_results
}
None if state.search.has_federated() => &empty_results,
None => {
let hint = if search.query.is_empty() {
"type to search artists, releases and tracks"
@@ -967,11 +962,7 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) {
return centered_line(frame, inner, line);
}
};
if results.is_empty()
&& state.search.fed_tracks.is_empty()
&& state.search.fed_artists.is_empty()
&& !state.search.fed_loading
{
if results.is_empty() && !state.search.has_federated() {
return centered_line(frame, inner, Line::styled("nothing found", theme::dim()));
}
@@ -1037,15 +1028,12 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) {
}
}
// Federated section: artists whose card can be assembled, then tracks
// (both marked with the owning peers).
if !state.search.fed_tracks.is_empty()
|| !state.search.fed_artists.is_empty()
|| state.search.fed_loading
{
// (both marked with the owning peers), then public podcast cards.
if state.search.has_federated() {
if !rows.is_empty() {
rows.push((Line::default(), None, None));
}
let header = if state.search.fed_loading {
let header = if state.search.fed_loading || state.search.fed_podcasts_loading {
"Federation · searching…"
} else {
"Federation"
@@ -1100,6 +1088,23 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) {
));
index += 1;
}
// Podcasts carry an explicit type marker: they are not music and
// Enter opens their public card, never plays anything.
if !state.search.fed_podcasts.is_empty() {
rows.push((
Line::styled("Podcasts · public cards", theme::header_for(state)),
None,
None,
));
}
for hit in &state.search.fed_podcasts {
rows.push((
podcast_hit_line(state, hit),
Some(podcast_hit_meta(state, hit)),
Some(index),
));
index += 1;
}
}
// Absolute cursor indices covered by an active Shift-V range in the
@@ -1145,6 +1150,47 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) {
}
}
/// One public podcast in the search results: the `podcast` type marker,
/// the title and the claimed author.
fn podcast_hit_line(
state: &AppState,
hit: &crate::podcasts::discovery::PodcastHit,
) -> Line<'static> {
let card = &hit.hit.card;
let mut detail = String::from(" ");
if let Some(author) = &card.author {
detail.push_str(author);
detail.push_str(" · ");
}
detail.push_str("open the card");
Line::from(vec![
Span::styled(
format!("[{}] ", hit.hit.kind().as_str()),
theme::accent_for(state),
),
Span::raw(card.title.clone()),
Span::styled(detail, theme::dim()),
])
}
/// Right column of a podcast hit: subscribed here, or how many devices
/// publish the card (not a subscriber count).
fn podcast_hit_meta(state: &AppState, hit: &crate::podcasts::discovery::PodcastHit) -> String {
if state.podcasts.subscribed_to(hit) {
return "✓ subscribed".to_string();
}
let mut meta = match hit.hit.card.episode_count {
Some(count) => format!("{count} ep · "),
None => String::new(),
};
let publishers = hit.hit.publishers.len();
meta.push_str(&format!(
"{publishers} publisher{}",
if publishers == 1 { "" } else { "s" }
));
meta
}
fn draw_similarity_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) {
let search = &state.search;
let status = if search.fed_loading {
+292
View File
@@ -4,6 +4,7 @@ mod federation;
pub(crate) mod global;
mod logs;
mod playlists;
mod podcast_card;
mod podcasts;
mod popup;
#[cfg(test)]
@@ -181,6 +182,297 @@ mod tests {
}
}
#[test]
fn podcast_share_state_is_shown_in_the_list_and_details() {
use crate::podcasts::publication::{Discovery, Publication};
let mut state =
podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 0, 3, 0)]);
state.podcasts.selected = crate::app::state::PODCAST_ACTION_ROWS;
let screen = render(&state, 110, 30);
assert!(screen.contains("private (not shared"), "{screen}");
assert!(!screen.contains("shared · 3 ep"), "{screen}");
let mut row = podcast_fixtures::row("Test Show", 0, 3, 0);
row.summary.shared = true;
let mut state = podcast_fixtures::ready_state(vec![row]);
state.podcasts.selected = crate::app::state::PODCAST_ACTION_ROWS;
state.podcasts.publication.discovery = Discovery::Running { peers: 2 };
state
.podcasts
.publication
.podcasts
.insert(podcast_fixtures::podcast_id(), Publication::Published);
let screen = render(&state, 110, 30);
assert!(screen.contains("shared · 3 ep"), "{screen}");
assert!(screen.contains("shared · published from"), "{screen}");
state.podcasts.publication.podcasts.insert(
podcast_fixtures::podcast_id(),
Publication::HeldBack(Vec::new()),
);
let screen = render(&state, 110, 30);
assert!(screen.contains("held back"), "{screen}");
// Restarted with other devices in the group: not published before
// a sync with one of them.
state.podcasts.publication.podcasts.insert(
podcast_fixtures::podcast_id(),
Publication::WaitingForDevices,
);
let screen = render(&state, 110, 30);
assert!(screen.contains("waiting for a sync"), "{screen}");
assert!(!screen.contains("published from"), "{screen}");
state.podcasts.publication.discovery = Discovery::Off("federation is off".into());
let screen = render(&state, 110, 30);
assert!(screen.contains("not published:"), "{screen}");
// Sharing turned off here: until a pass revoked the card, the panel
// does not claim the podcast is simply private.
state.podcasts.publication.discovery = Discovery::Running { peers: 2 };
state
.podcasts
.publication
.podcasts
.insert(podcast_fixtures::podcast_id(), Publication::Published);
state
.podcasts
.publication
.note_revocation(&podcast_fixtures::podcast_id(), true);
let screen = render(&state, 110, 30);
assert!(screen.contains("private · revoking the"), "{screen}");
if let Some(crate::app::state::Loadable::Ready(rows)) = &mut state.podcasts.list {
rows[0].summary.shared = false;
}
let screen = render(&state, 110, 30);
assert!(screen.contains("private · revoking the"), "{screen}");
assert!(!screen.contains("private (not shared"), "{screen}");
state.podcasts.publication.discovery = Discovery::Off("federation is off".into());
let screen = render(&state, 110, 30);
assert!(screen.contains("may not be revoked yet:"), "{screen}");
assert!(screen.contains("federation is off"), "{screen}");
state.podcasts.publication.unrevoked.clear();
let screen = render(&state, 110, 30);
assert!(screen.contains("private (not shared"), "{screen}");
}
#[test]
fn the_podcast_card_scrolls_exactly_to_its_last_line() {
use crate::app::state::Popup;
use crate::app::update::podcast_discovery::card_key;
use crossterm::event::KeyCode;
let mut state = search_with_podcasts();
let mut hit = state.search.fed_podcasts[1].clone();
// Long words word-wrap into far more rows than their character
// count suggests (one 50-character word per 90-column row).
let word = "x".repeat(50);
hit.hit.card.description = Some(vec![word.as_str(); 30].join(" "));
state.popup = Some(Popup::PodcastCard {
hit: Box::new(hit),
preview: None,
scroll: 0,
max_scroll: std::cell::Cell::new(u16::MAX),
});
let last_line = "e — прочитать ленту";
let screen = render(&state, 110, 30);
assert!(!screen.contains(last_line), "below the fold:\n{screen}");
// Paging far past the end stops at the last line ...
for _ in 0..20 {
let popup = state.popup.take().unwrap();
assert_eq!(card_key(&mut state, popup, KeyCode::PageDown), None);
}
let screen = render(&state, 110, 30);
assert!(screen.contains(last_line), "{screen}");
let Some(Popup::PodcastCard {
scroll, max_scroll, ..
}) = &state.popup
else {
panic!("the card is open");
};
assert_eq!(*scroll, max_scroll.get());
let end = *scroll;
// ... and one step back moves the view at once.
let popup = state.popup.take().unwrap();
card_key(&mut state, popup, KeyCode::Up);
assert!(matches!(
&state.popup,
Some(Popup::PodcastCard { scroll, .. }) if *scroll == end - 1
));
}
/// Search view with a federated artist and two public podcast cards;
/// the first podcast is subscribed on this device.
fn search_with_podcasts() -> AppState {
use crate::podcasts::discovery::{PodcastHit, test_hit};
let mut state =
podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 0, 3, 0)]);
state.active_tab = Tab::Global;
state.search.query = "show".into();
state.search.results = Some(Default::default());
state.search.fed_artists = vec![crate::federation::FedArtistHit {
name: "Show Band".into(),
peers: 2,
}];
let mut other = test_hit("https://feeds.example.test/other.xml", "Other Show");
other.card.author = None;
state.search.fed_podcasts = vec![
PodcastHit::new(test_hit("https://example.test/feed.xml", "Test Show")),
PodcastHit::new(other),
];
state.global.stack.push(GlobalView::Search { cursor: 1 });
state
}
#[test]
fn search_marks_podcast_hits_apart_from_music() {
let screen = render(&search_with_podcasts(), 120, 20);
assert!(screen.contains("Federation"), "{screen}");
assert!(
screen.contains("Show Band artist · open the card"),
"{screen}"
);
assert!(screen.contains("Podcasts · public cards"), "{screen}");
assert!(
screen.contains("[podcast] Test Show Ferris Crab · open the card"),
"{screen}"
);
assert!(
screen.contains("[podcast] Other Show open the card"),
"{screen}"
);
assert!(screen.contains("✓ subscribed"), "{screen}");
assert!(screen.contains("12 ep · 1 publisher"), "{screen}");
// The podcasts come after the music rows.
let artist = screen.find("Show Band").unwrap();
let podcast = screen.find("[podcast]").unwrap();
assert!(artist < podcast, "{screen}");
}
#[test]
fn podcast_card_offers_subscribe_or_shows_already_subscribed() {
use crate::app::state::{Loadable, Popup};
use crate::podcasts::discovery::{FeedPreview, PreviewEpisode};
let mut state = search_with_podcasts();
let mut hit = state.search.fed_podcasts[1].clone();
hit.hit.claimed_feed_urls = vec![music_dht::podcast_dht::ClaimedFeedUrl {
feed_url: music_dht::podcast::FeedUrl::parse("https://elsewhere.test/claimed.xml")
.unwrap(),
publishers: hit.hit.publishers.clone(),
}];
state.popup = Some(Popup::PodcastCard {
hit: Box::new(hit.clone()),
preview: None,
scroll: 0,
max_scroll: std::cell::Cell::new(u16::MAX),
});
let screen = render(&state, 110, 40);
assert!(screen.contains("[podcast] Other Show"), "{screen}");
assert!(screen.contains("они не проверены"), "{screen}");
assert!(screen.contains("Категории: Technology"), "{screen}");
assert!(
screen.contains("Выпусков: 12 · последний 2024-06-15"),
"{screen}"
);
assert!(
screen.contains("Опубликовали: 1 устройство (не число подписчиков"),
"{screen}"
);
assert!(
screen.contains("Лента: https://feeds.example.test/other.xml"),
"{screen}"
);
assert!(
screen.contains("(не проверен, не используется): https://elsewhere.test/claimed.xml"),
"{screen}"
);
assert!(screen.contains("[ Подписаться ]"), "{screen}");
assert!(
screen.contains("e — прочитать ленту без подписки"),
"{screen}"
);
assert!(screen.contains("enter подписаться"), "{screen}");
assert!(!screen.contains("Уже подписан"), "{screen}");
state.popup = Some(Popup::PodcastCard {
hit: Box::new(hit),
preview: Some(Loadable::Ready(FeedPreview {
title: "Other Show (feed)".into(),
episode_count: 3,
seasons: vec![(Some(1), 2), (None, 1)],
episodes: vec![PreviewEpisode {
title: "Pilot".into(),
season: Some(1),
episode_number: Some(1),
published_at_ms: Some(1_718_445_600_000),
duration_ms: Some(2_700_000),
}],
moved_to: None,
subscribed_as: None,
})),
scroll: 0,
max_scroll: std::cell::Cell::new(u16::MAX),
});
let screen = render(&state, 110, 40);
assert!(
screen.contains("Название в ленте: Other Show (feed)"),
"{screen}"
);
assert!(
screen.contains("В ленте: 3 выпуска · сезон 1: 2, без сезона: 1"),
"{screen}"
);
assert!(
screen.contains("• Pilot S1E1 · 2024-06-15 · 45:00"),
"{screen}"
);
assert!(screen.contains("… и ещё 2"), "{screen}");
// The subscribed podcast: «Уже подписан», Enter opens it.
state.popup = Some(Popup::PodcastCard {
hit: Box::new(state.search.fed_podcasts[0].clone()),
preview: None,
scroll: 0,
max_scroll: std::cell::Cell::new(u16::MAX),
});
let screen = render(&state, 110, 40);
assert!(screen.contains("✓ Уже подписан"), "{screen}");
assert!(screen.contains("enter открыть"), "{screen}");
assert!(!screen.contains("[ Подписаться ]"), "{screen}");
}
#[test]
fn podcast_share_confirmation_lists_the_warnings_in_russian() {
let mut state =
podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 0, 1, 0)]);
state.popup = Some(crate::app::state::Popup::ConfirmPodcastShare {
podcast_id: podcast_fixtures::podcast_id(),
title: "Test Show".into(),
urls: crate::podcasts::publication::ConfirmedUrls {
feed_url: music_dht::podcast::FeedUrl::parse(
"https://example.test/feed.xml?token=abc",
)
.unwrap(),
id_feed_url: None,
},
warnings: vec!["в адресе ленты есть параметр «token», похожий на ключ доступа".into()],
already_shared: false,
});
let screen = render(&state, 100, 30);
assert!(
screen.contains("Поделиться подкастом «Test Show»"),
"{screen}"
);
assert!(screen.contains("Адрес похож на личный"), "{screen}");
assert!(screen.contains("параметр «token»"), "{screen}");
assert!(screen.contains("feed.xml?token=abc"), "{screen}");
assert!(
screen.contains("enter/y опубликовать · esc/n отмена"),
"{screen}"
);
assert!(!screen.contains("x не делиться"), "{screen}");
}
#[test]
fn podcast_seasons_and_episodes_render_progress() {
use music_dht::podcast::ProgressStatus;
+284
View File
@@ -0,0 +1,284 @@
//! The public podcast card opened from the search results. In Russian, like
//! the share confirmation: «Подписаться» / «Уже подписан» are the actions
//! the requirements name.
//!
//! Everything but the origin feed URL is a publisher's claim and is shown as
//! such; the episode preview comes from the feed itself.
use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
use super::podcasts::{format_date, format_duration_ms};
use super::popup::centered;
use super::theme;
use crate::app::state::{AppState, Loadable};
use crate::podcasts::discovery::{FeedPreview, PodcastHit};
pub(super) fn draw(
frame: &mut Frame,
state: &AppState,
hit: &PodcastHit,
preview: Option<&Loadable<FeedPreview>>,
scroll: u16,
max_scroll: &std::cell::Cell<u16>,
) {
let subscribed =
crate::app::update::podcast_discovery::subscribed_id(state, hit, preview).is_some();
let subscribing = state.podcasts.subscribing;
let lines = card_lines(state, hit, preview, subscribed, subscribing);
let width = 92.min(frame.area().width.saturating_sub(4)).max(30);
let inner_width = width.saturating_sub(2).max(1);
let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
// The height of the word-wrapped text, as it is rendered.
let body_height = u16::try_from(paragraph.line_count(inner_width)).unwrap_or(u16::MAX);
let height = body_height
.saturating_add(4)
.min(frame.area().height.saturating_sub(2));
let area = centered(frame.area(), width, height);
let block = Block::bordered()
.title(" Подкаст · публичная карточка ")
.title_style(theme::header_for(state))
.border_style(theme::strong_border_for(state));
let inner = block.inner(area);
frame.render_widget(Clear, area);
frame.render_widget(block, area);
let [body, footer_area] =
Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).areas(inner);
let last = body_height.saturating_sub(body.height);
max_scroll.set(last);
frame.render_widget(paragraph.scroll((scroll.min(last), 0)), body);
let footer = if subscribed {
"enter открыть · e выпуски · ↑↓ прокрутка · esc закрыть"
} else {
"enter подписаться · e выпуски · ↑↓ прокрутка · esc закрыть"
};
frame.render_widget(
Paragraph::new(Line::styled(footer, theme::dim())).alignment(Alignment::Center),
footer_area,
);
}
fn card_lines(
state: &AppState,
hit: &PodcastHit,
preview: Option<&Loadable<FeedPreview>>,
subscribed: bool,
subscribing: bool,
) -> Vec<Line<'static>> {
let card = &hit.hit.card;
let bold = Style::new().add_modifier(Modifier::BOLD);
let mut lines = vec![
Line::from(vec![
Span::styled("[podcast] ", theme::accent_for(state)),
Span::styled(card.title.clone(), bold),
]),
Line::styled(
"Сведения ниже указали издатели карточки; они не проверены.",
theme::dim(),
),
Line::raw(""),
];
if let Some(author) = &card.author {
lines.push(field("Автор", author.clone()));
}
if !card.categories.is_empty() {
lines.push(field("Категории", card.categories.join(", ")));
}
if let Some(language) = &card.language {
lines.push(field("Язык", language.clone()));
}
let mut episodes = match card.episode_count {
Some(count) => format!("{count}"),
None => "не указано".to_string(),
};
if let Some(latest) = card.latest_episode_at_ms {
episodes.push_str(&format!(
" · последний {}",
format_date(latest.div_euclid(1000))
));
}
lines.push(field("Выпусков", episodes));
let publishers = hit.hit.publishers.len();
lines.push(field(
"Опубликовали",
format!(
"{publishers} {} (не число подписчиков и не знак доверия)",
plural_ru(publishers, "устройство", "устройства", "устройств")
),
));
lines.push(field("Лента", hit.hit.feed_url.as_str().to_string()));
for claim in &hit.hit.claimed_feed_urls {
lines.push(Line::styled(
format!(
"Заявленный новый адрес (не проверен, не используется): {}",
claim.feed_url.as_str()
),
theme::dim(),
));
}
if let Some(link) = &card.link {
lines.push(field("Сайт", link.clone()));
}
if let Some(description) = &card.description {
lines.push(Line::raw(""));
lines.extend(
description
.lines()
.map(|line| Line::raw(line.replace('\t', " "))),
);
}
lines.push(Line::raw(""));
if subscribed {
lines.push(Line::from(vec![
Span::styled(
"✓ Уже подписан",
Style::new().fg(Color::Green).add_modifier(Modifier::BOLD),
),
Span::styled(
" · enter откроет подкаст во вкладке Podcasts",
theme::dim(),
),
]));
} else if subscribing {
lines.push(Line::styled(
"Подписка… читаем ленту",
theme::accent_for(state),
));
} else {
lines.push(Line::from(vec![
Span::styled(
"[ Подписаться ]",
theme::accent_for(state).add_modifier(Modifier::BOLD),
),
Span::styled(
" лента будет прочитана с её сервера; подписка личная и не публикуется",
theme::dim(),
),
]));
}
lines.push(Line::raw(""));
lines.push(Line::styled(
"Сезоны и выпуски (из RSS-ленты)",
theme::header_for(state),
));
match preview {
None => lines.push(Line::styled(
"e — прочитать ленту без подписки (запрос к серверу ленты)",
theme::dim(),
)),
Some(Loadable::Loading) => {
lines.push(Line::styled("читаем ленту…", theme::accent_for(state)))
}
Some(Loadable::Failed(err)) => lines.push(Line::styled(
format!("не удалось прочитать ленту: {err}"),
Style::new().fg(Color::Red),
)),
Some(Loadable::Ready(feed)) => preview_lines(&mut lines, card.title.as_str(), feed),
}
lines
}
fn preview_lines(lines: &mut Vec<Line<'static>>, card_title: &str, feed: &FeedPreview) {
if feed.title != card_title {
lines.push(field("Название в ленте", feed.title.clone()));
}
if let Some(moved) = &feed.moved_to {
lines.push(field("Лента переехала", moved.as_str().to_string()));
}
let seasons: Vec<String> = feed
.seasons
.iter()
.map(|(season, count)| match season {
Some(season) => format!("сезон {season}: {count}"),
None => format!("без сезона: {count}"),
})
.collect();
lines.push(field(
"В ленте",
format!(
"{} {}{}",
feed.episode_count,
plural_ru(feed.episode_count, "выпуск", "выпуска", "выпусков"),
if seasons.is_empty() {
String::new()
} else {
format!(" · {}", seasons.join(", "))
}
),
));
for episode in &feed.episodes {
let mut meta = Vec::new();
match (episode.season, episode.episode_number) {
(Some(season), Some(number)) => meta.push(format!("S{season}E{number}")),
(Some(season), None) => meta.push(format!("S{season}")),
(None, Some(number)) => meta.push(format!("#{number}")),
(None, None) => {}
}
if let Some(published) = episode.published_at_ms {
meta.push(format_date(published.div_euclid(1000)));
}
if let Some(duration) = episode.duration_ms {
meta.push(format_duration_ms(duration));
}
lines.push(Line::from(vec![
Span::raw(format!("• {}", episode.title)),
Span::styled(
if meta.is_empty() {
String::new()
} else {
format!(" {}", meta.join(" · "))
},
theme::dim(),
),
]));
}
if feed.episodes.len() < feed.episode_count {
lines.push(Line::styled(
format!("… и ещё {}", feed.episode_count - feed.episodes.len()),
theme::dim(),
));
}
}
fn field(label: &str, value: String) -> Line<'static> {
Line::from(vec![
Span::styled(format!("{label}: "), theme::dim()),
Span::raw(value),
])
}
/// Russian plural form for `n`.
fn plural_ru(n: usize, one: &'static str, few: &'static str, many: &'static str) -> &'static str {
let (tens, units) = (n % 100, n % 10);
if (11..=14).contains(&tens) {
many
} else if units == 1 {
one
} else if (2..=4).contains(&units) {
few
} else {
many
}
}
#[cfg(test)]
mod tests {
use super::plural_ru;
#[test]
fn russian_plurals() {
let forms = |n| plural_ru(n, "устройство", "устройства", "устройств");
assert_eq!(forms(1), "устройство");
assert_eq!(forms(3), "устройства");
assert_eq!(forms(5), "устройств");
assert_eq!(forms(11), "устройств");
assert_eq!(forms(21), "устройство");
assert_eq!(forms(0), "устройств");
}
}
+62 -2
View File
@@ -17,6 +17,7 @@ use crate::app::state::{
PodcastStoreStatus, SeasonRow,
};
use crate::app::update::podcasts::{played_label, sort_label};
use crate::podcasts::publication::{Discovery, Publication};
/// Width below which the side panel with the cover is dropped.
const SIDE_PANEL_MIN_TOTAL_WIDTH: u16 = 80;
@@ -219,7 +220,7 @@ fn list_row(state: &AppState, row: PodcastListRow, width: u16) -> (Line<'static>
Span::raw(" ")
};
let summary = &podcast.summary;
let meta = if summary.unplayed_count > 0 {
let mut meta = if summary.unplayed_count > 0 {
format!(
"{} unplayed · {} ep",
summary.unplayed_count, summary.episode_count
@@ -227,6 +228,9 @@ fn list_row(state: &AppState, row: PodcastListRow, width: u16) -> (Line<'static>
} else {
format!("{} ep", summary.episode_count)
};
if summary.shared {
meta = format!("shared · {meta}");
}
let title_width = usize::from(width).saturating_sub(2 + meta.width() + 2);
let left = Line::from(vec![
marker,
@@ -293,7 +297,7 @@ fn draw_side_panel(frame: &mut Frame, area: Rect, state: &AppState, podcast: Opt
counts.push_str(&format!(" · {} seasons", summary.season_count));
}
lines.push(Line::styled(counts, theme::dim()));
lines.push(Line::styled("private", theme::dim()));
lines.push(share_status_line(state, podcast));
lines.push(fetch_status_line(state, podcast));
if let Some(description) = &summary.meta.description {
lines.push(Line::raw(""));
@@ -302,6 +306,62 @@ fn draw_side_panel(frame: &mut Frame, area: Rect, state: &AppState, podcast: Opt
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), text_area);
}
/// Public discovery state of one podcast: private, or shared and whether
/// this device publishes its card.
pub(crate) fn share_status_line(state: &AppState, podcast: &PodcastRow) -> Line<'static> {
let tab = &state.podcasts;
if tab.share_busy.contains(podcast.id()) {
return loading_line(state, "saving the share setting…");
}
let report = &tab.publication;
// A card from this device that is still live although the podcast is
// private now (revocation pending, failed, or federation off).
let unrevoked = report.unrevoked.contains(podcast.id());
if !podcast.summary.shared || (unrevoked && !report.podcasts.contains_key(podcast.id())) {
if !unrevoked {
return Line::styled("private (not shared in the federation)", theme::dim());
}
if let Discovery::Off(_) = report.discovery {
return Line::styled(
"private · public card may not be revoked yet: federation is off",
Style::new().fg(Color::Yellow),
);
}
return loading_line(
state,
"private · revoking the public card from this device…",
);
}
let (text, style) = match (&report.discovery, report.podcasts.get(podcast.id())) {
(Discovery::Off(reason), _) => (format!("shared · not published: {reason}"), theme::dim()),
(_, Some(Publication::HeldBack(_))) => (
"shared · held back on this device: the feed URL looks private, \
press Shift+F to confirm"
.to_string(),
Style::new().fg(Color::Yellow),
),
(_, Some(Publication::Failed(error))) => {
(format!("shared · not published: {error}"), error_style())
}
(Discovery::Running { peers: 0 }, Some(Publication::Published)) => (
"shared · published from this device (no discovery peers yet)".to_string(),
theme::accent_for(state),
),
(_, Some(Publication::Published)) => (
"shared · published from this device".to_string(),
theme::accent_for(state),
),
(_, Some(Publication::WaitingForDevices)) => (
"shared · not published yet: waiting for a sync with your other devices".to_string(),
theme::dim(),
),
(Discovery::Starting, _) | (_, Some(Publication::Pending) | None) => {
return loading_line(state, "shared · publishing…");
}
};
Line::styled(text, style)
}
/// Refresh status of one podcast: checking, the last error, or when it was
/// last checked.
fn fetch_status_line(state: &AppState, podcast: &PodcastRow) -> Line<'static> {
+93 -1
View File
@@ -28,6 +28,19 @@ pub fn draw(frame: &mut Frame, state: &AppState) {
Some(Popup::ConfirmPodcastUnsubscribe { title, .. }) => {
draw_confirm_podcast_unsubscribe(frame, state, title)
}
Some(Popup::PodcastCard {
hit,
preview,
scroll,
max_scroll,
}) => super::podcast_card::draw(frame, state, hit, preview.as_ref(), *scroll, max_scroll),
Some(Popup::ConfirmPodcastShare {
title,
urls,
warnings,
already_shared,
..
}) => draw_confirm_podcast_share(frame, state, title, urls, warnings, *already_shared),
Some(Popup::SimilarityPrivacyConsent { .. }) => {
draw_similarity_privacy_consent(frame, state)
}
@@ -1318,6 +1331,85 @@ fn draw_confirm_podcast_unsubscribe(frame: &mut Frame, state: &AppState, title:
);
}
/// Sharing a podcast whose feed URL looks private. In Russian: the warning
/// is about the user's own secret, so it must not be missed.
fn draw_confirm_podcast_share(
frame: &mut Frame,
state: &AppState,
title: &str,
urls: &crate::podcasts::publication::ConfirmedUrls,
warnings: &[String],
already_shared: bool,
) {
let width = 78.min(frame.area().width.saturating_sub(4)).max(30);
let mut lines = vec![
Line::styled(
format!("Поделиться подкастом «{title}» в федерации?"),
ratatui::style::Style::new().add_modifier(ratatui::style::Modifier::BOLD),
),
Line::raw(""),
Line::raw(
"Карточка с адресом RSS-ленты станет видна всем участникам федерации, \
и любой из них сможет читать ленту по этому адресу.",
),
Line::raw(""),
Line::styled(
"Адрес похож на личный:",
ratatui::style::Style::new().fg(ratatui::style::Color::Yellow),
),
];
lines.extend(warnings.iter().map(|warning| {
Line::styled(
format!("• {warning}"),
ratatui::style::Style::new().fg(ratatui::style::Color::Yellow),
)
}));
lines.push(Line::raw(""));
lines.push(Line::styled(
format!("Лента: {}", urls.feed_url.as_str()),
theme::dim(),
));
if let Some(origin) = &urls.id_feed_url {
lines.push(Line::styled(
format!("Исходный адрес: {}", origin.as_str()),
theme::dim(),
));
}
lines.push(Line::raw(""));
lines.push(Line::styled(
"Публикацию можно отозвать, но копии, которые уже получили другие, \
отозвать нельзя. Подтверждение хранится только на этом устройстве.",
theme::dim(),
));
let footer = if already_shared {
"enter/y опубликовать · x не делиться · esc/n отмена"
} else {
"enter/y опубликовать · esc/n отмена"
};
let inner_width = width.saturating_sub(2).max(1);
let body = Paragraph::new(lines).wrap(Wrap { trim: false });
// The height of the word-wrapped text, as it is rendered.
let body_height = u16::try_from(body.line_count(inner_width)).unwrap_or(u16::MAX);
let height = body_height
.saturating_add(4)
.min(frame.area().height.saturating_sub(2));
let area = centered(frame.area(), width, height);
let block = Block::bordered()
.title(" Поделиться в федерации ")
.title_style(theme::header_for(state))
.border_style(theme::strong_border_for(state));
let inner = block.inner(area);
frame.render_widget(Clear, area);
frame.render_widget(block, area);
let [body_area, footer_area] =
Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).areas(inner);
frame.render_widget(body, body_area);
frame.render_widget(
Paragraph::new(Line::styled(footer, theme::dim())).alignment(Alignment::Center),
footer_area,
);
}
fn draw_log_detail(frame: &mut Frame, state: &AppState, entry: &crate::config::logging::LogEntry) {
let width = 90.min(frame.area().width.saturating_sub(4)).max(40);
let height = 18.min(frame.area().height.saturating_sub(2)).max(7);
@@ -1736,7 +1828,7 @@ fn draw_name_entry(
frame.render_widget(Paragraph::new(hint).alignment(Alignment::Center), footer);
}
fn centered(area: Rect, width: u16, height: u16) -> Rect {
pub(super) fn centered(area: Rect, width: u16, height: u16) -> Rect {
let [rect] = Layout::horizontal([Constraint::Length(width.min(area.width))])
.flex(Flex::Center)
.areas(area);
+1 -1
View File
@@ -13,7 +13,7 @@ use semver::Version;
use serde::Deserialize;
use sha2::{Digest, Sha256};
const REPOSITORY: &str = "https://api.github.com/repos/house-of-vanity/furumi_tui";
const REPOSITORY: &str = "https://api.github.com/repos/Furumi-stack/furumi-tui";
const MAX_ARCHIVE: u64 = 512 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
File diff suppressed because it is too large. Load diff
+980 -25
View File
File diff suppressed because it is too large. Load diff