Compare commits

...
Author SHA1 Message Date
sanapachandClaude Opus 5.5 22c3605516 Describe the library import in the changelog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:31:38 +02:00
sanapachandClaude Opus 5.5 f1443948d8 Check the live import test on the page, not the player stores
The live test waited for the notices after Choose and Retry unmatched in the
imports store and read the playlist titles from the library store. It now
waits for the visible status notices and reads the titles of the rendered
playlist rows. Against an instance that already has an administrator it
stops at once with an explanation instead of a 30-second timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:31:06 +02:00
sanapachandClaude Opus 5.5 6dc547e66e Test the library import against a real server and worker
The browser scenario of the import page runs on isolated API fixtures, so
nothing checked the page with the real handlers, the background worker and
the publisher together. tests/browser-library-import-live.cjs seeds a few
library tracks on a fresh disposable instance, uploads a Spotify export
ZIP built in the test and checks that only the playlist files are sent,
the statistics after the worker finishes, the private playlists in source
order without repeats, the filters, a manual choice published by the next
pass, the export flagged as already imported, Retry unmatched, history
deletion that keeps the playlists and the page at phone width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:25:14 +02:00
sanapachandClaude Opus 5.5 4b73de46ec Bound the federated tracks one import lookup keeps
Only each peer catalogue was limited to 4 MiB, so one lookup of up to 16
untrusted owners could bring hundreds of thousands of made-up tracks, and
the pass kept 64 such lookups. A lookup now keeps at most 5,000 tracks; a
catalogue whose new tracks do not fit counts as lost (too large). The pass
remembers 8 lookups, enough for folded spellings and collaboration parts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:51:57 +02:00
sanapachandClaude Opus 5.5 e7d970c60d Search peer catalogues for ambiguous import entries too
REQ §11 repeats the search in the library and the federation for both
unmatched and ambiguous entries, but only unmatched ones waited for the
network stage, so an entry with a weak local candidate (a remaster, a
compilation) never asked a peer, not even on Retry. With the user's
consent an ambiguous entry now waits too, with its candidates. A peer's
match decides it only when no stored candidate is Strong or Exact, as
deciding over both would; otherwise the catalogue candidates are added.
When the search fails, the node is off or the budget is used up, the
entry is ambiguous again with its candidates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:51:57 +02:00
sanapachandClaude Opus 5.5 64cb868b54 Read uploaded exports without building JSON trees
An upload was buffered by an untagged enum, built into a JSON tree,
serialized again and parsed into a second tree, so a 32 MiB body of tiny
entries took gigabytes, and nothing limited parallel uploads. The file
JSON is now kept as written (serde_json raw values) and passed to the
adapter, which borrows each playlist and entry from the bytes and parses
them one at a time. An upload may hold at most 200,000 entries and as many
playlists, more are refused with 413, and only two uploads are read and
parsed at a time. The same body now peaks below 90 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:51:57 +02:00
sanapachandClaude Opus 5.5 5d8568ae96 Test register and playlist row consistency deterministically
The concurrent sync test passed even when the playlist row was written
after the register committed, because nothing held the window open. Row
and table locks now park a removal and an addition between the two
writes, and the register must still show the old state. Consistency
checks also look at every library track in the playlist, not only at
registers that name a local track.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:36:27 +02:00
sanapachandClaude Opus 5.5 ee091b4b6e Apply a playlist item again when PostgreSQL aborts it for a deadlock
Applying an item now changes its register and playlist row in one
transaction, register first. Library cleanup and metadata fixes delete
playlist rows before they detach registers, so the two could deadlock and
the sync exchange failed with the operation already journaled. A deadlock
or serialization failure now runs the item again, up to three times, from
its register. Reordering the locks would instead conflict with the import
publisher, which locks registers before writing playlist rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:36:27 +02:00
sanapachandClaude Opus 5.5 c60fb08b95 Pause an import playlist only for the target the worker saw
The publisher reads the targets once per phase. When the user deleted a
target and asked to recreate it while another playlist was publishing,
the worker reached it with its old view and paused it again, undoing the
request it had already confirmed. A pause now applies only while the
target is still the one the worker read; otherwise the requested rerun
publishes into a new target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:35:19 +02:00
sanapachandClaude Opus 5.5 22e5b515aa Test that Retry unmatched is refused for other users and unfinished imports
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:28:39 +02:00
sanapachandClaude Opus 5.5 2c17c9e4df Accept cancel and recreate of an import only as JSON requests
Both took any POST, so a form of a sibling site that receives the
SameSite=Lax session cookie could cancel or requeue an import. Like every
other change of an import they now need application/json, which a form
cannot send without a preflight; the player already sends it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:28:39 +02:00
sanapachandClaude Opus 5.5 da28e775b3 Index the foreign keys of import receipts and targets
Deleting an import cascades to its receipts once per entry, and deleting
any playlist sets the import targets that point at it to NULL. Without an
index on the referencing columns each of these scanned the whole table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:27:34 +02:00
sanapachandClaude Opus 5.5 b6c2ec7b39 Match the import statistics skeleton and fix the Russian retry notice
The skeleton had four cells in five columns while the statistics have six;
it now inherits the statistics grid on every width. The Russian notice
after Retry promised that the tracks would be found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:21:00 +02:00
sanapachandClaude Opus 5.5 1ab0d3bf57 Keep focus in the import wizard and drop searches after leaving details
The wizard dialog leaves the DOM without close(), so focus fell to the
page body. Closing it now returns focus to the button that opened it, or
to New import, unless it closes to navigate, and each new step focuses the
dialog title. Leaving the details clears a pending entry search, and
entries are not loaded without an import, so /api/imports/null/items is
never requested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:21:00 +02:00
sanapachandClaude Opus 5.5 7af037066e Charge ZIP entries what fflate copies for them
A stored entry is copied by its compressed size, so a record that declares
an original size of zero could still bring hundreds of megabytes, once per
central directory record that points at it. Each extracted file is now
charged the larger of its sizes, a stored entry must declare equal sizes,
and unknown methods and duplicate names are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:19:01 +02:00
sanapachandClaude Opus 5.5 d275e7326b Add the Import library page and wizard to the web player
Import library sits between Followed and Settings in the account menu and
opens #imports: the sources, the history with statistics and links to the
created playlists, and #imports/N with progress, per-playlist results, a
deleted-playlist notice with Create again, and the entries with status and
playlist filters, search, paging and the candidates of doubtful entries to
choose from. Retry unmatched (with the federated search consent), Cancel,
Delete history and a new Spotify sign-in for waiting imports call the
existing /api/imports endpoints. The page polls every 3 s while an import
runs. It follows the player's views, skeletons, dialogs, switches and
phrase table in English and Russian.

The New import wizard picks a source, then the data export or the Spotify
sign-in, then the playlists: imported ones cannot be selected, similar ones
need an explicit confirmation, and federated search is off until the user
turns it on. A ZIP export is opened in the browser with fflate 0.8.2,
vendored with its MIT licence and served at /vendor/fflate-0.8.2.js only
when an archive is picked. Only Playlist*.json and YourLibrary.json are
extracted; archives over 256 MiB, with more than 2,000 entries, more than
256 playlist files or more than 32 MiB declared for them are refused before
anything is decompressed, and a request over 32 MiB is not sent.

Federated tracks can now be removed from a playlist in edit mode:
DELETE /api/player/tracks/content/playlist checks the owner and records the
existing PlaylistTrackRemoved operation. The body-level dialogs get an
Alpine root, which also makes Get app open again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:05:30 +02:00
sanapachandClaude Opus 5.5 4d6a1513d9 Publish matched import entries into private playlists over Device Sync
Each source playlist gets an ordinary private playlist, created with its
PlaylistCreated operation in one transaction even when nothing matched.
Matched entries follow in source order, at most 200 per transaction: the
playlist row, the item register, the existing PlaylistTrackAdded operation
and a receipt are written together, so fed_sync_ops serves as the outbox
and an interrupted batch leaves nothing behind. Locks are taken in a fixed
order (per-user advisory lock, import lease, playlist, fed-device identity,
registers). Registers are only inserted; an item the playlist has or had,
a removal committed to the journal but not yet applied, a repeat or a
receipt keep the publisher from adding it again. A deleted target pauses
publication until POST .../playlists/{pid}/recreate; POST .../resync
retries unmatched entries and appends new matches at the end.

Before each batch the outgoing Device Sync line is measured by serializing
the same parts the exchange sends. Tracks and new playlists are published
while the music snapshot stays within library_import_sync_budget (2 MiB)
and the whole line within 7 MiB; the rest waits as deferred_sync_limit.

Device Sync gets local helpers only: create_owned_playlist_tx is extracted
from the playlist handler, append_in_transaction takes an explicit
position, the two operations have in-transaction variants on
append_local_op, and applying a playlist item writes its register under an
atomic last-writer-wins condition and its playlist row in the same
transaction, so concurrent operations cannot make them diverge. The
protocol and its formats are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 17:46:47 +02:00
sanapachandClaude Opus 5.5 f10e384650 Search peer artist catalogues for unmatched import entries
With the user's consent and federation enabled, entries that the local
library and known federated tracks do not match wait for resolver stage 3.
It looks up each artist group by its original name, its spelling without
Latin diacritics and, if those find nothing, its collaboration parts, and
decides the entries against the federated tracks of the catalogues.

The new artist_catalogs_bounded in the federation client asks at most 16
owners, a given number at a time, in a JoinSet owned by one task; dropping
the stream aborts the search and every catalogue request. The player's
stream_artist_catalogs keeps its behaviour and shares the owner parsing.
Imports search two groups at a time process-wide, give a group 60 s, retry
failed searches after 2/4/8 s, stop after 500 groups or 30 minutes per pass
and cancel running lookups on cancellation or lease loss. Lost catalogues
are counted in the statistics.

POST /api/imports/{id}/items/{item_id}/match takes a stored candidate of
an ambiguous entry for its owner after checking it again, and queues a
finished import so that the choice is published.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 17:16:21 +02:00
sanapachandClaude Opus 5.5 0a258a3e05 Match imported entries against the local library and known federated tracks
Add the matcher and the first two resolver stages of the library import.
The matcher is pure: titles are split into a core, featured artists and
version tags, taken from the album title too, so a remaster or concert
album counts like a marker in the track title. Hard tags (live, remix,
edit and similar) must be equal; remaster, mono, stereo, explicit and
clean never match automatically. A match without a comparable duration
needs the same album, and a single candidate is not a match by itself.
Collaborations are split only into known artists, so "Tyler, The Creator"
stays one artist.

The resolve_local phase matches pending entries by artist group against
the library, then against federated tracks this server already knows from
searches and from the owner's synced likes and playlists, and stores
matched, ambiguous (with up to five candidates) or unmatched decisions
under the lease. A local match without a cached content id is hashed with
ensure_local_content_id from agent_storage_dir, so local imports are
publishable with federation disabled. The network is reached only through
a FederationAccess trait and only with the user's consent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:55:27 +02:00
sanapachandClaude Opus 5.5 ff87d9110d Import Spotify data exports and optionally playlists from the Spotify Web API
Add the Spotify adapter to the library import. The data export path parses
Playlist*.json and YourLibrary.json sent by the browser, tolerates missing
and unexpected keys, keeps the source order and repeats, and stores episodes,
audiobooks, local files and unreadable entries as unsupported instead of
dropping them. The bundled export fixture is synthetic and must be joined by
an anonymized real export before acceptance.

POST /api/imports/preview lists the playlists of an upload and marks those
already imported or similar to an earlier import; POST /api/imports stores
the selected playlists with every entry in one transaction and starts the
worker. Requests are JSON-only and limited to 32 MiB (413). Re-import is
detected per source playlist: a repeat is refused with 409, and a changed
playlist with the same title needs confirm_similar.

The Spotify Web API is optional and enabled by an administrator's client ID
(and redirect URI behind a proxy) in the settings. Sign-in uses PKCE with the
state, verifier and waiting import kept in the session; access tokens stay
only in an in-memory vault for at most 30 minutes. The worker fetches the
selected playlists one by one, honors Retry-After and backs off on server
errors. A missing or expired token parks the import as needs_reauth; signing
in again with the same account continues the same import and skips the
playlists already fetched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:30:07 +02:00
sanapachandClaude Opus 5.5 097812a845 Store library imports and run them as a resumable background job
Add the library_import subsystem core: migration m_0065 with the import,
playlist, item, publication-receipt and attempt tables, the provider-neutral
import model, the adapter trait and the storage layer.

The library_import job claims imports under a two-minute lease that a
heartbeat renews, checks cancellation between phases and resumes an
interrupted import from its stored phase. Matching and publication phases
are placeholders for the following changes. At boot, imports of the previous
process are requeued; a sweeper starts a worker whenever an import waits
without one, so a worker that stops without a server restart is replaced
once its lease expires.

The /api/imports endpoints list the user's imports, show one import with
its playlists and paged entries, cancel it and delete its history while
keeping the created playlists. Every request is scoped to the owner.
GET /imports redirects to the player view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:05:42 +02:00
Aleksandr Bogomiakov 2a7179702b Verify imported audio and keep resolved uploads out of the review queue
Build and Publish / Build and Publish Docker Image (push) Successful in 2m31s
2026-11-24 19:38:16 +02:00
Aleksandr Bogomiakov 2352f359f4 Added GET APP modal 2026-11-24 14:53:38 +02:00
ab a301d89d56 Make music uploads batch-oriented and share the player dialog frame
Build and Publish / Build and Publish Docker Image (push) Successful in 2m18s
2026-11-24 06:02:14 +02:00
ab b6ed286e4d Redesign the download manager around transfer activity
Build and Publish / Build and Publish Docker Image (push) Successful in 2m18s
2026-11-24 05:38:57 +02:00
ab 1803f4bf60 Shorten offline status labels
Build and Publish / Build and Publish Docker Image (push) Successful in 2m18s
2026-11-24 05:20:44 +02:00
ab d32ec66fb0 Distinguish manual offline mode from a lost server connection 2026-11-24 05:19:47 +02:00
ab 84f234bc6e Show a compact full-width offline status banner 2026-11-24 05:17:40 +02:00
ab 44ed0a5715 Show skeletons during library navigation and align popular track scrolling 2026-11-24 05:14:27 +02:00
ab d5d268a767 Redesign player settings and fade in loaded artwork
Build and Publish / Build and Publish Docker Image (push) Successful in 3m22s
2026-11-24 04:55:02 +02:00
ab f25519dd24 Release Furumusic v0.16.3
Build and Publish / Build and Publish Docker Image (push) Successful in 4m48s
2026-11-24 04:35:54 +02:00
ab 388dc9b745 Animate the account menu and document player motion conventions 2026-11-24 04:35:31 +02:00
ab 88fb82b081 Download and cache the lyrics embedding model when indexing is enabled 2026-11-24 04:34:23 +02:00
ab b095f4aceb Hide uploader identities in shared track details 2026-11-24 04:25:45 +02:00
ab 1354f9c5f0 Play saved audio and display artwork directly from browser storage
Build and Publish / Build and Publish Docker Image (push) Successful in 2m44s
2026-11-24 04:19:25 +02:00
ab 32057fd67b Show the linked build version beside the desktop wordmark
Build and Publish / Build and Publish Docker Image (push) Successful in 2m48s
2026-11-24 03:52:19 +02:00
ab a045ab4fbe Fix offline playback ownership and polish the artist list and desktop sidebar
Build and Publish / Build and Publish Docker Image (push) Successful in 2m44s
2026-11-24 03:40:41 +02:00
ab 656466b176 Filter playlists, group artist tracks and improve playback and cache controls
Build and Publish / Build and Publish Docker Image (push) Successful in 2m46s
2026-11-24 03:15:58 +02:00
ab 2b8dad2139 Add offline listening and a device-local music catalog
Build and Publish / Build and Publish Docker Image (push) Successful in 2m56s
2026-11-24 02:45:38 +02:00
ab af38255440 Keep one like per recording and float the playlist artwork picker
Build and Publish / Build and Publish Docker Image (push) Successful in 4m24s
2026-11-24 02:03:11 +02:00
ab b584e660a4 Unify catalog navigation and playlist editing, align track actions and repair listening totals
Build and Publish / Build and Publish Docker Image (push) Successful in 3m58s
2026-11-24 01:39:34 +02:00
ab 3f5fbdd05a Add a calendar heatmap to personal listening activity 2026-11-24 01:05:05 +02:00
ab 576e802b7a Allow reordering sidebar pins and undoing removals
Build and Publish / Build and Publish Docker Image (push) Successful in 3m16s
2026-11-24 00:47:05 +02:00
ab 8324f256c6 Resolve Unicode artist portraits in listening rankings
Build and Publish / Build and Publish Docker Image (push) Successful in 3m27s
2026-11-24 00:16:04 +02:00
ab bdbee5beb3 Redesign player navigation, add personal listening stats and improve lyrics
Build and Publish / Build and Publish Docker Image (push) Successful in 2m36s
2026-11-23 22:54:51 +02:00
ab bc0a1f38c8 Merge origin/master for Furumusic 0.14.0
Build and Publish / Build and Publish Docker Image (push) Successful in 2m40s
2026-11-23 22:30:22 +02:00
ab 675d6c63cb chore: release v0.14.0 2026-11-23 22:25:14 +02:00
ab ce8f5700ef feat: add similar tracks and artwork preview to now playing 2026-11-23 22:22:09 +02:00
Aleksandr Bogomiakov c7d8672a29 feat: replicate lyrics across federation peers
Build and Publish / Build and Publish Docker Image (push) Successful in 2m36s
2026-11-23 17:06:51 +02:00
ab 50926cc7bb fix: count and play artist guest appearances 2026-11-23 05:57:56 +02:00
212 changed files with 38141 additions and 8040 deletions

No files matched your search

+1
View File
@@ -2,5 +2,6 @@
**/target
**/.claude
**/media
**/similarity-models
**/NUL
**/nul
+9
View File
@@ -0,0 +1,9 @@
# Web player interactions
Give player controls immediate visual feedback. Use short transitions in both directions when menus and dialogs open or close, sections expand or collapse, and items appear or disappear. Match the pace of nearby controls, typically 120–160 ms, and keep the surrounding layout steady.
Honor `prefers-reduced-motion` and keep controls responsive to repeated clicks and keyboard input during transitions.
Build player dialogs with the shared native `player-dialog` and `player-dialog-surface` styles. Use `player/dialog_header.html` for the title bar and `player/dialog_close.html` for the close control in custom headers. Keep feature-specific styles in the dialog body.
When a view or section waits for its first data, show a quiet skeleton matching its final layout, including on mobile. Reuse the player's card and track placeholders. Keep existing content visible during background refreshes and pagination. Replace placeholders as soon as data, an empty result, or an error arrives. Announce loading once to assistive technology and keep decorative shapes hidden from it.
+165
View File
@@ -2,6 +2,15 @@
## Unreleased
- Import library in the account menu moves Spotify playlists and Liked Songs
into private Furumi playlists, from a "Download your data" export or, when an
administrator sets a Spotify client ID, directly from the Spotify Web API.
Tracks are matched strictly against the local library and known federated
tracks; with explicit consent, peer catalogues are searched too. Unmatched,
ambiguous and unsupported entries stay visible for a manual choice or a later
retry. Imports run as a resumable background job, survive restarts and
publish through Device Sync within a bounded snapshot budget.
- Federated tracks can be removed from a playlist in the web player.
- Content-bound lyrics with alternative plain/LRC versions, an optional Frid
protocol and HTTP APIs that leave existing audio/catalog clients compatible.
- Daily LRCLIB enrichment with durable positive/negative caching, metadata
@@ -10,6 +19,162 @@
- Desktop/mobile lyrics view following playback, individual track previews,
availability icons, and local version editing in the admin track editor.
## v0.16.7 — 2026-11-24
- Approving an upload in the admin panel now finds its audio in the inbox.
An import with missing audio reports an error before adding the track.
- The review queue closes uploads that already have a verified copy in the
library. Dismissing a review keeps its audio and prevents the same file
from returning on the next scan. A replacement file can still be imported.
- Recording conflicts have a separate queue. An administrator can check edited
metadata, keep a separate recording, or dismiss the upload.
- The account menu includes a Get App dialog for downloading the Furumi TUI.
## v0.16.6 — 2026-11-24
- Add music opens with file and folder upload, with torrent and YouTube forms
alongside it. The form shows the latest transfer and a personal track and
release count. File selection is available on demand.
- Upload history groups each submission into one entry. Checkboxes remove a
selection across upload types while preserving the music and ongoing jobs.
- Settings and Add music share a dialog frame, title bar and close control.
## v0.16.5 — 2026-11-24
- Downloads opens with transfer activity across torrents, YouTube and local
files. Filter by status or open a job to see its details.
- On phones, torrent file selection has a dedicated scrollable view with the
download action in reach. Uploads awaiting review remain accessible from
the same manager.
## v0.16.4 — 2026-11-24
- Artist, playlist and release pages immediately show the outline of the artwork
and track list while opening. The catalog and initial search use matching
placeholders as well.
- Expanding an artist's popular tracks scrolls to the section heading.
Collapsing the list returns to the top of the artist page.
- A compact full-width offline banner shows whether the listener enabled the
mode manually or the server is unreachable.
- Personal settings group language and Last.fm side by side and bring offline
storage, the cache limit and saved music together in one compact panel.
- Connected devices use compact lists with counts, separate mobile tabs for
browser sessions and trusted devices, and on-demand pairing and sync details.
- Artwork fades in over 100 ms after loading, including covers from the offline
cache. Reduced-motion preferences skip the fade.
## v0.16.3 — 2026-11-24
- Furumi downloads the lyrics search model when indexing is enabled and reuses
it from the audio models directory. This removes about 487 MB of uncompressed
model files from the Docker image.
- Shared track details omit the uploader's name.
- The account menu opens and closes with a short animation on desktop and mobile
and respects the device's reduced motion preference.
## v0.16.2 — 2026-11-24
- Saved tracks and their likes load when the browser loses its connection.
Federation streams close while offline and reconnect when the server returns.
- Only the device already playing a saved track automatically continues offline.
Remote controller tabs stay paused. The account menu explains offline mode,
and a soft yellow label beside search shows when it is active.
- Collapsing popular tracks on an artist page returns the list to the position
where it was expanded.
- The desktop sidebar now has a `#furumi` wordmark with an embedded monospace
font and a subtle click animation that respects reduced motion. The build
version beside it links to the project repository.
## v0.16.1 — 2026-11-24
- Artist pages show five distinct popular titles at first. Matching titles are
grouped regardless of capitalization, with each recording available from its
branch button. A slim control below the list quickly expands or collapses
the top 50 and respects reduced-motion settings.
- The bottom player uses a shorter, responsive grid for playback, seeking and
track actions on desktop and mobile.
- Saved music in account settings opens a searchable, sortable, paginated cache
manager. It shows download and last-played dates, play counts, audio details
and sizes. Cleanup by date previews the number of recordings and the space
that removing them would free, including shared audio and artwork.
- The account menu shows cache usage against the configured limit and stays
open when interacting with its controls. Unpin notifications can be dismissed early.
- Playlists and Liked songs have an in-list search by track title or artist.
Matching rows animate into place and retain their original playback and edit positions.
## v0.16.0 — 2026-11-24
- Added opt-in offline listening to the web player. Starting a music track saves
the recording on this device with its catalog entries, available artwork and lyrics.
Saved music can be searched, played and browsed through artist and release pages.
- The account menu shows cache usage and switches the player to local playback.
Server outages activate offline listening automatically until the instance returns.
- Cache management includes individual removal and a logarithmic size limit from
100 MB to 512 GB, initially 3 GB. Downloads pause when the cache fills.
## v0.15.3 — 2026-11-24
- Listening by day can display a calendar heatmap shaded by daily play count.
Select a day to open its history, or select the last 365 days for a full year.
The player remembers the chart style in the browser.
- Fixed inflated listening time from older web clients. Existing affected plays
are corrected on upgrade. Both daily charts now show play count and listening
time together, and the selected day's history shows its total play count.
- Moved My listening into the account menu on desktop and mobile.
- Catalog now brings All music, Playlists and My uploads together. Personal
playlists appear first, followed by available public playlists. Followed
artists are accessible from the account menu.
- Playlist headers show release artwork as a collage and keep the pin on the
right. Owners can rename inline, choose up to four images from the playlist,
upload a cover, or restore the automatic collage. The artwork picker floats
beside the cover and keeps the track list in place.
- Liked songs now keeps one entry when several catalog rows share the same
audio. Existing duplicate likes are repaired on upgrade. Different recordings
with the same title can still be liked separately.
- Track rows keep lyrics, popularity and playback controls aligned. The new
actions menu includes sharing, playlists, queueing, track details, similarity
search and downloading where available.
## v0.15.2 — 2026-11-24
- Reorder pinned sidebar shortcuts by dragging or using the arrow keys. The
order is saved for the account on desktop and mobile.
- Unpin shortcuts directly from the menu. Each removal can be undone for ten
seconds to restore the shortcut to its previous position.
## v0.15.1 — 2026-11-24
- My listening now finds local artist portraits for Cyrillic and other Unicode
credits, including older catalog entries with different sort keys.
- A failed listening thumbnail falls back to the original image. A refreshed
ranking row can display new artwork after an earlier image failed.
## v0.15.0 — 2026-11-23
- Desktop and mobile navigation now includes a personal music collection,
account shortcuts and pins for artists, releases and playlists.
- My listening shows personal listening time, daily activity, rankings and a
playable history that can be filtered by day.
- The lyrics preview keeps loading status in the header, offers one-click
copying and lets listeners switch versions from the source names below the text.
- Double-clicking a track row starts playback without selecting the title.
## v0.14.0 — 2026-11-23
- Artist pages count guest appearances as tracks and include them in the Listen
queue. A guest appearance leaves the artist's release count unchanged.
- The player can open an audio similarity search for the current library track.
Hover over the cover to enlarge it, or click to pin it. On touchscreens, tap
the cover in the expanded player.
## v0.13.3 — 2026-11-23
- Discover lyrics versions from federation peers by exact audio content ID.
- Show local lyrics immediately and append peer alternatives without changing
the selected version. Save on listen makes peer lyrics available for further
distribution alongside imported audio.
- Keep outbound lyrics streams alive until the response finishes sending.
## v0.13.2 — 2026-11-23
- Search brings local and federated artists, releases and tracks into the same
Generated
+2 -1
View File
@@ -2062,7 +2062,7 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "furumusic"
version = "0.13.2"
version = "0.16.7"
dependencies = [
"anyhow",
"async-stream",
@@ -2093,6 +2093,7 @@ dependencies = [
"sha2 0.10.9",
"sqlx",
"symphonia",
"tempfile",
"tokio",
"tokio-cron-scheduler",
"tokio-util",
+3 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "furumusic"
version = "0.13.2"
version = "0.16.7"
edition = "2024"
description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL"
@@ -32,7 +32,7 @@ bytes = "1"
tower = "0.5"
base64 = "0.22"
blake3 = "1"
serde_json = "1"
serde_json = { version = "1", features = ["raw_value"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
chrono = "0.4.44"
@@ -40,6 +40,7 @@ symphonia = { version = "0.5", default-features = false, features = ["mp3","aac"
id3 = "1"
encoding_rs = "0.8"
sha2 = "0.10"
tempfile = "3"
md-5 = "0.10"
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] }
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres"] }
-5
View File
@@ -1,7 +1,3 @@
FROM python:3.13-slim-bookworm AS lyrics-model
COPY scripts/fetch-lyrics-model.py /fetch-lyrics-model.py
RUN python /fetch-lyrics-model.py /model
# The prebuilt Linux ONNX Runtime needs Trixie's glibc and libstdc++ at link time and at runtime.
FROM rust:1.97.0-trixie AS chef
@@ -53,7 +49,6 @@ RUN apt-get update \
WORKDIR /data
COPY --from=builder /app/target/release/furumusic /usr/local/bin/furumusic
COPY --from=deno /deno /usr/local/bin/deno
COPY --from=lyrics-model /model /opt/furumusic/models/multilingual-e5-small
RUN FURU_LOG_LEVEL=error furumusic --version
+77
View File
@@ -99,6 +99,83 @@ completion receipts. Retries and restarts retain the choice, avoid duplicates,
and do not re-add tracks subsequently removed by the user. A started batch keeps
its destination for its remaining files.
## Spotify library import
Users start an import from **Import library** in the account menu. The page
lists the available sources, the history of imports with their statistics and
links to the created playlists, and the entries of each import.
Spotify playlists and Liked Songs are imported from the account data export
("Download your data") without any server configuration. The browser opens the
ZIP archive itself and sends only `Playlist*.json` and `YourLibrary.json`;
listening history and account details never leave it. Before anything is
decompressed the browser refuses archives over 256 MiB, archives with more than
2,000 entries, more than 256 playlist files, or playlist files declaring more
than 32 MiB in total. The server parses the files in memory and stores the
entries of the selected playlists. An import request may not exceed 32 MiB. Importing a playlist a second time is refused; a playlist with
the same title and changed contents is imported as a new playlist only after
confirmation.
The Spotify Web API is optional. Register an application on a Spotify Premium
account, add the users to its allowlist (Development Mode admits at most five)
and set **Settings → Spotify Import → Client ID** (`FURU_SPOTIFY_CLIENT_ID`).
Register the redirect URI shown there in the application; set
`FURU_SPOTIFY_REDIRECT_URI` when the public address differs from the one the
administration page is opened at. Spotify requires HTTPS, or HTTP for
`127.0.0.1`. Sign-in uses PKCE, so no client secret is stored. Access tokens
stay in server memory for at most 30 minutes and are dropped once the
playlists are fetched. After a restart or an expired token an import waits for
the user to sign in again and then continues without fetching the playlists it
already has. In Development Mode Spotify reads only the user's own and
collaborative playlists; others are imported from the data export.
Entries are matched against the local library first, then against federated
tracks this server already knows from searches and from the user's synced likes
and playlists; neither step uses the network. A match needs the same title, an
artist in common and the same version markers (live, remix, edit and similar,
also when they appear only in the album title). Remastered, mono, stereo,
explicit and clean versions are never treated as equal automatically, and a
match without a comparable duration needs the same album; doubtful entries are
left for the user to choose. Matched local tracks are hashed for their
federation content id even when federation is disabled, which requires
**Settings → Agent → Storage directory** (`FURU_AGENT_STORAGE_DIR`); without it
they wait as "no content id" and later passes try again.
When the user allows federated search and federation is enabled, entries still
without a match are looked up in the artist catalogues of peers. Only artist
names are sent: the server searches the network for each artist once, asks at
most 16 peers that offer it for their catalogues, four at a time, and spends at
most a minute per artist. Imports of the whole server search two artists at a
time, and one pass searches at most 500 artists for at most 30 minutes; the rest
stays unmatched until **Retry unmatched**. A failed search is repeated after 2, 4
and 8 seconds before the artist is skipped. Catalogues that a peer refuses, that
exceed 4 MiB or that do not arrive in 8 seconds are counted as lost in the import
statistics. Cancelling an import stops its running searches. Without consent, or
with federation disabled, the import makes no network requests.
Doubtful entries keep up to five candidates. The import page lets the owner pick
one; the choice is checked against the stored candidates and published like an
automatic match.
Each source playlist becomes an ordinary private playlist, created even when
nothing matched; Liked Songs becomes "Liked Songs (Spotify)". Matches are added
in source order without repeats and reach paired devices through the usual
Device Sync operations; unmatched entries stay in the import. Every added track
is recorded together with its playlist row and its sync operation in one
transaction, so an interrupted import never leaves half of it behind. **Retry
unmatched** searches again and appends new matches at the end. Tracks the user
added or removed in the playlist, on any device, are left as they are, and a
deleted target playlist pauses publication until the owner asks to recreate it.
Device Sync sends every playlist item in each exchange and receivers reject
lines over 8 MiB, so the import limits its share. Before each batch it measures
the line the server would send: tracks are published while the music part of
the sync snapshot stays within **2 MiB** and the whole line within 7 MiB; new
playlists count as well. Set `FURU_LIBRARY_IMPORT_SYNC_BUDGET` (bytes) to change
the 2 MiB budget. Tracks beyond it wait as "deferred" and are published by a
later **Retry unmatched** when there is room again. About 3,000 federated
tracks take 1.6 MiB.
## Federation
Federation is optional. Independent Furumusic and Furumi players that use the
+102
View File
@@ -146,3 +146,105 @@ migrated instance with the import agent disabled at `FURU_TEST_URL` (default
`furumi-import-playlist-test-pg` with database `furumi_import_test`, and Playwright
and Chrome configured as above. It uses a local torrent preview fixture and
simulated imported tracks, without downloading external torrents.
## Library import tests
```bash
cargo test library_import
# Disposable PostgreSQL with ICU support; each test creates and drops a unique schema.
FURU_LIBRARY_IMPORT_TEST_DATABASE_URL=postgresql://... cargo test library_import -- --include-ignored
```
The database tests cover per-user isolation, repeated and similar source playlists,
storing a 5000-entry export, exclusive claims, lease ownership, cancellation,
history deletion that keeps target playlists, resumption after a worker stops
without a server restart once its lease expires, continuing the same Spotify
API import after the user signs in again, and resolving a small library with
federation disabled: local matches get content ids from `agent_storage_dir`,
known federated tracks match without the network, and a federation stub that
panics proves no network access without consent. Peer catalogues come from a
fake catalogue source: the tests cover matches through the original, folded and
split artist names, repeated failed searches, lost catalogues, the budget of a
pass, a stopped node, manual choices with tampered candidates, and cancellation
that leaves no catalogue request running. The database needs the `pg_trgm`
extension; the tests install it into `public`.
The publisher tests (`src/library_import/tests/publisher.rs`) run against the
Device Sync tables of the same schema. They cover source order, repeats, empty
playlists, a second pass that adds nothing, Resync appending at the end, tracks
removed by the user or by a committed but not yet applied operation, a
federated track removed in the web player by its content id, deleted
target playlists and recreation, an entry failing after its operation was
recorded, registers written concurrently, deletions from the web and from
another device during a batch, older operations that arrive during a batch,
concurrent operations that must keep registers and playlist rows consistent,
two imports of one user publishing in turn, and the Device Sync budget for
tracks and playlists. `library_import_measures_the_outgoing_device_sync_line`
prints the measured line for 3,200 published tracks with `--nocapture`.
`cargo test federation::client` checks bounded artist catalogue lookups without a
database: at most 16 owners and the given number of parallel requests, timeouts,
errors, oversized catalogues, and that dropping a lookup stops its search and
requests.
The matcher's reference table (`src/library_import/matcher/tests.rs`) runs
without a database and documents the matching rules case by case.
The import page has browser-store tests and a browser scenario on the rendered
player with isolated API fixtures; neither needs a server or a database:
```bash
node --test tests/library_import.test.cjs
FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1 cargo test library_import::tests::web
node tests/browser-library-import.cjs
```
The store tests unzip real archives with the vendored fflate and cover the
archive limits (size, entries, playlist files and declared sizes, checked
before decompression), the request limit, the selection of repeated, similar
and unavailable playlists, federated consent, polling, the Spotify sign-in
return and removing a federated track from a playlist. The browser scenario
checks the menu order on desktop and mobile, history polling, that only
`Playlist*.json` and `YourLibrary.json` from a ZIP with listening history reach
the server, the wizard, details, a manual choice, Retry unmatched, history
deletion, continuing a Spotify import after a new sign-in, federated track
removal in a playlist and reduced motion. Set `PLAYWRIGHT_MODULE` and
`CHROME_PATH` as for the other browser tests; `FURU_SCREENSHOT_DIR` chooses
where screenshots go (default `target/`).
`tests/browser-library-import-live.cjs` runs the same page against a real server
and its background worker:
```bash
# Fresh disposable instance; federation disabled, no Spotify client id.
FURU_DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:55432/furumi_libimport_live \
FURU_AGENT_STORAGE_DIR=/tmp/furumi-libimport-storage FURU_FEDERATION_ENABLED=false \
target/release/furumusic -l 127.0.0.1:3020
FURU_TEST_STORAGE_DIR=/tmp/furumi-libimport-storage node tests/browser-library-import-live.cjs
```
Start the instance a second time once the first start has applied the
migrations: on an empty database the scheduler starts before them, and import
workers run only after a restart. The test creates the administrator, seeds
library tracks over `psql` in the disposable container `FURU_TEST_PG_CONTAINER`
(default `furumi-libimport-test-pg`, database `FURU_TEST_DATABASE`, default
`furumi_libimport_live`) and writes their audio files into
`FURU_TEST_STORAGE_DIR`, which must be the instance's absolute
`FURU_AGENT_STORAGE_DIR`. `FURU_TEST_URL` defaults to `http://127.0.0.1:3020`.
It builds a Spotify export ZIP with listening history, checks that only the
playlist files are sent, and waits for the worker: statistics, private playlists
with the matched tracks in source order and without repeats (in the API, the
sidebar and the player), filters for unmatched and unsupported entries, a
manual choice for a remaster found only as the original and published by the
next pass, the same export flagged as already imported, Retry unmatched
appending a track added to the library meanwhile, history deletion that keeps
the playlists, and the page at phone width without horizontal scrolling. Run it
only against a fresh disposable instance and drop its database afterwards.
`src/player/vendor/fflate-0.8.2.min.js` is `umd/index.js` of the npm package
`fflate@0.8.2` (MIT, `src/player/vendor/fflate-LICENSE`), served unchanged at
`/vendor/fflate-0.8.2.js` and loaded only when a user picks an archive.
The Spotify export fixture in `src/library_import/adapters/fixtures/spotify_export/`
is synthetic. Add a fresh anonymized real export next to it before relying on the
parser for a new export format.
+21 -14
View File
@@ -73,8 +73,13 @@ the same stored texts, restricted to visible tracks in that share.
`{ "content_id": "b3:…" | null, "versions": […] }`.
- Public share: `GET /api/player/shares/{token}/lyrics/{track_id}` has the same
membership and visibility checks as shared audio.
- Federated web playback: `GET /api/player/federation/tracks/lyrics` accepts
`owner` and `content_id`, fetching from that peer's optional lyrics protocol.
- Federated web playback: `GET /api/player/federation/tracks/lyrics` discovers
alternatives by `content_id`, with an optional preferred `owner`. The player
displays saved local versions while that lookup runs. With Save on listen
enabled, imported or listened-to tracks also look up versions in the background.
Verified alternatives are saved for locally available audio with a visible
catalog entry and are eligible to serve to other peers. Guest shares read the
local library.
- Frid: `music_dht::lyrics` defines ALPN `furumi/lyrics/1`, capability `lyrics: 1`,
DTOs, validation and bounded JSON read/write helpers. Each direction carries
one JSON document terminated by EOF. Requests include protocol version and
@@ -122,19 +127,21 @@ Source version timestamps and visibility are rechecked before returning tracks,
so removed or edited text cannot be returned from an older memory snapshot.
Rolling replicas serialize indexing batches with a PostgreSQL advisory lock.
Inference uses Rust `fastembed`/ONNX Runtime on CPU (two inference threads).
The official `intfloat/multilingual-e5-small` FP32 ONNX model and tokenizer are
pinned to revision `614241f622f53c4eeff9890bdc4f31cfecc418b3`, downloaded and
checksum-verified **during Docker build**, and copied to
`/opt/furumusic/models/multilingual-e5-small`. Native ONNX Runtime is linked into
the executable. There are no runtime model downloads or external inference
services. The model adds about 487 MB of uncompressed artifacts to the image.
For development:
When indexing is enabled, Furumusic downloads the official
`intfloat/multilingual-e5-small` FP32 ONNX model and tokenizer from Hugging Face
if they are missing (about 487 MB in total). It checks file integrity against
the pinned revision `614241f622f53c4eeff9890bdc4f31cfecc418b3` and reuses the
cached files on restart.
Rust `fastembed` and ONNX Runtime run inference locally on two CPU threads.
Lyrics and search queries stay on the instance.
```sh
python scripts/fetch-lyrics-model.py target/lyrics-model
export FURU_LYRICS_MODEL_DIR="$PWD/target/lyrics-model"
```
The default model directory is `similarity-models/multilingual-e5-small` under
the server's working directory. In Docker, mount a writable volume at
`/data/similarity-models` to keep both the lyrics and audio models across
container replacements. Set `FURU_LYRICS_MODEL_DIR` to use another directory
for the lyrics model. To prepare an instance without internet access, run
`python scripts/fetch-lyrics-model.py ./multilingual-e5-small` on a connected
machine and copy that directory into the model cache.
The encoder uses attention-mask mean pooling, L2 normalization and E5's
`query:` / `passage:` prefixes. Ranking combines inverse-frequency weighted
+3 -1
View File
@@ -32,7 +32,9 @@ cargo run --locked
The repository also contains a multi-stage `Dockerfile` for building a small
runtime image. A deployment must provide PostgreSQL plus persistent, writable
volumes for the inbox and music library.
volumes for the inbox and music library. Mount a writable volume at
`/data/similarity-models` to reuse downloaded audio and lyrics models when
replacing the container.
## Configuration
+1 -1
View File
@@ -1,4 +1,4 @@
"""Build-time only. Pin official E5 artifacts; never fetch models at runtime."""
"""Pre-populate Furumi's lyrics model directory for installations without internet access."""
import hashlib
import pathlib
import sys
+3
View File
@@ -951,6 +951,9 @@ impl App for AdminApp {
all.extend(cot::db::migrations::wrap_migrations(
crate::youtube::db_migrations::MIGRATIONS,
));
all.extend(cot::db::migrations::wrap_migrations(
crate::library_import::db_migrations::MIGRATIONS,
));
all
}
}
+206
View File
@@ -0,0 +1,206 @@
use super::finalize_review_approval;
use crate::agent::dto::NormalizedFields;
use crate::config::AppConfig;
use crate::scheduler::{JobRegistry, PendingReview};
use cot::App;
use cot::db::Database;
use cot::db::migrations::MigrationEngine;
use sha2::{Digest, Sha256};
use sqlx::PgPool;
#[tokio::test]
#[ignore = "requires disposable PostgreSQL in FURU_IMPORT_TEST_DATABASE_URL"]
async fn review_approval_requires_audio_and_moves_relative_uploads() -> anyhow::Result<()> {
let url = std::env::var("FURU_IMPORT_TEST_DATABASE_URL")?;
let db = Database::new(&url).await?;
let app = crate::admin::AdminApp::new(
Default::default(),
JobRegistry::new().into(),
Default::default(),
);
MigrationEngine::new(app.migrations())?.run(&db).await?;
let pool = PgPool::connect(&url).await?;
let root = tempfile::tempdir()?;
let inbox = root.path().join("inbox");
let library = root.path().join("library");
let config = AppConfig {
agent_inbox_dir: inbox.to_str().unwrap().into(),
agent_storage_dir: library.to_str().unwrap().into(),
..Default::default()
};
let artist = format!("Artist-{}", uuid::Uuid::new_v4());
let fields = NormalizedFields {
artist: Some(artist.clone()),
album: Some("Альбом".into()),
title: Some("Мутанты".into()),
..Default::default()
};
let relative_source = "user_uploads/3/Папка/data.mp3";
let source = inbox.join(relative_source);
let relative_destination = format!("{artist}/Альбом/Мутанты.mp3");
let destination = library.join(&relative_destination);
let bytes = artist.as_bytes();
let sha = format!("{:x}", Sha256::digest(bytes));
let context = serde_json::json!({ "sha256": sha, "file_size": bytes.len() });
let mut review = PendingReview::create(
&db,
0,
"file",
Some(relative_source),
Some(&context.to_string()),
None,
)
.await?;
std::fs::create_dir_all(destination.parent().unwrap())?;
for existing in [None, Some(b"another recording")] {
if let Some(other_bytes) = existing {
std::fs::write(&destination, other_bytes)?;
}
assert!(
finalize_review_approval(&db, &pool, &config, &mut review, &fields, false)
.await
.is_err()
);
assert_eq!(
PendingReview::get_by_id(&db, review.id_val())
.await?
.unwrap()
.status_str(),
"pending"
);
let count: i64 =
sqlx::query_scalar("SELECT COUNT(*) FROM furumusic__media_file WHERE sha256_hash = $1")
.bind(&sha)
.fetch_one(&pool)
.await?;
assert_eq!(count, 0);
}
assert_eq!(std::fs::read(&destination)?, b"another recording");
std::fs::create_dir_all(source.parent().unwrap())?;
std::fs::write(&source, bytes)?;
let mut stale_review = review.clone();
let result = serde_json::to_string(&fields)?;
assert!(
review
.claim_for_processing(&pool, Some(result.clone()))
.await?
);
assert!(!stale_review.claim_for_processing(&pool, None).await?);
// Fail just this upload's catalog insert after the mover publishes its
// collision-suffixed file. The next approval starts with an empty inbox.
let constraint = format!("fail_insert_{}", &sha[..16]);
sqlx::query(&format!(
"ALTER TABLE furumusic__media_file ADD CONSTRAINT {constraint}
CHECK (sha256_hash <> '{sha}') NOT VALID"
))
.execute(&pool)
.await?;
let first_attempt =
finalize_review_approval(&db, &pool, &config, &mut review, &fields, false).await;
sqlx::query(&format!(
"ALTER TABLE furumusic__media_file DROP CONSTRAINT {constraint}"
))
.execute(&pool)
.await?;
let error = first_attempt.unwrap_err();
assert!(format!("{error:#}").contains(&constraint), "{error:#}");
assert!(!source.exists());
let moved = std::fs::read_dir(destination.parent().unwrap())?
.collect::<std::io::Result<Vec<_>>>()?
.into_iter()
.map(|entry| entry.path())
.find(|path| path != &destination)
.unwrap();
assert_eq!(std::fs::read(&moved)?, bytes);
finalize_review_approval(&db, &pool, &config, &mut review, &fields, false).await?;
let mut approved = PendingReview::get_by_id(&db, review.id_val())
.await?
.unwrap();
assert_eq!(approved.status_str(), "approved");
assert_eq!(approved.result_json_str(), result);
assert!(!approved.claim_for_processing(&pool, None).await?);
// A retry after the inbox file was consumed must keep a single playable track.
finalize_review_approval(&db, &pool, &config, &mut review, &fields, false).await?;
let paths: Vec<String> = sqlx::query_scalar(
"SELECT m.file_path FROM furumusic__track t JOIN furumusic__media_file m
ON m.id = t.audio_file_id WHERE m.sha256_hash = $1",
)
.bind(&sha)
.fetch_all(&pool)
.await?;
assert_eq!(paths, [moved.strip_prefix(&library)?.to_str().unwrap()]);
assert_eq!(std::fs::read(&destination)?, b"another recording");
assert_eq!(std::fs::read(&moved)?, bytes);
assert!(!source.exists());
// A recording with the same credits needs an explicit decision. Check
// that the queue can retain both files when the admin chooses to do so.
let second_input = format!("user_uploads/3/{artist}/second.mp3");
let second = inbox.join(&second_input);
std::fs::create_dir_all(second.parent().unwrap())?;
let generated = std::process::Command::new("ffmpeg")
.args([
"-nostdin",
"-v",
"error",
"-f",
"lavfi",
"-i",
"sine=duration=1",
"-metadata",
&format!("title={artist}"),
])
.arg(&second)
.output()?;
anyhow::ensure!(
generated.status.success(),
"{}",
String::from_utf8_lossy(&generated.stderr)
);
let second_bytes = std::fs::read(&second)?;
let second_sha = format!("{:x}", Sha256::digest(&second_bytes));
let second_context = serde_json::json!({"sha256": second_sha, "file_size": second_bytes.len()});
let mut different = PendingReview::create(
&db,
0,
"new_file",
Some(&second_input),
Some(&second_context.to_string()),
Some(&result),
)
.await?;
let error = finalize_review_approval(&db, &pool, &config, &mut different, &fields, false)
.await
.unwrap_err();
assert!(error.is::<crate::agent::dedup::DuplicateReview>());
different.set_approval_error(&db, &error).await?;
let page = super::load_review_page(
&pool,
super::ReviewsQuery {
status: Some("conflict".to_owned()),
search: Some(second_input.clone()),
limit: None,
offset: None,
},
)
.await?;
assert_eq!(page.total, 1);
assert_eq!(page.items[0].status, "conflict");
assert_eq!(std::fs::read(&second)?, second_bytes);
assert!(different.claim_for_processing(&pool, None).await?);
finalize_review_approval(&db, &pool, &config, &mut different, &fields, true).await?;
let second_path: String = sqlx::query_scalar(
"SELECT m.file_path FROM furumusic__track t
JOIN furumusic__media_file m ON m.id = t.audio_file_id WHERE m.sha256_hash=$1",
)
.bind(second_sha)
.fetch_one(&pool)
.await?;
assert_eq!(std::fs::read(library.join(second_path))?, second_bytes);
assert_eq!(std::fs::read(&moved)?, bytes);
assert!(!second.exists());
Ok(())
}
+128 -97
View File
@@ -379,6 +379,8 @@ struct ReviewDto {
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub(super) struct ReviewEditDto {
#[serde(default, skip_serializing)]
import_separately: bool,
title: String,
artist: String,
album: String,
@@ -550,6 +552,10 @@ struct AdminSettingsValues {
youtube_proxy_id: String,
#[serde(default)]
youtube_cookie_id: String,
#[serde(default)]
spotify_client_id: String,
#[serde(default)]
spotify_redirect_uri: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
@@ -622,6 +628,8 @@ struct AdminSettingsSources {
torrent_proxy_id: &'static str,
youtube_proxy_id: &'static str,
youtube_cookie_id: &'static str,
spotify_client_id: &'static str,
spotify_redirect_uri: &'static str,
}
#[derive(Debug, Deserialize)]
@@ -678,6 +686,10 @@ pub(super) struct UpdateSettingsRequest {
youtube_proxy_id: String,
#[serde(default)]
youtube_cookie_id: String,
#[serde(default)]
spotify_client_id: String,
#[serde(default)]
spotify_redirect_uri: String,
}
fn default_similarity_model() -> String {
@@ -1016,34 +1028,23 @@ pub async fn bulk_reviews(
return Json(approve_selected_reviews(&db, pool, &body).await?).into_response();
}
let mode = body.mode.as_deref().unwrap_or("ids");
let affected = if mode == "filter" {
apply_review_filter_action(pool, action, body.filter.unwrap_or_default()).await?
let ids: Vec<i64> = selected_reviews_query(&body)
.build_query_scalar()
.fetch_all(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let affected = if action == "delete" {
scheduler::PendingReview::dismiss(pool, &ids, None).await
} else {
let mut ids = body.ids.unwrap_or_default();
ids.retain(|id| *id > 0);
ids.sort_unstable();
ids.dedup();
if ids.is_empty() {
0
} else if action == "delete" {
crate::scheduler::PendingReview::delete_by_ids(&db, &ids)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
ids.len() as u64
} else {
crate::scheduler::PendingReview::requeue_by_ids(&db, &ids)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
ids.len() as u64
}
};
scheduler::PendingReview::requeue(pool, &ids).await
}
.map_err(|e| cot::Error::internal(e.to_string()))?;
Json(BulkReviewsResponse {
ok: true,
affected,
failed: 0,
skipped: 0,
skipped: ids.len() as u64 - affected,
})
.into_response()
}
@@ -1091,22 +1092,13 @@ async fn approve_selected_reviews(
result.skipped += 1;
continue;
};
if review.status_str() != "pending" {
result.skipped += 1;
continue;
}
// Claim one row at a time so overlapping bulk requests cannot import it twice.
let claimed = sqlx::query(
"UPDATE furumusic__pending_review SET status = 'processing', updated_at = $2 \
WHERE id = $1 AND status = 'pending'",
)
.bind(row.id)
.bind(chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string())
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
if claimed.rows_affected() == 0 {
if review.status_str() != "pending"
|| agent::dedup::DuplicateReview::is_recorded(review.error_message.as_deref())
|| !review
.claim_for_processing(pool, None)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?
{
result.skipped += 1;
continue;
}
@@ -1115,7 +1107,7 @@ async fn approve_selected_reviews(
let normalized = serde_json::from_str::<crate::agent::dto::NormalizedFields>(
review.result_json_str(),
)?;
finalize_review_approval(db, pool, &config, &mut review, &normalized).await
finalize_review_approval(db, pool, &config, &mut review, &normalized, false).await
}
.await;
match approval {
@@ -1123,10 +1115,14 @@ async fn approve_selected_reviews(
Err(error) => {
tracing::error!(review_id = row.id, ?error, "bulk review approval failed");
review
.set_failed(db, &format!("Review approval failed: {error:#}"))
.set_approval_error(db, &error)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
result.failed += 1;
if error.is::<agent::dedup::DuplicateReview>() {
result.skipped += 1;
} else {
result.failed += 1;
}
}
}
}
@@ -1150,23 +1146,54 @@ pub async fn approve_review(
.map_err(|e| cot::Error::internal(e.to_string()))?
.ok_or_else(|| cot::Error::internal("review not found"))?;
let normalized = normalized_from_review_edit(&body);
if body.import_separately
&& !(review.status_str() == "pending"
&& agent::dedup::DuplicateReview::is_recorded(review.error_message.as_deref()))
{
return Ok(json_error(
StatusCode::CONFLICT,
"review has no recording conflict to resolve",
));
}
let result_json = serde_json::to_string(&normalized)
.map_err(|e| cot::Error::internal(format!("failed to serialize review fields: {e}")))?;
review
.set_result_json(&db, result_json)
if !review
.claim_for_processing(pool, Some(result_json))
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
.map_err(|e| cot::Error::internal(e.to_string()))?
{
return Ok(json_error(
StatusCode::CONFLICT,
"review cannot be approved from this status",
));
}
let (live_config, _) = AppConfig::load_with_db(&db).await;
match finalize_review_approval(&db, pool, &live_config, &mut review, &normalized).await {
match finalize_review_approval(
&db,
pool,
&live_config,
&mut review,
&normalized,
body.import_separately,
)
.await
{
Ok(()) => Json(serde_json::json!({ "ok": true })).into_response(),
Err(error) => {
tracing::error!(?error, "review approval failed");
let _ = review.set_rejected(&db).await;
Ok(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
"review approval failed",
))
tracing::error!(review_id, ?error, "review approval failed");
review
.set_approval_error(&db, &error)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
if let Some(conflict) = error.downcast_ref::<agent::dedup::DuplicateReview>() {
Ok(json_error(StatusCode::CONFLICT, &conflict.to_string()))
} else {
Ok(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
"review approval failed",
))
}
}
}
}
@@ -1177,24 +1204,29 @@ async fn finalize_review_approval(
config: &AppConfig,
review: &mut crate::scheduler::PendingReview,
normalized: &crate::agent::dto::NormalizedFields,
import_separately: bool,
) -> anyhow::Result<()> {
let context: serde_json::Value =
serde_json::from_str(review.context_json_str()).unwrap_or_default();
let input_path = review.input_path_str().to_owned();
let stats = crate::scheduler::ProcessingStats::get_by_review_id(db, review.id_val())
.await
.unwrap_or(None);
let model_name = stats.as_ref().map(|s| s.model_name.to_string());
use crate::jobs::inbox_process::ReviewApproval;
let approval = if import_separately {
ReviewApproval::Separate(model_name.as_deref())
} else {
ReviewApproval::Check(model_name.as_deref())
};
crate::jobs::inbox_process::finalize_approved(
db,
pool,
config,
&input_path,
review.input_path_str(),
normalized,
&context,
&config.agent_storage_dir,
model_name.as_deref(),
approval,
)
.await?;
review.set_approved(db).await?;
@@ -1309,6 +1341,23 @@ pub async fn update_settings(
"selected YouTube cookie file is not in the saved cookie file list",
));
}
let spotify_client_id = body.spotify_client_id.trim().to_string();
if spotify_client_id.len() > 128
|| !spotify_client_id
.chars()
.all(|character| character.is_ascii_alphanumeric())
{
return Ok(json_error(
StatusCode::BAD_REQUEST,
"Spotify client ID may contain only letters and digits",
));
}
let spotify_redirect_uri = body.spotify_redirect_uri.trim().to_string();
if let Err(message) =
crate::library_import::providers::spotify_api::validate_redirect_uri(&spotify_redirect_uri)
{
return Ok(json_error(StatusCode::BAD_REQUEST, message));
}
let download_proxies_json = serde_json::to_string(&download_proxies)
.map_err(|error| cot::Error::internal(error.to_string()))?;
let fields = [
@@ -1390,6 +1439,8 @@ pub async fn update_settings(
("torrent_proxy_id", torrent_proxy_id),
("youtube_proxy_id", youtube_proxy_id),
("youtube_cookie_id", youtube_cookie_id),
("spotify_client_id", spotify_client_id),
("spotify_redirect_uri", spotify_redirect_uri),
];
for (key, value) in fields {
let mut entry = ConfigEntry::new(key.to_string(), value);
@@ -1738,6 +1789,8 @@ fn settings_dto(
torrent_proxy_id: config.torrent_proxy_id,
youtube_proxy_id: config.youtube_proxy_id,
youtube_cookie_id: config.youtube_cookie_id,
spotify_client_id: config.spotify_client_id,
spotify_redirect_uri: config.spotify_redirect_uri,
},
sources: AdminSettingsSources {
auth_password_enabled: sources.auth_password_enabled.code(),
@@ -1776,6 +1829,8 @@ fn settings_dto(
torrent_proxy_id: sources.torrent_proxy_id.code(),
youtube_proxy_id: sources.youtube_proxy_id.code(),
youtube_cookie_id: sources.youtube_cookie_id.code(),
spotify_client_id: sources.spotify_client_id.code(),
spotify_redirect_uri: sources.spotify_redirect_uri.code(),
},
}
}
@@ -3165,12 +3220,12 @@ async fn load_review_page(pool: &PgPool, query: ReviewsQuery) -> anyhow::Result<
let total_all = count_reviews(pool, None, search_pattern.clone()).await?;
let status_counts = load_review_status_counts(pool, None, search_pattern.clone()).await?;
let mut qb = QueryBuilder::<Postgres>::new(
let mut qb = QueryBuilder::<Postgres>::new(format!(
"SELECT id, job_run_id, review_type::text AS review_type, input_path, context_json, \
result_json, status::text AS status, created_at::text AS created_at, \
result_json, {REVIEW_QUEUE_STATUS} AS status, created_at::text AS created_at, \
updated_at::text AS updated_at, error_message \
FROM furumusic__pending_review WHERE 1=1",
);
));
push_review_filters(&mut qb, status.clone(), search_pattern.clone());
qb.push(" ORDER BY id DESC LIMIT ");
qb.push_bind(limit);
@@ -3214,12 +3269,12 @@ async fn load_review_status_counts(
status: Option<String>,
search_pattern: Option<String>,
) -> anyhow::Result<Vec<StatusCountDto>> {
let mut qb = QueryBuilder::<Postgres>::new(
"SELECT status::text AS status, COUNT(*) AS count \
let mut qb = QueryBuilder::<Postgres>::new(format!(
"SELECT {REVIEW_QUEUE_STATUS} AS status, COUNT(*) AS count \
FROM furumusic__pending_review WHERE 1=1",
);
));
push_review_filters(&mut qb, status, search_pattern);
qb.push(" GROUP BY status ORDER BY status");
qb.push(" GROUP BY 1 ORDER BY 1");
let rows = qb
.build_query_as::<StatusCountRow>()
@@ -3234,13 +3289,18 @@ async fn load_review_status_counts(
.collect())
}
// A recording conflict is still pending a human decision. Project it as its
// own queue so old review rows and new decisions share the same filters.
const REVIEW_QUEUE_STATUS: &str = "CASE WHEN status = 'pending' AND \
starts_with(error_message, 'Duplicate check needs review:') THEN 'conflict' ELSE status::text END";
fn push_review_filters(
qb: &mut QueryBuilder<'_, Postgres>,
status: Option<String>,
search_pattern: Option<String>,
) {
if let Some(status) = status {
qb.push(" AND status = ");
qb.push(" AND ").push(REVIEW_QUEUE_STATUS).push(" = ");
qb.push_bind(status);
}
if let Some(pattern) = search_pattern {
@@ -3353,6 +3413,7 @@ fn review_edit_dto_from_json(result_json: &str) -> ReviewEditDto {
return ReviewEditDto::default();
};
ReviewEditDto {
import_separately: false,
title: normalized.title.unwrap_or_default(),
artist: normalized.artist.unwrap_or_default(),
album: normalized.album.unwrap_or_default(),
@@ -3434,40 +3495,6 @@ fn media_tags(row: &ReviewMediaRow) -> Vec<TagDto> {
tags
}
async fn apply_review_filter_action(
pool: &PgPool,
action: &str,
filter: ReviewFilter,
) -> cot::Result<u64> {
let status = normalize_status(filter.status.as_deref());
let search_pattern = clean_search(filter.search.as_deref()).map(|s| format!("%{s}%"));
let result = if action == "delete" {
let mut qb =
QueryBuilder::<Postgres>::new("DELETE FROM furumusic__pending_review WHERE 1=1");
push_review_filters(&mut qb, status, search_pattern);
qb.build()
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?
} else {
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
let mut qb = QueryBuilder::<Postgres>::new(
"UPDATE furumusic__pending_review \
SET status = 'queued', error_message = NULL, updated_at = ",
);
qb.push_bind(now);
qb.push(" WHERE 1=1");
push_review_filters(&mut qb, status, search_pattern);
qb.build()
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?
};
Ok(result.rows_affected())
}
async fn load_jobs(
db: &Database,
pool: &PgPool,
@@ -4656,6 +4683,10 @@ fn clean_search(search: Option<&str>) -> Option<String> {
.map(|s| s.chars().take(120).collect())
}
#[cfg(test)]
#[path = "review_approval_tests.rs"]
mod review_approval_tests;
#[cfg(test)]
mod unicode_search_tests {
use super::*;
+19 -1
View File
@@ -11,6 +11,12 @@ use super::dto::NormalizedFields;
#[derive(Debug)]
pub struct DuplicateReview(pub String);
impl DuplicateReview {
pub fn is_recorded(message: Option<&str>) -> bool {
message.is_some_and(|message| message.starts_with("Duplicate check needs review:"))
}
}
impl std::fmt::Display for DuplicateReview {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Duplicate check needs review: {}", self.0)
@@ -242,6 +248,17 @@ async fn probe(path: &Path) -> Result<AudioInfo> {
})
}
pub async fn verify_separate_recording(path: &Path) -> Result<()> {
let info = probe(path)
.await
.context("cannot inspect incoming recording")?;
ensure!(
info.duration > 0.0,
"incoming recording has no audio duration"
);
Ok(())
}
#[derive(Deserialize)]
struct AudioFingerprint {
duration: f64,
@@ -443,7 +460,8 @@ pub async fn merge_existing(
}
// A repeated YouTube import must still resolve to this existing media ID.
if let Some(sha) = context["sha256"].as_str() {
if let Err(error) = crate::import_playlists::link_media(pool, sha, candidate.media_id).await {
if let Err(error) = crate::import_playlists::link_media(pool, sha, candidate.media_id).await
{
tracing::warn!(%error, "could not link deduplicated import to destination playlists");
}
if let Err(error) = sqlx::query(
+57 -5
View File
@@ -21,10 +21,7 @@ pub async fn move_to_storage(
filename: &str,
source: &Path,
) -> anyhow::Result<MoveOutcome> {
let artist_dir = sanitize_dir_name(artist);
let album_dir = sanitize_dir_name(album);
let dest_dir = storage_dir.join(&artist_dir).join(&album_dir);
let dest_dir = album_directory(storage_dir, artist, album);
tokio::fs::create_dir_all(&dest_dir).await?;
let mut dest = dest_dir.join(filename);
@@ -54,6 +51,54 @@ pub async fn move_to_storage(
Ok(MoveOutcome::Moved(dest))
}
fn album_directory(storage_dir: &Path, artist: &str, album: &str) -> PathBuf {
storage_dir
.join(sanitize_dir_name(artist))
.join(sanitize_dir_name(album))
}
/// Recover a file published before an interrupted catalog write, including a
/// destination that move_to_storage renamed to avoid a filename collision.
pub async fn find_moved_file(
storage_dir: &Path,
artist: &str,
album: &str,
filename: &str,
sha256: &str,
) -> anyhow::Result<Option<PathBuf>> {
if sha256.is_empty() {
return Ok(None);
}
let directory = album_directory(storage_dir, artist, album);
let mut entries = match tokio::fs::read_dir(directory).await {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
let name = Path::new(filename);
let stem = name.file_stem().and_then(|s| s.to_str()).unwrap_or("audio");
let ext = name.extension().and_then(|s| s.to_str()).unwrap_or("audio");
let prefix = format!("{stem} [");
let suffix = format!("].{ext}");
while let Some(entry) = entries.next_entry().await? {
let entry_name = entry.file_name();
let Some(entry_name) = entry_name.to_str() else {
continue;
};
let is_collision = entry_name
.strip_prefix(&prefix)
.and_then(|name| name.strip_suffix(&suffix))
.is_some_and(|id| uuid::Uuid::parse_str(id).is_ok());
if (entry_name == filename || is_collision)
&& entry.file_type().await?.is_file()
&& sha256_file(&entry.path()).await? == sha256
{
return Ok(Some(entry.path()));
}
}
Ok(None)
}
/// Copy into the destination filesystem, then expose the complete file without
/// replacing an existing destination. The source remains available on errors.
pub async fn publish_copy(source: &Path, destination: &Path) -> anyhow::Result<()> {
@@ -131,7 +176,14 @@ mod tests {
};
assert_ne!(new, old);
assert_eq!(tokio::fs::read(&old).await.unwrap(), b"original recording");
assert_eq!(tokio::fs::read(new).await.unwrap(), b"different recording");
assert_eq!(tokio::fs::read(&new).await.unwrap(), b"different recording");
let sha256 = sha256_file(&new).await.unwrap();
assert_eq!(
find_moved_file(&storage, "Artist", "Album", "song.mp3", &sha256)
.await
.unwrap(),
Some(new)
);
tokio::fs::remove_dir_all(root).await.unwrap();
}
}
+45 -30
View File
@@ -77,46 +77,61 @@ pub async fn find_similar_releases(
.collect())
}
/// Check if a file with the given SHA-256 hash is actively used in the library.
/// Returns true only if a media_file with this hash exists AND at least one
/// track references it via audio_file_id. Orphaned media_files (no track)
/// are ignored so that re-discovery is possible after the user deletes
/// artists/releases/tracks.
pub async fn file_hash_exists(pool: &PgPool, sha256: &str) -> anyhow::Result<bool> {
sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM furumusic__media_file mf \
JOIN furumusic__track t ON t.audio_file_id = mf.id \
WHERE mf.sha256_hash = $1)",
)
.bind(sha256)
.fetch_one(pool)
.await
.map_err(Into::into)
}
/// Verify the bytes on disk as well as the database hash before dropping an
/// inbox upload. Stale catalog hashes must not discard a replacement file.
pub async fn file_hash_exists_verified(
pub async fn verified_audio_media(
pool: &PgPool,
sha256: &str,
storage_dir: &str,
) -> anyhow::Result<bool> {
let paths: Vec<String> = sqlx::query_scalar(
"SELECT DISTINCT mf.file_path FROM furumusic__media_file mf \
JOIN furumusic__track t ON t.audio_file_id = mf.id \
WHERE mf.sha256_hash = $1",
) -> anyhow::Result<Option<i64>> {
if sha256.is_empty() || storage_dir.is_empty() {
return Ok(None);
}
let paths: Vec<(i64, String)> = sqlx::query_as(
"SELECT mf.id, mf.file_path FROM furumusic__media_file mf
WHERE mf.file_type = 'audio' AND mf.sha256_hash = $1
AND EXISTS (SELECT 1 FROM furumusic__track t WHERE t.audio_file_id = mf.id)
ORDER BY mf.id",
)
.bind(sha256)
.fetch_all(pool)
.await?;
for path in paths {
if paths.is_empty() {
return Ok(None);
}
let library = match tokio::fs::canonicalize(storage_dir).await {
Ok(path) => path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
let mut read_error = None;
for (id, path) in paths {
let path = crate::media_paths::resolve_media_file_path(storage_dir, &path);
if super::mover::sha256_file(&path)
.await
.is_ok_and(|actual| actual == sha256)
{
return Ok(true);
// A legacy absolute path or symlink can point straight back to the
// inbox. It does not provide an independent archived copy.
let physical = match tokio::fs::canonicalize(&path).await {
Ok(physical) if physical.starts_with(&library) => physical,
Ok(_) => continue,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => {
read_error = Some(
anyhow::Error::from(error).context(format!("resolving {}", path.display())),
);
continue;
}
};
match super::mover::sha256_file(&physical).await {
Ok(actual) if actual == sha256 => return Ok(Some(id)),
Ok(_) => {}
Err(error)
if error
.downcast_ref::<std::io::Error>()
.is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) => {}
Err(error) => read_error = Some(error.context(format!("reading {}", path.display()))),
}
}
Ok(false)
match read_error {
Some(error) => Err(error),
None => Ok(None),
}
}
+19 -5
View File
@@ -74,15 +74,29 @@ fn authenticated_user_from_user(user: User) -> Option<AuthenticatedUser> {
/// Return the signed-in identity, including an account awaiting approval.
pub async fn get_session_identity(session: &Session, db: &Database) -> Option<User> {
let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??;
User::get_by_id(db, user_id).await.ok()?
checked_session_identity(session, db).await.ok().flatten()
}
/// Offline-capable routes must distinguish an expired login from a storage outage.
pub(crate) async fn checked_session_identity(
session: &Session,
db: &Database,
) -> cot::Result<Option<User>> {
let Some(user_id) = session
.get::<i64>(SESSION_USER_ID)
.await
.map_err(cot::Error::internal)?
else {
return Ok(None);
};
Ok(User::get_by_id(db, user_id).await?)
}
/// Return a session user only when access to the instance has been granted.
pub async fn get_session_user(session: &Session, db: &Database) -> Option<AuthenticatedUser> {
let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??;
let user = User::get_by_id(db, user_id).await.ok()??;
authenticated_user_from_user(user)
get_session_identity(session, db)
.await
.and_then(authenticated_user_from_user)
}
// ---------------------------------------------------------------------------
+25
View File
@@ -151,6 +151,9 @@ pub struct ConfigSources {
pub torrent_proxy_id: ConfigSource,
pub youtube_proxy_id: ConfigSource,
pub youtube_cookie_id: ConfigSource,
pub spotify_client_id: ConfigSource,
pub spotify_redirect_uri: ConfigSource,
pub library_import_sync_budget: ConfigSource,
}
impl Default for ConfigSources {
@@ -194,6 +197,9 @@ impl Default for ConfigSources {
torrent_proxy_id: ConfigSource::Default,
youtube_proxy_id: ConfigSource::Default,
youtube_cookie_id: ConfigSource::Default,
spotify_client_id: ConfigSource::Default,
spotify_redirect_uri: ConfigSource::Default,
library_import_sync_budget: ConfigSource::Default,
}
}
}
@@ -414,6 +420,16 @@ pub struct AppConfig {
pub youtube_proxy_id: String,
/// Saved cookie-file id used by yt-dlp; empty means no cookies.
pub youtube_cookie_id: String,
/// Client ID of the administrator's Spotify application. Empty disables
/// the optional Spotify Web API import; the data export always works.
/// Authorization uses PKCE, so no client secret is stored.
pub spotify_client_id: String,
/// Redirect URI registered in the Spotify application. Empty means
/// `<request origin>/api/imports/providers/spotify/callback`.
pub spotify_redirect_uri: String,
/// Bytes of the Device Sync music snapshot up to which a library import
/// publishes tracks; the rest waits as `deferred_sync_limit`.
pub library_import_sync_budget: u64,
}
impl Default for AppConfig {
@@ -460,6 +476,9 @@ impl Default for AppConfig {
torrent_proxy_id: String::new(),
youtube_proxy_id: String::new(),
youtube_cookie_id: String::new(),
spotify_client_id: String::new(),
spotify_redirect_uri: String::new(),
library_import_sync_budget: 2 * 1024 * 1024,
}
}
}
@@ -504,6 +523,9 @@ impl_env_overrides!(
torrent_proxy_id,
youtube_proxy_id,
youtube_cookie_id,
spotify_client_id,
spotify_redirect_uri,
library_import_sync_budget,
);
impl AppConfig {
@@ -649,6 +671,9 @@ impl AppConfig {
apply_db_field!(torrent_proxy_id);
apply_db_field!(youtube_proxy_id);
apply_db_field!(youtube_cookie_id);
apply_db_field!(spotify_client_id);
apply_db_field!(spotify_redirect_uri);
apply_db_field!(library_import_sync_budget);
}
pub fn parsed_download_proxies(&self) -> anyhow::Result<Vec<DownloadProxy>> {
+188 -21
View File
@@ -13,12 +13,18 @@ use sqlx::Row as _;
use tokio::io::AsyncReadExt;
use super::{Federation, now_iso};
#[cfg(test)]
mod catalog_tests;
mod local_catalog;
#[cfg(test)]
mod search_tests;
use local_catalog::LocalCatalog;
const MAX_CATALOG_BYTES: u64 = 4 * 1024 * 1024;
/// Time allowed for one peer's catalogue.
const CATALOG_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8);
/// Peers asked for one artist's catalogue by a bounded lookup.
pub const MAX_CATALOG_OWNERS: usize = 16;
#[derive(Debug, Clone, Serialize)]
pub struct TrackKeyDto {
@@ -176,32 +182,16 @@ impl Federation {
tokio::spawn(async move {
let result = async {
let service = federation.service().await?;
let normalized = music_dht::normalize_name(&name);
let outcome = service
.search_network(&name)
.await
.map_err(|err| anyhow::anyhow!("federated artist search failed: {err}"))?;
// Deep links carry normalized names. Peers may require their
// original spelling (for example "AC/DC") in catalog requests.
let mut owners = HashMap::new();
for item in &outcome.network_results {
if item.kind == ItemKind::Artist && item.normalized_name == normalized {
owners.insert(item.owner, item.name.clone());
} else if let Some(display) = item
.artist_names
.iter()
.chain(&item.featured_artist_names)
.find(|artist| music_dht::normalize_name(artist) == normalized)
{
owners.entry(item.owner).or_insert_with(|| display.clone());
}
}
for (owner, name) in owners {
for (owner, name) in catalog_owners(&outcome.network_results, &name) {
let service = std::sync::Arc::clone(&service);
let sender = sender.clone();
tokio::spawn(async move {
let result = tokio::time::timeout(
std::time::Duration::from_secs(8),
CATALOG_TIMEOUT,
fetch_artist_catalog(&service, owner, &name),
)
.await
@@ -221,6 +211,25 @@ impl Federation {
receiver
}
/// Catalogues of the peers offering `name`, with real limits: one task
/// searches the network, then asks at most [`MAX_CATALOG_OWNERS`] owners,
/// `max_parallel` at a time. Dropping the stream cancels the search and
/// every catalogue request. Fails at once when the node is not running.
/// [`Self::stream_artist_catalogs`] of the player is not limited this way.
pub async fn artist_catalogs_bounded(
&self,
name: &str,
max_parallel: usize,
) -> Result<CatalogStream> {
let service = self.service().await?;
Ok(CatalogStream::spawn(
std::sync::Arc::new(DhtCatalogPeers(service)),
name.to_owned(),
max_parallel,
CATALOG_TIMEOUT,
))
}
/// Performs one bounded DHT search and returns entity upserts. The HTTP
/// layer streams each upsert independently; catalog fan-out can append
/// events to the same contract without changing the browser model.
@@ -478,6 +487,159 @@ async fn build_search_events(
Ok(events)
}
/// Owners whose search results credit `name`, with the spelling they use.
/// Deep links carry normalized names. Peers may require their original
/// spelling (for example "AC/DC") in catalog requests.
fn catalog_owners(items: &[LibraryItem], name: &str) -> HashMap<music_dht::EndpointId, String> {
let normalized = music_dht::normalize_name(name);
let mut owners = HashMap::new();
for item in items {
if item.kind == ItemKind::Artist && item.normalized_name == normalized {
owners.insert(item.owner, item.name.clone());
} else if let Some(display) = item
.artist_names
.iter()
.chain(&item.featured_artist_names)
.find(|artist| music_dht::normalize_name(artist) == normalized)
{
owners.entry(item.owner).or_insert_with(|| display.clone());
}
}
owners
}
/// Why a bounded catalogue lookup yielded no catalogue.
#[derive(Debug)]
pub enum CatalogError {
/// The network search for owners failed; no peer was asked.
Search(anyhow::Error),
/// One owner's catalogue was lost: unreachable, refused, too large or late.
Catalog(anyhow::Error),
}
pub type CatalogResult =
std::result::Result<(String, music_dht::catalog::CatalogArtist), CatalogError>;
/// Where catalogues come from: the DHT node, or a fake in tests.
#[async_trait::async_trait]
pub trait CatalogPeers: Send + Sync + 'static {
type Owner: std::fmt::Display + Send + 'static;
/// Owners offering `name`, each with the spelling to ask for.
async fn owners(&self, name: &str) -> Result<Vec<(Self::Owner, String)>>;
async fn catalog(
&self,
owner: Self::Owner,
name: String,
) -> Result<music_dht::catalog::CatalogArtist>;
}
/// Catalogues of one bounded lookup as they arrive. Dropping the stream
/// aborts its task; the task owns the request [`tokio::task::JoinSet`], so
/// the search and all catalogue requests stop with it.
pub struct CatalogStream {
receiver: tokio::sync::mpsc::UnboundedReceiver<CatalogResult>,
task: tokio::task::AbortHandle,
}
impl CatalogStream {
/// Starts a lookup: at most [`MAX_CATALOG_OWNERS`] owners, `max_parallel`
/// requests at a time, each limited to `timeout`.
pub fn spawn<P: CatalogPeers>(
peers: std::sync::Arc<P>,
name: String,
max_parallel: usize,
timeout: std::time::Duration,
) -> Self {
let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
let task = tokio::spawn(async move {
let owners = match peers.owners(&name).await {
Ok(owners) => owners,
Err(err) => {
let _ = sender.send(Err(CatalogError::Search(err)));
return;
}
};
let mut owners = owners.into_iter().take(MAX_CATALOG_OWNERS);
let mut requests = tokio::task::JoinSet::new();
loop {
while requests.len() < max_parallel.max(1) {
let Some((owner, spelling)) = owners.next() else {
break;
};
let peers = std::sync::Arc::clone(&peers);
requests.spawn(async move {
let label = owner.to_string();
tokio::time::timeout(timeout, peers.catalog(owner, spelling))
.await
.map_err(|_| anyhow::anyhow!("catalog request timed out"))
.and_then(|result| result)
.map(|artist| (label, artist))
.map_err(CatalogError::Catalog)
});
}
let Some(joined) = requests.join_next().await else {
return;
};
let result = joined.unwrap_or_else(|err| {
Err(CatalogError::Catalog(anyhow::anyhow!(
"catalog request failed: {err}"
)))
});
if sender.send(result).is_err() {
return;
}
}
});
Self {
receiver,
task: task.abort_handle(),
}
}
/// The next catalogue or loss; `None` once every owner answered.
pub async fn next(&mut self) -> Option<CatalogResult> {
self.receiver.recv().await
}
}
impl Drop for CatalogStream {
fn drop(&mut self) {
self.task.abort();
}
}
/// The running DHT node as a catalogue source.
struct DhtCatalogPeers(std::sync::Arc<music_dht::MusicDhtService>);
#[async_trait::async_trait]
impl CatalogPeers for DhtCatalogPeers {
type Owner = music_dht::EndpointId;
async fn owners(&self, name: &str) -> Result<Vec<(Self::Owner, String)>> {
let outcome = self
.0
.search_network(name)
.await
.map_err(|err| anyhow::anyhow!("federated artist search failed: {err}"))?;
let mut owners: Vec<_> = catalog_owners(&outcome.network_results, name)
.into_iter()
.collect();
owners.sort_by_cached_key(|(owner, _)| owner.to_string());
owners.truncate(MAX_CATALOG_OWNERS);
Ok(owners)
}
async fn catalog(
&self,
owner: Self::Owner,
name: String,
) -> Result<music_dht::catalog::CatalogArtist> {
fetch_artist_catalog(&self.0, owner, &name).await
}
}
async fn fetch_artist_catalog(
service: &music_dht::MusicDhtService,
owner: music_dht::EndpointId,
@@ -495,10 +657,15 @@ async fn fetch_artist_catalog(
request.push(b'\n');
stream.send.write_all(&request).await?;
stream.send.finish()?;
read_catalog_response(stream.recv).await
}
/// Reads a catalogue response of at most [`MAX_CATALOG_BYTES`].
async fn read_catalog_response(
recv: impl tokio::io::AsyncRead + Unpin,
) -> Result<music_dht::catalog::CatalogArtist> {
let mut payload = Vec::new();
stream
.recv
.take(MAX_CATALOG_BYTES + 1)
recv.take(MAX_CATALOG_BYTES + 1)
.read_to_end(&mut payload)
.await?;
anyhow::ensure!(
+257
View File
@@ -0,0 +1,257 @@
//! Limits and cancellation of bounded artist catalogue lookups, on a fake
//! catalogue source.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use music_dht::catalog::{CatalogArtist, CatalogResponse};
use music_dht::{ItemId, SecretKey};
use super::*;
/// Counts a running request until it is dropped, finished or aborted.
struct Live(Arc<Counters>);
impl Live {
fn start(counters: &Arc<Counters>) -> Self {
let now = counters.live.fetch_add(1, Ordering::SeqCst) + 1;
counters.peak.fetch_max(now, Ordering::SeqCst);
counters.started.fetch_add(1, Ordering::SeqCst);
Self(Arc::clone(counters))
}
}
impl Drop for Live {
fn drop(&mut self) {
self.0.live.fetch_sub(1, Ordering::SeqCst);
}
}
#[derive(Default)]
struct Counters {
live: AtomicUsize,
peak: AtomicUsize,
started: AtomicUsize,
}
#[derive(Clone, Copy)]
enum Answer {
Catalog,
Fail,
Hang,
TooLarge,
}
struct FakePeers {
owners: usize,
search_hangs: bool,
answer: fn(usize) -> Answer,
delay: Duration,
counters: Arc<Counters>,
}
impl FakePeers {
fn new(owners: usize, answer: fn(usize) -> Answer) -> Self {
Self {
owners,
search_hangs: false,
answer,
delay: Duration::from_millis(20),
counters: Arc::default(),
}
}
}
#[async_trait::async_trait]
impl CatalogPeers for FakePeers {
type Owner = usize;
async fn owners(&self, name: &str) -> Result<Vec<(usize, String)>> {
let _live = Live::start(&self.counters);
if self.search_hangs {
std::future::pending::<()>().await;
}
Ok((0..self.owners)
.map(|owner| (owner, name.to_owned()))
.collect())
}
async fn catalog(&self, owner: usize, name: String) -> Result<CatalogArtist> {
let _live = Live::start(&self.counters);
tokio::time::sleep(self.delay).await;
match (self.answer)(owner) {
Answer::Catalog => Ok(CatalogArtist {
name,
..Default::default()
}),
Answer::Fail => anyhow::bail!("peer refused catalog"),
Answer::Hang => std::future::pending().await,
Answer::TooLarge => {
let response = serde_json::to_vec(&CatalogResponse {
ok: true,
artist: Some(CatalogArtist {
name: "x".repeat(MAX_CATALOG_BYTES as usize),
..Default::default()
}),
..Default::default()
})?;
read_catalog_response(response.as_slice()).await
}
}
}
}
async fn collect(mut stream: CatalogStream) -> (Vec<String>, Vec<String>) {
let (mut found, mut lost) = (Vec::new(), Vec::new());
while let Some(result) = stream.next().await {
match result {
Ok((owner, _)) => found.push(owner),
Err(CatalogError::Catalog(err)) => lost.push(err.to_string()),
Err(CatalogError::Search(err)) => lost.push(format!("search: {err}")),
}
}
found.sort();
(found, lost)
}
async fn settle(counters: &Counters) {
for _ in 0..50 {
if counters.live.load(Ordering::SeqCst) == 0 {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
#[tokio::test]
async fn bounded_lookup_limits_owners_and_parallel_requests() {
let peers = Arc::new(FakePeers::new(20, |_| Answer::Catalog));
let counters = Arc::clone(&peers.counters);
let stream = CatalogStream::spawn(peers, "Artist".into(), 4, Duration::from_secs(5));
let (found, lost) = collect(stream).await;
assert_eq!(found.len(), MAX_CATALOG_OWNERS);
assert!(lost.is_empty());
// The search plus at most four catalogue requests run at once.
assert!(counters.peak.load(Ordering::SeqCst) <= 4);
assert_eq!(
counters.started.load(Ordering::SeqCst),
1 + MAX_CATALOG_OWNERS
);
}
#[tokio::test]
async fn bounded_lookup_reports_timeouts_errors_and_oversized_catalogues() {
let peers = Arc::new(FakePeers::new(4, |owner| match owner {
0 => Answer::Catalog,
1 => Answer::Fail,
2 => Answer::Hang,
_ => Answer::TooLarge,
}));
let counters = Arc::clone(&peers.counters);
let stream = CatalogStream::spawn(peers, "Artist".into(), 4, Duration::from_millis(200));
let (found, mut lost) = collect(stream).await;
lost.sort();
assert_eq!(found, ["0"]);
assert_eq!(
lost,
[
"catalog request timed out",
"catalog response is too large",
"peer refused catalog",
]
);
settle(&counters).await;
assert_eq!(counters.live.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn bounded_lookup_reports_a_failed_search() {
struct Offline;
#[async_trait::async_trait]
impl CatalogPeers for Offline {
type Owner = usize;
async fn owners(&self, _name: &str) -> Result<Vec<(usize, String)>> {
anyhow::bail!("no peers")
}
async fn catalog(&self, _owner: usize, _name: String) -> Result<CatalogArtist> {
unreachable!("no owners were found")
}
}
let stream = CatalogStream::spawn(
Arc::new(Offline),
"Artist".into(),
4,
Duration::from_secs(1),
);
let (found, lost) = collect(stream).await;
assert!(found.is_empty());
assert_eq!(lost, ["search: no peers"]);
}
#[tokio::test]
async fn dropping_the_stream_stops_the_search_and_every_request() {
let mut searching = FakePeers::new(1, |_| Answer::Catalog);
searching.search_hangs = true;
let searching = Arc::new(searching);
let counters = Arc::clone(&searching.counters);
let stream = CatalogStream::spawn(searching, "Artist".into(), 4, Duration::from_secs(60));
tokio::time::sleep(Duration::from_millis(50)).await;
assert_eq!(counters.live.load(Ordering::SeqCst), 1);
drop(stream);
settle(&counters).await;
assert_eq!(counters.live.load(Ordering::SeqCst), 0);
let fetching = Arc::new(FakePeers::new(10, |_| Answer::Hang));
let counters = Arc::clone(&fetching.counters);
let mut stream = CatalogStream::spawn(fetching, "Artist".into(), 4, Duration::from_secs(60));
let pending = tokio::time::timeout(Duration::from_millis(100), stream.next()).await;
assert!(pending.is_err(), "hanging peers answer nothing");
assert_eq!(counters.live.load(Ordering::SeqCst), 4);
drop(stream);
settle(&counters).await;
assert_eq!(counters.live.load(Ordering::SeqCst), 0);
// No request was started after the drop.
assert_eq!(counters.started.load(Ordering::SeqCst), 1 + 4);
}
fn item(kind: ItemKind, name: &str, artists: &[&str], owner_seed: u8) -> LibraryItem {
let owner = SecretKey::from_bytes(&[owner_seed; 32]).public();
LibraryItem {
id: ItemId::derive(&owner, kind, name),
owner,
kind,
name: name.into(),
normalized_name: music_dht::normalize_name(name),
artist_names: artists.iter().map(|artist| (*artist).to_owned()).collect(),
featured_artist_names: Vec::new(),
release_title: None,
release_type: None,
year: None,
content_id: None,
track_number: None,
disc_number: None,
duration_seconds: None,
revision: 1,
deleted: false,
updated_at_ms: 1,
}
}
#[test]
fn catalog_owners_keep_the_spelling_each_peer_uses() {
let items = [
item(ItemKind::Artist, "AC/DC", &[], 1),
item(ItemKind::Track, "Thunderstruck", &["AC/DC"], 2),
item(ItemKind::Track, "Thunderstruck", &["AC-DC"], 3),
item(ItemKind::Track, "Other", &["Somebody"], 4),
];
let owners = catalog_owners(&items, "ac dc");
let mut spellings: Vec<&str> = owners.values().map(String::as_str).collect();
spellings.sort();
assert_eq!(spellings, ["AC-DC", "AC/DC", "AC/DC"]);
}
+441 -100
View File
@@ -5,6 +5,8 @@
//! protocol as the TUI clients on `furumi/sync/1` and maps operations into
//! user-scoped Postgres state.
pub(crate) mod likes;
use music_dht::playback::{Announcement, Checkpoint, Config as PlaybackConfig, Engine};
use std::collections::BTreeMap;
use std::str::FromStr;
@@ -539,41 +541,87 @@ pub async fn record_track_like(
} else {
None
};
record_local_op(
pool,
let identity = ensure_identity(pool, user_id, "").await?;
let mut tx = pool.begin().await?;
likes::lock(&mut tx, user_id).await?;
let aliases = likes::Aliases::load(&mut tx, &content_id).await?;
// Another click may have committed between the web mutation and sync.
if aliases.existing(&mut tx, user_id).await?.is_some() != liked {
return Ok(());
}
let payload = SyncOpPayload::TrackLikeSet {
content_id: content_id.clone(),
liked,
fed: fed.clone(),
};
let op = append_local_op(&mut tx, user_id, identity.device_id, payload).await?;
store_like_state(
&mut tx,
&aliases,
user_id,
SyncOpPayload::TrackLikeSet {
content_id,
liked,
fed,
},
&content_id,
liked,
fed.as_ref(),
op.hlc_ms,
&op.op_id,
)
.await?;
tx.commit().await?;
}
Ok(())
}
// Older web clients could include idle time in a single-track report. Their
// HTTP fallback ID survives device sync. Modern events measure actual playback,
// which can exceed the track length when a listener replays a passage.
fn web_listened_ms(id: Option<&str>, reported_ms: i64, track_duration_ms: Option<i64>) -> i64 {
let Some(duration) = track_duration_ms.filter(|&ms| ms > 0 && ms < reported_ms) else {
return reported_ms;
};
if let Some(id) = id {
let Some(suffix) = id.strip_prefix("legacy-web:") else {
return reported_ms;
};
let mut fields = suffix.split(':');
let numeric = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
if fields.clone().count() != 3 || !fields.all(numeric) {
return reported_ms;
}
}
duration
}
pub async fn record_track_listen(
pool: &sqlx::PgPool,
user_id: i64,
track_id: i64,
listen_id: String,
started_at_ms: i64,
listened_ms: i64,
listen_id: Option<String>,
started_at_seconds: Option<i64>,
listened_seconds: i32,
ended_reason: ListenEndReason,
) -> Result<()> {
) -> Result<i32> {
let content_id = track_content_id(pool, track_id)
.await?
.context("track content id is not ready")?;
let track = synced_fed_track_for_track(pool, track_id, &content_id)
.await?
.context("track metadata is not available")?;
let track_duration_ms = track.duration_seconds.map(|s| s.saturating_mul(1_000));
let listened_ms = web_listened_ms(
listen_id.as_deref(),
i64::from(listened_seconds.max(0)) * 1_000,
track_duration_ms,
);
let started_at =
started_at_seconds.unwrap_or_else(|| chrono::Utc::now().timestamp() - listened_ms / 1_000);
let listen_id =
listen_id.unwrap_or_else(|| format!("legacy-web:{user_id}:{track_id}:{started_at}"));
let event = ListenEvent {
listen_id,
content_id,
started_at_ms,
started_at_ms: started_at.saturating_mul(1_000),
listened_ms,
track_duration_ms: track.duration_seconds.map(|seconds| seconds * 1_000),
track_duration_ms,
ended_reason,
track: ListenTrackMetadata {
title: track.title,
@@ -585,7 +633,7 @@ pub async fn record_track_listen(
if event.should_record() {
record_local_op(pool, user_id, SyncOpPayload::ListenRecorded { event }).await?;
}
Ok(())
Ok((listened_ms / 1_000) as i32)
}
/// Records a like for a content-addressed track that need not be local yet.
@@ -650,39 +698,14 @@ pub async fn record_content_playlist_add(
.await
}
/// Reconciles content-addressed user state after a track becomes local.
/// History is intentionally not touched: only actual web playback writes it.
pub async fn materialize_content_state(
/// Adds saved playlist items to the local catalog after the audio import commits.
pub(super) async fn materialize_playlist_items(
pool: &sqlx::PgPool,
content_id: &str,
track_id: i64,
) -> Result<()> {
let content_id =
music_dht::normalize_content_id(content_id).context("invalid track content id")?;
let likes = sqlx::query(
"SELECT user_id, liked, hlc_ms
FROM furumusic__fed_state_like WHERE content_id = $1",
)
.bind(&content_id)
.fetch_all(pool)
.await?;
for row in likes {
let user_id: i64 = row.get("user_id");
let liked: bool = row.get("liked");
if liked {
sqlx::query(
"INSERT INTO furumusic__user_liked_track
(user_id, track_id, created_at)
VALUES ($1, $2, $3)
ON CONFLICT (user_id, track_id) DO NOTHING",
)
.bind(user_id)
.bind(track_id)
.bind(iso_from_ms(row.get("hlc_ms")))
.execute(pool)
.await?;
}
}
let playlist_items = sqlx::query(
"SELECT i.user_id, i.playlist_id, i.position
FROM furumusic__fed_state_playlist_item i
@@ -712,14 +735,6 @@ pub async fn materialize_content_state(
.execute(pool)
.await?;
}
sqlx::query(
"UPDATE furumusic__fed_state_like
SET local_track_id = $2 WHERE content_id = $1",
)
.bind(&content_id)
.bind(track_id)
.execute(pool)
.await?;
sqlx::query(
"UPDATE furumusic__fed_state_playlist_item
SET local_track_id = $2 WHERE content_id = $1",
@@ -1793,6 +1808,19 @@ async fn record_local_op(
);
}
let mut tx = pool.begin().await?;
let op = append_local_op(&mut tx, user_id, identity.device_id, payload).await?;
tx.commit().await?;
let _ = apply_op(pool, Arc::new(PlayerDeviceHub::default()), user_id, &op).await?;
Ok(())
}
async fn append_local_op(
conn: &mut sqlx::PgConnection,
user_id: i64,
device_id: String,
payload: SyncOpPayload,
) -> Result<SyncOpWire> {
let now = now_ms();
let row = sqlx::query(
"UPDATE furumusic__fed_device_identity
@@ -1803,14 +1831,14 @@ async fn record_local_op(
)
.bind(user_id)
.bind(now)
.fetch_one(pool)
.fetch_one(&mut *conn)
.await?;
let seq: i64 = row.get("local_seq");
let hlc_ms: i64 = row.get("last_hlc_ms");
let op_id = format!("{}:{seq}", identity.device_id);
let op_id = format!("{device_id}:{seq}");
let op = SyncOpWire {
op_id,
origin_device_id: identity.device_id,
origin_device_id: device_id,
seq,
hlc_ms,
payload,
@@ -1831,7 +1859,7 @@ async fn record_local_op(
.bind(op.hlc_ms)
.bind(now_ms())
.bind(op.payload.is_tombstone())
.execute(pool)
.execute(&mut *conn)
.await?;
sqlx::query(
"INSERT INTO furumusic__fed_sync_vector (user_id, device_id, max_seq)
@@ -1842,10 +1870,9 @@ async fn record_local_op(
.bind(user_id)
.bind(&op.origin_device_id)
.bind(op.seq)
.execute(pool)
.execute(conn)
.await?;
let _ = apply_op(pool, Arc::new(PlayerDeviceHub::default()), user_id, &op).await?;
Ok(())
Ok(op)
}
pub(crate) async fn record_podcast_op(
@@ -1876,6 +1903,208 @@ pub(crate) async fn record_podcast_op(
Ok(())
}
/// Device id of the user's web fed-device, created on first use. Callers
/// that record operations inside their own transaction read it beforehand.
pub(crate) async fn local_device_id(pool: &sqlx::PgPool, user_id: i64) -> Result<String> {
Ok(ensure_identity(pool, user_id, "").await?.device_id)
}
/// Sync id of a playlist created by [`record_playlist_created_in_tx`].
pub(crate) fn local_playlist_sync_id_for(user_id: i64, playlist_id: i64) -> String {
format!("webpl_{user_id}_{playlist_id}")
}
/// `PlaylistCreated` for a playlist inserted in the caller's transaction,
/// with the playlist register written in the same transaction; the same state
/// that `record_playlist_created` reaches after its own commit. Returns the
/// sync id.
pub(crate) async fn record_playlist_created_in_tx(
conn: &mut sqlx::PgConnection,
user_id: i64,
device_id: &str,
playlist_id: i64,
title: &str,
) -> Result<String> {
let sync_id = local_playlist_sync_id_for(user_id, playlist_id);
let op = append_local_op(
&mut *conn,
user_id,
device_id.to_string(),
SyncOpPayload::PlaylistCreated {
playlist_id: sync_id.clone(),
title: title.to_string(),
},
)
.await?;
sqlx::query(
"INSERT INTO furumusic__fed_state_playlist
(user_id, playlist_id, local_playlist_id, title, deleted, hlc_ms, op_id)
VALUES ($1, $2, $3, $4, false, $5, $6)
ON CONFLICT (user_id, playlist_id) DO UPDATE SET
local_playlist_id = EXCLUDED.local_playlist_id,
title = EXCLUDED.title,
deleted = false,
hlc_ms = EXCLUDED.hlc_ms,
op_id = EXCLUDED.op_id",
)
.bind(user_id)
.bind(&sync_id)
.bind(playlist_id)
.bind(title)
.bind(op.hlc_ms)
.bind(&op.op_id)
.execute(&mut *conn)
.await?;
Ok(sync_id)
}
/// `PlaylistTrackAdded` in the caller's transaction, with the item register.
/// The register is only inserted, never overwritten: when a row for this
/// `content_id` exists (a concurrent operation was applied meanwhile) the
/// result is `None` and the caller must roll back, which also drops the
/// operation. Otherwise returns the operation id.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn record_playlist_track_added_in_tx(
conn: &mut sqlx::PgConnection,
user_id: i64,
device_id: &str,
sync_id: &str,
content_id: &str,
position: i64,
fed: &SyncedFedTrack,
local_track_id: Option<i64>,
) -> Result<Option<String>> {
let content_id =
music_dht::normalize_content_id(content_id).context("invalid track content id")?;
let op = append_local_op(
&mut *conn,
user_id,
device_id.to_string(),
SyncOpPayload::PlaylistTrackAdded {
playlist_id: sync_id.to_string(),
content_id: content_id.clone(),
position,
fed: Some(fed.clone()),
},
)
.await?;
let inserted = sqlx::query(
"INSERT INTO furumusic__fed_state_playlist_item
(user_id, playlist_id, content_id, present, position, hlc_ms, op_id,
local_track_id, fed_json)
VALUES ($1, $2, $3, true, $4, $5, $6, $7, $8)
ON CONFLICT (user_id, playlist_id, content_id) DO NOTHING",
)
.bind(user_id)
.bind(sync_id)
.bind(&content_id)
.bind(position)
.bind(op.hlc_ms)
.bind(&op.op_id)
.bind(local_track_id)
.bind(serde_json::to_value(fed)?)
.execute(&mut *conn)
.await?
.rows_affected();
Ok((inserted == 1).then_some(op.op_id))
}
/// Size of the Device Sync line the web player would send now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct OutgoingSyncSize {
/// Longest `Hello` line over the trusted devices, newline included.
pub full_line: u64,
/// Serialized snapshot without its podcast sections.
pub music_snapshot: u64,
}
/// Measures the outgoing Device Sync line by serializing the same parts that
/// `sync_device` sends, with the same `serde_json::to_vec` as `write_msg`:
/// for every trusted device its snapshot, pending operations and playback,
/// plus the device profiles and the vector. Without devices a virtual peer of
/// the current protocol version stands in. Nothing is written except the
/// periodic local seed that every snapshot runs; playback coordination,
/// which has side effects and stays small, is left out.
pub(crate) async fn outgoing_sync_line_size(
pool: &sqlx::PgPool,
user_id: i64,
) -> Result<OutgoingSyncSize> {
let identity = ensure_identity(pool, user_id, "").await?;
let snapshot = snapshot(pool, user_id).await?;
let mut music = snapshot.clone();
music.strip_podcast_state();
let music_snapshot = serde_json::to_vec(&music)?.len() as u64;
let devices = device_profiles(pool, user_id).await?;
let profile = devices
.iter()
.find(|device| device.device_id == identity.device_id)
.cloned()
.map(|mut profile| {
profile.client_version = CLIENT_VERSION.to_string();
profile.protocol_version = PROTOCOL_VERSION;
profile
})
.unwrap_or_else(|| DeviceProfileWire {
device_id: identity.device_id.clone(),
name: identity.name.clone(),
client_version: CLIENT_VERSION.to_string(),
protocol_version: PROTOCOL_VERSION,
endpoint_id: String::new(),
endpoint_ticket: String::new(),
revoked: false,
revoke_cutoff_seq: None,
updated_at_ms: now_ms(),
});
let vector = vector(pool, user_id).await?;
let state = PlayerDeviceHub::shared()
.playback_state_json_for_commands(user_id)
.unwrap_or_else(|| serde_json::json!({}));
let playback = PlaybackSnapshot {
device_id: identity.device_id.clone(),
device_name: identity.name.clone(),
active: false,
updated_at_ms: now_ms(),
state: playback_state_from_browser_json(pool, state).await?,
coordination: None,
};
let mut peers = Vec::new();
for device in active_remote_devices(pool, user_id).await? {
let version = peer_protocol_version(pool, user_id, &device.device_id).await?;
peers.push((device.device_id, version));
}
if peers.is_empty() {
peers.push((String::new(), PROTOCOL_VERSION));
}
let mut full_line = 0;
for (device_id, version) in peers {
let message = WireMessage::Hello {
group_id: identity.group_id.clone(),
profile: profile.clone(),
devices: devices.clone(),
vector: vector.clone(),
ops: ops_for_peer_version(pool, user_id, &device_id, version).await?,
snapshot: snapshot.for_peer(version),
playback: music_dht::device_sync::playback_allowed_for_peer(&playback.state, version)
.then(|| playback.clone()),
};
full_line = full_line.max(serde_json::to_vec(&message)?.len() as u64 + 1);
}
Ok(OutgoingSyncSize {
full_line,
music_snapshot,
})
}
/// Applies operations received from a paired device, as an exchange does.
#[cfg(test)]
pub(crate) async fn apply_received_ops(
pool: &sqlx::PgPool,
user_id: i64,
ops: Vec<SyncOpWire>,
) -> Result<()> {
apply_ops(pool, Arc::new(PlayerDeviceHub::default()), user_id, ops).await
}
async fn apply_ops(
pool: &sqlx::PgPool,
hub: Arc<PlayerDeviceHub>,
@@ -2098,6 +2327,11 @@ async fn apply_listen_event(
.fetch_optional(pool)
.await?
.flatten();
let listened_ms = web_listened_ms(
Some(&event.listen_id),
event.listened_ms,
event.track_duration_ms,
);
let inserted = sqlx::query(
"INSERT INTO furumusic__listen_event
(user_id, listen_id, content_id, local_track_id, origin_device_id,
@@ -2112,7 +2346,7 @@ async fn apply_listen_event(
.bind(local_track_id)
.bind(origin_device_id)
.bind(event.started_at_ms)
.bind(event.listened_ms)
.bind(listened_ms)
.bind(event.track_duration_ms)
.bind(serde_json::to_string(&event.ended_reason)?)
.bind(event.qualifies_as_play())
@@ -2142,10 +2376,7 @@ async fn apply_listen_event(
if duration_seconds <= 30 {
return Ok(true);
}
let listened_seconds = event
.listened_ms
.div_euclid(1_000)
.clamp(0, i64::from(i32::MAX)) as i32;
let listened_seconds = listened_ms.div_euclid(1_000).clamp(0, i64::from(i32::MAX)) as i32;
let started_at = event.started_at_ms.div_euclid(1_000);
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
sqlx::query(
@@ -2186,14 +2417,42 @@ async fn apply_like_state(
let Some(content_id) = music_dht::normalize_content_id(content_id) else {
return Ok(false);
};
let mut tx = pool.begin().await?;
likes::lock(&mut tx, user_id).await?;
let aliases = likes::Aliases::load(&mut tx, &content_id).await?;
let applied = store_like_state(
&mut tx,
&aliases,
user_id,
&content_id,
liked,
fed,
hlc_ms,
op_id,
)
.await?;
tx.commit().await?;
Ok(applied)
}
async fn store_like_state(
conn: &mut sqlx::PgConnection,
aliases: &likes::Aliases,
user_id: i64,
content_id: &str,
liked: bool,
fed: Option<&SyncedFedTrack>,
hlc_ms: i64,
op_id: &str,
) -> Result<bool> {
let current = sqlx::query(
"SELECT liked, hlc_ms, op_id
FROM furumusic__fed_state_like
WHERE user_id = $1 AND content_id = $2",
)
.bind(user_id)
.bind(&content_id)
.fetch_optional(pool)
.bind(content_id)
.fetch_optional(&mut *conn)
.await?;
let apply = current.as_ref().is_none_or(|row| {
let current_hlc: i64 = row.get("hlc_ms");
@@ -2203,8 +2462,9 @@ async fn apply_like_state(
if !apply {
return Ok(false);
}
let local_track_id = track_id_by_content_id(pool, &content_id).await?;
let metadata = fed.cloned();
let local_track_id = aliases
.project(conn, user_id, liked, None, &iso_from_ms(hlc_ms))
.await?;
sqlx::query(
"INSERT INTO furumusic__fed_state_like
(user_id, content_id, liked, hlc_ms, op_id, local_track_id, fed_json)
@@ -2217,37 +2477,14 @@ async fn apply_like_state(
fed_json = COALESCE(EXCLUDED.fed_json, furumusic__fed_state_like.fed_json)",
)
.bind(user_id)
.bind(&content_id)
.bind(content_id)
.bind(liked)
.bind(hlc_ms)
.bind(op_id)
.bind(local_track_id)
.bind(metadata.map(serde_json::to_value).transpose()?)
.execute(pool)
.bind(fed.map(serde_json::to_value).transpose()?)
.execute(conn)
.await?;
if let Some(track_id) = local_track_id {
if liked {
let created_at = iso_from_ms(hlc_ms);
sqlx::query(
"INSERT INTO furumusic__user_liked_track (user_id, track_id, created_at)
VALUES ($1, $2, $3)
ON CONFLICT (user_id, track_id) DO NOTHING",
)
.bind(user_id)
.bind(track_id)
.bind(created_at)
.execute(pool)
.await?;
} else {
sqlx::query(
"DELETE FROM furumusic__user_liked_track WHERE user_id = $1 AND track_id = $2",
)
.bind(user_id)
.bind(track_id)
.execute(pool)
.await?;
}
}
Ok(true)
}
@@ -2325,6 +2562,25 @@ async fn apply_playlist_state(
Ok(true)
}
/// Attempts of [`apply_playlist_item_state`] when PostgreSQL aborts it to
/// break a deadlock or a serialization conflict.
const ITEM_STATE_ATTEMPTS: usize = 3;
/// A deadlock or serialization failure: the transaction can simply run again.
fn is_transient_conflict(error: &anyhow::Error) -> bool {
error
.chain()
.any(|cause| match cause.downcast_ref::<sqlx::Error>() {
Some(sqlx::Error::Database(db)) => {
matches!(db.code().as_deref(), Some("40P01" | "40001"))
}
_ => false,
})
}
/// Its transaction locks the register before the playlist row, while library
/// cleanup and metadata fixes lock the playlist row first, so PostgreSQL may
/// abort one of them; the item is then applied again from its register.
#[allow(clippy::too_many_arguments)]
async fn apply_playlist_item_state(
pool: &sqlx::PgPool,
@@ -2336,6 +2592,41 @@ async fn apply_playlist_item_state(
fed: Option<&SyncedFedTrack>,
hlc_ms: i64,
op_id: &str,
) -> Result<bool> {
let mut attempt = 1;
loop {
match apply_playlist_item_state_once(
pool,
user_id,
playlist_id,
content_id,
present,
position,
fed,
hlc_ms,
op_id,
)
.await
{
Err(error) if attempt < ITEM_STATE_ATTEMPTS && is_transient_conflict(&error) => {
attempt += 1;
}
result => return result,
}
}
}
#[allow(clippy::too_many_arguments)]
async fn apply_playlist_item_state_once(
pool: &sqlx::PgPool,
user_id: i64,
playlist_id: &str,
content_id: &str,
present: bool,
position: i64,
fed: Option<&SyncedFedTrack>,
hlc_ms: i64,
op_id: &str,
) -> Result<bool> {
let Some(content_id) = music_dht::normalize_content_id(content_id) else {
return Ok(false);
@@ -2365,7 +2656,13 @@ async fn apply_playlist_item_state(
local_playlist_id_by_sync_id(pool, user_id, playlist_id).await?
};
let fed_json = fed.cloned().map(serde_json::to_value).transpose()?;
sqlx::query(
// The register and the materialized row change in one transaction. The
// conditional upsert keeps last-writer-wins atomic: it locks the register
// row, so a concurrent write of the same item (another operation or the
// library import publisher) waits and is then compared with this one.
// `playlist_track` follows in the same order as the register.
let mut tx = pool.begin().await?;
let changed = sqlx::query(
"INSERT INTO furumusic__fed_state_playlist_item
(user_id, playlist_id, content_id, present, position, hlc_ms, op_id,
local_track_id, fed_json)
@@ -2376,7 +2673,10 @@ async fn apply_playlist_item_state(
hlc_ms = EXCLUDED.hlc_ms,
op_id = EXCLUDED.op_id,
local_track_id = EXCLUDED.local_track_id,
fed_json = COALESCE(EXCLUDED.fed_json, furumusic__fed_state_playlist_item.fed_json)",
fed_json = COALESCE(EXCLUDED.fed_json, furumusic__fed_state_playlist_item.fed_json)
WHERE (furumusic__fed_state_playlist_item.hlc_ms,
furumusic__fed_state_playlist_item.op_id COLLATE \"C\")
< (EXCLUDED.hlc_ms, EXCLUDED.op_id COLLATE \"C\")",
)
.bind(user_id)
.bind(playlist_id)
@@ -2387,8 +2687,13 @@ async fn apply_playlist_item_state(
.bind(op_id)
.bind(local_track_id)
.bind(fed_json)
.execute(pool)
.await?;
.execute(&mut *tx)
.await?
.rows_affected();
if changed == 0 {
tx.rollback().await?;
return Ok(false);
}
if let (Some(local_playlist_id), Some(track_id)) = (local_playlist_id, local_track_id) {
if present {
let exists: Option<i64> = sqlx::query_scalar(
@@ -2398,7 +2703,7 @@ async fn apply_playlist_item_state(
)
.bind(local_playlist_id)
.bind(track_id)
.fetch_optional(pool)
.fetch_optional(&mut *tx)
.await?;
if exists.is_none() {
sqlx::query(
@@ -2411,7 +2716,7 @@ async fn apply_playlist_item_state(
.bind(position as i32)
.bind(iso_from_ms(hlc_ms))
.bind(user_id)
.execute(pool)
.execute(&mut *tx)
.await?;
} else {
sqlx::query(
@@ -2422,7 +2727,7 @@ async fn apply_playlist_item_state(
.bind(local_playlist_id)
.bind(track_id)
.bind(position as i32)
.execute(pool)
.execute(&mut *tx)
.await?;
}
} else {
@@ -2432,10 +2737,11 @@ async fn apply_playlist_item_state(
)
.bind(local_playlist_id)
.bind(track_id)
.execute(pool)
.execute(&mut *tx)
.await?;
}
}
tx.commit().await?;
Ok(true)
}
@@ -3976,7 +4282,7 @@ async fn track_content_id(pool: &sqlx::PgPool, track_id: i64) -> Result<Option<S
Ok(value.and_then(|value| music_dht::normalize_content_id(&value)))
}
async fn synced_fed_track_for_track(
pub(crate) async fn synced_fed_track_for_track(
pool: &sqlx::PgPool,
track_id: i64,
content_id: &str,
@@ -4378,6 +4684,15 @@ async fn ops_for_peer(
peer_device_id: &str,
) -> Result<Vec<SyncOpWire>> {
let peer_version = peer_protocol_version(pool, user_id, peer_device_id).await?;
ops_for_peer_version(pool, user_id, peer_device_id, peer_version).await
}
async fn ops_for_peer_version(
pool: &sqlx::PgPool,
user_id: i64,
peer_device_id: &str,
peer_version: u16,
) -> Result<Vec<SyncOpWire>> {
let rows = sqlx::query(
"SELECT o.op_id, o.origin_device_id, o.seq, o.hlc_ms, o.payload_json
FROM furumusic__fed_sync_ops o
@@ -4822,6 +5137,8 @@ fn payload_kind(payload: &SyncOpPayload) -> &'static str {
async fn write_msg(stream: &mut ByteStream, message: &WireMessage) -> Result<()> {
let mut payload = serde_json::to_vec(message)?;
payload.push(b'\n');
// Compared with `outgoing_sync_line_size`, which measures the same line.
tracing::debug!(bytes = payload.len(), "device sync line written");
stream.send.write_all(&payload).await?;
Ok(())
}
@@ -5010,3 +5327,27 @@ fn base64url_decode(value: &str) -> Result<Vec<u8>> {
#[cfg(test)]
mod interop_tests;
#[cfg(test)]
mod tests {
use super::web_listened_ms;
#[test]
fn only_legacy_http_listens_are_bounded_by_known_track_length() {
let reported = 40_461_000;
let duration = Some(267_000);
for id in [None, Some("legacy-web:3:17:1795213775")] {
assert_eq!(web_listened_ms(id, reported, duration), 267_000);
assert_eq!(web_listened_ms(id, 60_000, duration), 60_000);
assert_eq!(web_listened_ms(id, reported, None), reported);
}
for id in [
"modern-session",
"legacy-web:17",
"legacy-web:3::17",
"legacy-web:3:2:1:0",
] {
assert_eq!(web_listened_ms(Some(id), reported, duration), reported);
}
}
}
+261
View File
@@ -0,0 +1,261 @@
use sqlx::{PgConnection, PgPool};
pub(crate) async fn lock(conn: &mut PgConnection, user: i64) -> sqlx::Result<()> {
sqlx::query(
"SELECT pg_advisory_xact_lock(hashtextextended('furumusic-like:' || $1::bigint::text,0))",
)
.bind(user)
.execute(conn)
.await?;
Ok(())
}
pub(super) struct Aliases {
ids: Vec<i64>,
visible: Vec<i64>,
}
impl Aliases {
pub(super) async fn load(conn: &mut PgConnection, content: &str) -> sqlx::Result<Self> {
let rows: Vec<(i64,bool)> = sqlx::query_as(
"SELECT track_id, hidden FROM furumusic__track_content_alias WHERE content_id=$1 ORDER BY track_id"
).bind(content).fetch_all(conn).await?;
Ok(Self {
ids: rows.iter().map(|r| r.0).collect(),
visible: rows.into_iter().filter(|r| !r.1).map(|r| r.0).collect(),
})
}
pub(super) async fn existing(
&self,
conn: &mut PgConnection,
user: i64,
) -> sqlx::Result<Option<i64>> {
sqlx::query_scalar(
"SELECT track_id FROM furumusic__user_liked_track WHERE user_id=$1 AND track_id=ANY($2)
ORDER BY (track_id=ANY($3)) DESC, id LIMIT 1",
)
.bind(user)
.bind(&self.ids)
.bind(&self.visible)
.fetch_optional(conn)
.await
}
// Only one local row represents a signed, content-addressed like. Preserve
// the existing visible edition, including the one the local listener chose.
pub(super) async fn project(
&self,
conn: &mut PgConnection,
user: i64,
liked: bool,
preferred: Option<i64>,
created_at: &str,
) -> sqlx::Result<Option<i64>> {
let existing = self.existing(conn, user).await?;
let chosen = existing
.filter(|id| self.visible.contains(id))
.or_else(|| preferred.filter(|id| self.visible.contains(id)))
.or_else(|| self.visible.first().copied());
sqlx::query(
"DELETE FROM furumusic__user_liked_track WHERE user_id=$1 AND track_id=ANY($2)
AND track_id IS DISTINCT FROM $3",
)
.bind(user)
.bind(&self.ids)
.bind(if liked { chosen } else { None })
.execute(&mut *conn)
.await?;
if let Some(id) = chosen.filter(|_| liked) {
sqlx::query(
"INSERT INTO furumusic__user_liked_track(user_id,track_id,created_at) VALUES($1,$2,$3)
ON CONFLICT(user_id,track_id) DO NOTHING"
).bind(user).bind(id).bind(created_at).execute(conn).await?;
}
Ok(chosen)
}
}
pub(crate) async fn toggle(
pool: &PgPool,
user: i64,
track: i64,
) -> sqlx::Result<Option<(bool, Option<String>, Vec<i64>)>> {
let mut tx = pool.begin().await?;
lock(&mut tx, user).await?;
let row: Option<(Option<String>,)> = sqlx::query_as(
"SELECT a.content_id FROM furumusic__track t LEFT JOIN furumusic__track_content_alias a ON a.track_id=t.id
WHERE t.id=$1"
).bind(track).fetch_optional(&mut *tx).await?;
let Some((content,)) = row else {
return Ok(None);
};
let aliases = match &content {
Some(content) => Aliases::load(&mut tx, content).await?,
None => Aliases {
ids: vec![track],
visible: vec![track],
},
};
let pending: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM furumusic__fed_state_like
WHERE user_id=$1 AND content_id=$2 AND liked AND local_track_id IS NULL)",
)
.bind(user)
.bind(content.as_deref())
.fetch_one(&mut *tx)
.await?;
let liked = !pending && aliases.existing(&mut tx, user).await?.is_none();
if liked && aliases.visible.is_empty() {
return Ok(None);
}
aliases
.project(&mut tx, user, liked, Some(track), &super::now_iso())
.await?;
tx.commit().await?;
Ok(Some((liked, content, aliases.ids)))
}
pub(crate) async fn on_content_available(
conn: &mut PgConnection,
content: &str,
preferred: Option<i64>,
) -> sqlx::Result<()> {
let users = sqlx::query_scalar::<_, i64>(
"SELECT user_id FROM furumusic__fed_state_like WHERE content_id=$1
UNION
SELECT l.user_id FROM furumusic__track_content_alias a
JOIN furumusic__user_liked_track l ON l.track_id=a.track_id
WHERE a.content_id=$1 ORDER BY user_id",
)
.bind(content)
.fetch_all(&mut *conn)
.await?;
if users.is_empty() {
return Ok(());
}
for user in users {
lock(conn, user).await?;
let aliases = Aliases::load(conn, content).await?;
let state: Option<(bool, i64)> = sqlx::query_as(
"SELECT liked, hlc_ms FROM furumusic__fed_state_like WHERE user_id=$1 AND content_id=$2"
).bind(user).bind(content).fetch_optional(&mut *conn).await?;
if let Some((liked, ms)) = state {
let chosen = aliases
.project(conn, user, liked, preferred, &super::iso_from_ms(ms))
.await?;
sqlx::query("UPDATE furumusic__fed_state_like SET local_track_id=$3 WHERE user_id=$1 AND content_id=$2")
.bind(user).bind(content).bind(chosen).execute(&mut *conn).await?;
} else if aliases.existing(conn, user).await?.is_some() {
aliases
.project(conn, user, true, preferred, &super::now_iso())
.await?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::federation::devices::{apply_like_state, record_track_like};
async fn local_rows(pool: &PgPool) -> sqlx::Result<Vec<i64>> {
sqlx::query_scalar(
"SELECT track_id FROM furumusic__user_liked_track WHERE user_id=1 ORDER BY track_id",
)
.fetch_all(pool)
.await
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
async fn catalog_aliases_share_one_like_across_web_sync_and_import() -> anyhow::Result<()> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?)
.await?;
sqlx::raw_sql("
CREATE TEMP TABLE furumusic__track(id bigint PRIMARY KEY,title text DEFAULT 'Taking Off',
release_id bigint DEFAULT 1,audio_file_id bigint,is_hidden bool DEFAULT false,
track_number int,disc_number int,duration_seconds float8 DEFAULT 220);
CREATE TEMP TABLE furumusic__release(id bigint PRIMARY KEY,title text,year int,is_hidden bool DEFAULT false);
CREATE TEMP TABLE furumusic__media_file(id bigint PRIMARY KEY,sha256_hash text);
CREATE TEMP TABLE furumusic__federation_content_id_cache(media_file_id bigint PRIMARY KEY,sha256_hash text,content_id text,updated_at text);
CREATE TEMP TABLE furumusic__track_artist(track_id bigint,artist_id bigint,role text,position int);
CREATE TEMP TABLE furumusic__artist(id bigint,name text);
CREATE TEMP TABLE furumusic__user_liked_track(id bigserial PRIMARY KEY,user_id bigint,track_id bigint,created_at text,UNIQUE(user_id,track_id));
CREATE TEMP TABLE furumusic__fed_state_like(user_id bigint,content_id text,liked bool,hlc_ms bigint,op_id text,local_track_id bigint,fed_json jsonb,PRIMARY KEY(user_id,content_id));
CREATE TEMP TABLE furumusic__fed_device_identity(user_id bigint,device_id text,group_id text,device_name text,local_seeded_at_ms bigint,local_seq bigint,last_hlc_ms bigint);
CREATE TEMP TABLE furumusic__fed_sync_ops(user_id bigint,op_id text,origin_device_id text,seq bigint,kind text,payload_json jsonb,hlc_ms bigint,received_at_ms bigint,tombstone bool,UNIQUE(user_id,op_id));
CREATE TEMP TABLE furumusic__fed_sync_vector(user_id bigint,device_id text,max_seq bigint,UNIQUE(user_id,device_id));
INSERT INTO furumusic__fed_device_identity VALUES(1,'web','g','web',1,0,0);
INSERT INTO furumusic__release(id,title) VALUES(1,'Ambitions');
INSERT INTO furumusic__track(id,audio_file_id) VALUES(5672,1),(5686,2),(5797,3),(50,4);
INSERT INTO furumusic__media_file VALUES(1,'one'),(2,'two'),(3,'three'),(4,'new');
INSERT INTO furumusic__federation_content_id_cache(media_file_id,sha256_hash,content_id) VALUES
(1,'one','b3:'||repeat('a',64)),(2,'two','b3:'||repeat('a',64)),
(3,'three','b3:'||repeat('b',64)),(4,'stale','b3:'||repeat('a',64));
").execute(&pool).await?;
sqlx::raw_sql(&include_str!("track_content_alias.sql").replacen(
"CREATE VIEW",
"CREATE TEMP VIEW",
1,
))
.execute(&pool)
.await?;
let content = format!("b3:{}", "a".repeat(64));
let local = toggle(&pool, 1, 5686).await?.unwrap();
assert_eq!(local, (true, Some(content.clone()), vec![5672, 5686]));
record_track_like(&pool, 1, 5686, true).await?;
assert_eq!(local_rows(&pool).await?, [5686]);
assert!(toggle(&pool, 1, 5797).await?.unwrap().0);
record_track_like(&pool, 1, 5797, true).await?;
let uncached = toggle(&pool, 1, 50).await?.unwrap();
assert_eq!(uncached, (true, None, vec![50]));
let mut tx = pool.begin().await?;
on_content_available(&mut tx, &content, Some(5672)).await?;
tx.commit().await?;
assert_eq!(local_rows(&pool).await?, [50, 5686, 5797]);
assert!(!toggle(&pool, 1, 5672).await?.unwrap().0);
record_track_like(&pool, 1, 5672, false).await?;
record_track_like(&pool, 1, 5686, true).await?; // A delayed callback cannot restore it.
assert_eq!(local_rows(&pool).await?, [50, 5797]);
assert!(apply_like_state(&pool, 1, &content, true, None, i64::MAX - 1, "peer:1").await?);
assert!(!apply_like_state(&pool, 1, &content, false, None, 1, "old").await?);
assert_eq!(local_rows(&pool).await?, [50, 5672, 5797]);
assert!(apply_like_state(&pool, 1, &content, false, None, i64::MAX, "peer:2").await?);
assert_eq!(local_rows(&pool).await?, [50, 5797]);
// Restore the legacy double insert, including the user's original, higher track ID.
sqlx::raw_sql(
"INSERT INTO furumusic__user_liked_track(user_id,track_id,created_at)
VALUES(1,5686,'first'),(1,5672,'second'),(2,5672,'other user')",
)
.execute(&pool)
.await?;
sqlx::raw_sql(include_str!("repair_like_aliases.sql"))
.execute(&pool)
.await?;
assert_eq!(local_rows(&pool).await?, [50, 5686, 5797]);
let other: i64 =
sqlx::query_scalar("SELECT track_id FROM furumusic__user_liked_track WHERE user_id=2")
.fetch_one(&pool)
.await?;
assert_eq!(other, 5672);
sqlx::raw_sql(
"INSERT INTO furumusic__media_file VALUES(5,'five');
INSERT INTO furumusic__track(id,audio_file_id) VALUES(60,5)",
)
.execute(&pool)
.await?;
assert!(toggle(&pool, 1, 60).await?.unwrap().0);
let late_hash = format!("b3:{}", "c".repeat(64));
crate::federation::persist_content_id(&pool, 4, "new", &late_hash).await?;
crate::federation::persist_content_id(&pool, 5, "five", &late_hash).await?;
assert_eq!(local_rows(&pool).await?, [50, 5686, 5797]);
assert!(!toggle(&pool, 1, 60).await?.unwrap().0);
assert_eq!(local_rows(&pool).await?, [5686, 5797]);
Ok(())
}
}
@@ -0,0 +1,11 @@
-- A local click inserted its selected track before device sync chose another
-- copy of the same audio. Keep the first visible insertion for each listener.
WITH ranked AS (
SELECT l.id, row_number() OVER (
PARTITION BY l.user_id, a.content_id ORDER BY a.hidden, l.id
) AS position
FROM furumusic__user_liked_track l
JOIN furumusic__track_content_alias a ON a.track_id = l.track_id
)
DELETE FROM furumusic__user_liked_track l USING ranked
WHERE l.id = ranked.id AND ranked.position > 1
@@ -0,0 +1,6 @@
CREATE VIEW furumusic__track_content_alias AS
SELECT t.id AS track_id, c.content_id, (t.is_hidden OR r.is_hidden) AS hidden
FROM furumusic__federation_content_id_cache c
JOIN furumusic__media_file m ON m.id = c.media_file_id AND m.sha256_hash = c.sha256_hash
JOIN furumusic__track t ON t.audio_file_id = m.id
JOIN furumusic__release r ON r.id = t.release_id
+261 -51
View File
@@ -1,77 +1,287 @@
//! Optional lyrics ALPN; existing audio and catalog framing stay unchanged.
use anyhow::Result;
use music_dht::lyrics::{self, LYRICS_PROTOCOL_VERSION, LyricsResponse};
use music_dht::{ByteStream, StreamAcceptor};
//! Optional lyrics overlay, keyed by the exact audio content.
use anyhow::{Context, Result};
use futures_util::{StreamExt, stream};
use music_dht::lyrics::{self, LyricsRequest, LyricsResponse, LyricsVersion};
use music_dht::{ByteStream, EndpointId, MusicDhtService, StreamAcceptor};
use sqlx::PgPool;
use std::time::Duration;
use std::collections::HashSet;
use std::sync::{Arc, atomic::Ordering};
use std::time::{Duration, Instant};
const PEER_TIMEOUT: Duration = Duration::from_secs(5);
const LOOKUP_INTERVAL: Duration = Duration::from_secs(120);
impl super::Federation {
pub async fn track_lyrics(&self, owner: &str, content_id: &str) -> Result<LyricsResponse> {
let request = lyrics::LyricsRequest::new(content_id)?;
let service = self.service().await?;
let owner = owner.parse::<music_dht::EndpointId>()?;
let response = tokio::time::timeout(Duration::from_secs(15), async {
let mut stream = service.open_stream(owner, lyrics::LYRICS_ALPN).await?;
lyrics::write_request(&mut stream, &request).await?;
stream.send.finish()?;
let response = lyrics::read_response_from(&mut stream.recv).await?;
anyhow::ensure!(
response.content_id == request.content_id,
"lyrics content identity mismatch"
);
Ok::<_, anyhow::Error>(response)
})
.await;
// Optional protocol: older peers do not support this ALPN.
match response {
Ok(Ok(response)) => Ok(response),
_ => Ok(LyricsResponse {
version: LYRICS_PROTOCOL_VERSION,
content_id: request.content_id,
versions: vec![],
}),
pub async fn track_lyrics(
&self,
owner: Option<&str>,
content_id: &str,
) -> Result<LyricsResponse> {
let request = LyricsRequest::new(content_id)?;
let preferred = owner.map(str::parse::<EndpointId>).transpose()?;
let mut versions = Vec::new();
if let (Ok(_permit), Ok(service)) = (self.lyrics_slots.try_acquire(), self.service().await)
{
let mut seen = HashSet::from([service.endpoint_id()]);
let outcome =
tokio::time::timeout(PEER_TIMEOUT, service.search_content_id(content_id)).await;
let owners = outcome
.ok()
.and_then(Result::ok)
.into_iter()
.flat_map(|outcome| {
outcome
.local_results
.into_iter()
.chain(outcome.network_results)
})
.filter(|item| {
item.kind == music_dht::ItemKind::Track
&& item.content_id.as_deref() == Some(content_id)
})
.map(|item| item.owner);
let peers = preferred
.into_iter()
.chain(owners)
.chain(service.connected_peers())
.filter(|peer| seen.insert(*peer))
.take(12);
let mut replies = stream::iter(peers)
.map(|peer| fetch(&service, peer, &request))
.buffer_unordered(6);
while let Some(reply) = replies.next().await {
match reply {
Ok(found) => append_versions(&mut versions, found),
Err(error) => tracing::trace!(%error, "peer lyrics unavailable"),
}
}
if !versions.is_empty() && self.save_on_listen.load(Ordering::Relaxed) {
let result = async {
let pool = self.pool().await?;
crate::lyrics::save_peer_versions(&pool, content_id, &versions).await
}
.await;
if let Err(error) = result {
tracing::warn!(%content_id, %error, "could not save federated lyrics");
}
}
}
Ok(response(content_id.to_owned(), versions))
}
pub fn refresh_track_lyrics(self: &Arc<Self>, track_id: i64, owner: Option<String>) {
if !self.save_on_listen.load(Ordering::Relaxed) {
return;
}
let now = Instant::now();
{
let mut attempts = super::lock(&self.lyrics_attempts);
attempts.retain(|_, checked| now.duration_since(*checked) < LOOKUP_INTERVAL);
if attempts.len() >= 512 || attempts.contains_key(&track_id) {
return;
}
attempts.insert(track_id, now);
}
let federation = Arc::clone(self);
tokio::spawn(async move {
let result = async {
let pool = federation.pool().await?;
if let Some(content_id) =
crate::lyrics::track_content_id(&pool, track_id, true).await?
{
federation
.track_lyrics(owner.as_deref(), &content_id)
.await?;
}
Ok::<_, anyhow::Error>(())
}
.await;
if let Err(error) = result {
tracing::debug!(track_id, %error, "could not refresh federated lyrics");
}
});
}
}
fn append_versions(versions: &mut Vec<LyricsVersion>, found: Vec<LyricsVersion>) {
for mut version in found {
if versions.len() >= lyrics::MAX_LYRICS_VERSIONS {
break;
}
if versions
.iter()
.any(|existing| crate::lyrics::same_text(existing, &version))
{
continue;
}
// Peer IDs are scoped to one peer's response and may collide.
version.id = crate::lyrics::peer_version_id(&version);
versions.push(version);
}
}
async fn fetch(
service: &MusicDhtService,
peer: EndpointId,
request: &LyricsRequest,
) -> Result<Vec<LyricsVersion>> {
tokio::time::timeout(PEER_TIMEOUT, async {
let mut stream = service.open_stream(peer, lyrics::LYRICS_ALPN).await?;
lyrics::write_request(&mut stream, request).await?;
stream.send.finish()?;
let response = lyrics::read_response_from(&mut stream.recv).await?;
anyhow::ensure!(
response.content_id == request.content_id,
"lyrics content identity mismatch"
);
Ok(response.versions)
})
.await
.context("peer lyrics timed out")?
}
fn response(content_id: String, mut versions: Vec<LyricsVersion>) -> LyricsResponse {
let mut remaining = lyrics::MAX_LYRICS_RESPONSE_BYTES - 256;
versions.retain(|version| {
let Ok(encoded) = serde_json::to_vec(version) else {
return false;
};
let Some(rest) = remaining.checked_sub(encoded.len() + 1) else {
return false;
};
remaining = rest;
true
});
LyricsResponse {
version: lyrics::LYRICS_PROTOCOL_VERSION,
content_id,
versions,
}
}
pub async fn serve(mut acceptor: StreamAcceptor, pool: PgPool) {
let limit = std::sync::Arc::new(tokio::sync::Semaphore::new(16));
let limit = Arc::new(tokio::sync::Semaphore::new(16));
while let Some(stream) = acceptor.accept().await {
let Ok(permit) = std::sync::Arc::clone(&limit).try_acquire_owned() else {
let Ok(permit) = Arc::clone(&limit).try_acquire_owned() else {
continue;
};
let pool = pool.clone();
tokio::spawn(async move {
let _permit = permit;
if let Err(error) =
tokio::time::timeout(Duration::from_secs(30), serve_one(stream, &pool)).await
{
tracing::debug!(%error,"lyrics stream timed out");
match tokio::time::timeout(Duration::from_secs(12), serve_one(stream, &pool)).await {
Ok(Ok(())) => {}
Ok(Err(error)) => tracing::debug!(%error, "could not serve lyrics"),
Err(_) => tracing::debug!("lyrics stream timed out"),
}
});
}
}
async fn serve_one(mut stream: ByteStream, pool: &PgPool) -> Result<()> {
let request = lyrics::read_request_from(&mut stream.recv).await?;
let hash:Option<String>=sqlx::query_scalar("SELECT m.sha256_hash::text FROM furumusic__track t
JOIN furumusic__release r ON r.id=t.release_id
JOIN furumusic__media_file m ON m.id=t.audio_file_id
JOIN furumusic__federation_content_id_cache c ON c.media_file_id=m.id AND c.sha256_hash=m.sha256_hash
WHERE c.content_id=$1 AND NOT t.is_hidden AND NOT r.is_hidden LIMIT 1")
.bind(&request.content_id).fetch_optional(pool).await?;
let versions = match hash {
let versions = match crate::lyrics::visible_content_hash(pool, &request.content_id).await? {
Some(hash) => crate::lyrics::versions(pool, &hash).await?,
None => vec![],
};
lyrics::write_response(
&mut stream,
&LyricsResponse {
version: LYRICS_PROTOCOL_VERSION,
content_id: request.content_id,
versions,
},
)
.await?;
send_response(stream, response(request.content_id, versions)).await
}
async fn send_response(mut stream: ByteStream, reply: LyricsResponse) -> Result<()> {
lyrics::write_response(&mut stream, &reply).await?;
stream.send.finish()?;
// ByteStream owns the connection: give the FIN time to reach the receiver.
let _ = tokio::time::timeout(Duration::from_secs(2), stream.send.stopped()).await;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn localhost_peer_receives_complete_lyrics_response() {
use music_dht::{MusicDhtConfig, NetworkId};
let scratch = std::env::temp_dir().join(format!(
"furumi-web-lyrics-{}-{}",
std::process::id(),
chrono::Utc::now().timestamp_nanos_opt().unwrap()
));
let server_dir = scratch.join("server");
let client_dir = scratch.join("client");
std::fs::create_dir_all(&server_dir).unwrap();
std::fs::create_dir_all(&client_dir).unwrap();
let network = NetworkId::from_name(&scratch.to_string_lossy());
let server_config = MusicDhtConfig::builder()
.data_dir(server_dir)
.network_id(network)
.schema_independent_stream_protocol(lyrics::LYRICS_ALPN)
.build()
.unwrap();
let client_config = MusicDhtConfig::builder()
.data_dir(client_dir)
.network_id(network)
.build()
.unwrap();
let (server, _server_events) = MusicDhtService::start(server_config).await.unwrap();
let (client, _client_events) = MusicDhtService::start(client_config).await.unwrap();
client
.connect(server.ticket().await.unwrap())
.await
.unwrap();
let mut acceptor = server.stream_acceptor(lyrics::LYRICS_ALPN).unwrap();
let task = tokio::spawn(async move {
let mut stream = acceptor.accept().await.unwrap();
let request = lyrics::read_request_from(&mut stream.recv).await.unwrap();
let version = LyricsVersion {
id: "version".into(),
label: "Lyrics".into(),
source: "manual".into(),
source_id: None,
language: None,
plain_text: Some("Words".into()),
synced_lrc: None,
instrumental: false,
};
send_response(stream, response(request.content_id, vec![version]))
.await
.unwrap();
});
let request = LyricsRequest::new(format!("b3:{}", "a".repeat(64))).unwrap();
let versions = fetch(&client, server.endpoint_id(), &request)
.await
.unwrap();
assert_eq!(versions[0].plain_text.as_deref(), Some("Words"));
task.await.unwrap();
client.shutdown().await.unwrap();
server.shutdown().await.unwrap();
// Release both SQLite handles before removing the test directories on Windows.
drop(client);
drop(server);
std::fs::remove_dir_all(scratch).unwrap();
}
#[test]
fn merges_alternatives_with_colliding_peer_ids() {
let make = |text: &str| LyricsVersion {
id: "original".into(),
label: "Lyrics".into(),
source: "manual".into(),
source_id: None,
language: None,
plain_text: Some(text.into()),
synced_lrc: None,
instrumental: false,
};
let mut versions = vec![];
append_versions(
&mut versions,
vec![make("First"), make("Second"), make("First")],
);
assert_eq!(versions.len(), 2);
assert_ne!(versions[0].id, versions[1].id);
response(format!("b3:{}", "a".repeat(64)), versions)
.validate()
.unwrap();
}
}
+64 -3
View File
@@ -289,6 +289,8 @@ pub struct Federation {
content_cache: std::sync::Mutex<HashMap<i64, (String, String)>>,
content_pending: std::sync::Mutex<HashSet<i64>>,
prepared_cache: std::sync::Mutex<HashMap<String, (PathBuf, String)>>,
lyrics_slots: tokio::sync::Semaphore,
lyrics_attempts: std::sync::Mutex<HashMap<i64, std::time::Instant>>,
artwork_cache: std::sync::Mutex<HashMap<String, CachedArtwork>>,
download_locks: std::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
pool: tokio::sync::OnceCell<PgPool>,
@@ -324,6 +326,8 @@ pub fn handle() -> Arc<Federation> {
content_cache: std::sync::Mutex::new(Default::default()),
content_pending: std::sync::Mutex::new(Default::default()),
prepared_cache: std::sync::Mutex::new(Default::default()),
lyrics_slots: tokio::sync::Semaphore::new(4),
lyrics_attempts: std::sync::Mutex::new(Default::default()),
artwork_cache: std::sync::Mutex::new(Default::default()),
download_locks: std::sync::Mutex::new(Default::default()),
pool: tokio::sync::OnceCell::new(),
@@ -698,6 +702,11 @@ impl Federation {
stop_running(guard.take()).await;
}
/// Whether the node runs and can search the network.
pub(crate) async fn is_running(&self) -> bool {
self.running.lock().await.is_some()
}
async fn service(&self) -> Result<Arc<MusicDhtService>> {
self.running
.lock()
@@ -1321,27 +1330,79 @@ async fn similarity_route_sync_loop(
}
}
/// The content id of a local audio file. A cached id with the file's current
/// hash is returned as is; otherwise the file is hashed off the async runtime
/// and stored in the shared cache, as the federation warmer does. Only
/// `storage_dir` (`agent_storage_dir`) is needed: the node does not have to
/// run. `None` when the storage directory is not set or the file is unreadable.
pub(crate) async fn ensure_local_content_id(
pool: &PgPool,
storage_dir: &str,
media_file_id: i64,
) -> Result<Option<String>> {
let Some(row) = sqlx::query(
"SELECT m.file_path, m.sha256_hash, c.content_id
FROM furumusic__media_file m
LEFT JOIN furumusic__federation_content_id_cache c
ON c.media_file_id = m.id AND c.sha256_hash = m.sha256_hash
WHERE m.id = $1",
)
.bind(media_file_id)
.fetch_optional(pool)
.await?
else {
return Ok(None);
};
let cached: Option<String> = row.get(2);
if let Some(content_id) = cached.as_deref().and_then(music_dht::normalize_content_id) {
return Ok(Some(content_id));
}
if storage_dir.trim().is_empty() {
return Ok(None);
}
let file_path: String = row.get(0);
let sha256_hash: String = row.get(1);
let storage_dir = storage_dir.to_owned();
let content_id =
tokio::task::spawn_blocking(move || audio_content_id(&storage_dir, &file_path))
.await
.ok()
.flatten();
let Some(content_id) = content_id else {
return Ok(None);
};
persist_content_id(pool, media_file_id, &sha256_hash, &content_id).await?;
Ok(Some(content_id))
}
async fn persist_content_id(
pool: &PgPool,
media_file_id: i64,
sha256_hash: &str,
content_id: &str,
) -> Result<()> {
sqlx::query(
let mut tx = pool.begin().await?;
let written = sqlx::query(
"INSERT INTO furumusic__federation_content_id_cache
(media_file_id, sha256_hash, content_id, updated_at)
VALUES ($1, $2, $3, $4)
ON CONFLICT (media_file_id) DO UPDATE SET
sha256_hash = EXCLUDED.sha256_hash,
content_id = EXCLUDED.content_id,
updated_at = EXCLUDED.updated_at",
updated_at = EXCLUDED.updated_at
WHERE (furumusic__federation_content_id_cache.sha256_hash, furumusic__federation_content_id_cache.content_id)
IS DISTINCT FROM (EXCLUDED.sha256_hash, EXCLUDED.content_id)",
)
.bind(media_file_id)
.bind(sha256_hash)
.bind(content_id)
.bind(now_iso())
.execute(pool)
.execute(&mut *tx)
.await?;
if written.rows_affected() > 0 {
devices::likes::on_content_available(&mut tx, content_id, None).await?;
}
tx.commit().await?;
Ok(())
}
+5 -9
View File
@@ -288,6 +288,7 @@ impl Federation {
};
let _download_guard = download_lock.lock().await;
if let Some(track_id) = local_track_id(&pool, &content_id).await? {
self.refresh_track_lyrics(track_id, Some(owner.to_owned()));
progress(DownloadProgress {
phase: "ready",
received: 1,
@@ -393,6 +394,7 @@ impl Federation {
total: 0,
});
let track_id = materialize(&pool, &storage_root, &content_id, downloaded).await?;
self.refresh_track_lyrics(track_id, Some(owner.to_string()));
// Materialization is the playback boundary: return the local track
// immediately so the browser can replace the pending queue entry and
// start it. Publishing must not keep the prepare stream stuck at 100%
@@ -636,6 +638,7 @@ async fn materialize(
.fetch_optional(&mut *tx)
.await?
{
super::devices::likes::on_content_available(&mut tx, content_id, Some(track_id)).await?;
tx.commit().await?;
return Ok(track_id);
}
@@ -729,14 +732,7 @@ async fn materialize(
.bind(now_iso())
.execute(&mut *tx)
.await?;
sqlx::query(
"UPDATE furumusic__fed_state_like
SET local_track_id = $2 WHERE content_id = $1",
)
.bind(content_id)
.bind(track_id)
.execute(&mut *tx)
.await?;
super::devices::likes::on_content_available(&mut tx, content_id, Some(track_id)).await?;
sqlx::query(
"UPDATE furumusic__fed_state_playlist_item
SET local_track_id = $2 WHERE content_id = $1",
@@ -746,7 +742,7 @@ async fn materialize(
.execute(&mut *tx)
.await?;
tx.commit().await?;
super::devices::materialize_content_state(pool, content_id, track_id).await?;
super::devices::materialize_playlist_items(pool, content_id, track_id).await?;
// Artwork is non-authoritative for identity and may be installed after
// the audio transaction. Failure does not invalidate a verified track.
+103 -49
View File
@@ -9,8 +9,8 @@ use std::sync::Arc;
use anyhow::Result;
pub use music_dht::catalog::CATALOG_ALPN;
use music_dht::catalog::{
CatalogArtist, CatalogArtistPreview, CatalogImageHeader as ImageHeader, CatalogRelease,
CatalogRequest, CatalogResponse, CatalogTrack,
CatalogAppearance, CatalogArtist, CatalogArtistPreview, CatalogImageHeader as ImageHeader,
CatalogRelease, CatalogRequest, CatalogResponse, CatalogTrack,
};
use music_dht::{ByteStream, EndpointId, ItemId, ItemKind, StreamAcceptor, normalize_name};
use serde::{Deserialize, Serialize};
@@ -597,16 +597,28 @@ async fn build_catalog(pool: &PgPool, own: &EndpointId, artist: &str) -> Result<
.fetch_all(pool)
.await?;
// Fetch every release track and its credits in one round trip. The old
// implementation performed one track query per release and one artist
// query per track; a large discography could not finish before the
// client's five-second catalog deadline when PostgreSQL was busy.
let release_ids: Vec<i64> = release_rows.iter().map(|row| row.get(0)).collect();
let track_rows = if release_ids.is_empty() {
Vec::new()
} else {
sqlx::query(
"SELECT t.release_id, t.id, t.title, t.track_number, t.disc_number,
let mut releases = Vec::with_capacity(release_rows.len());
let mut owned = HashMap::with_capacity(release_rows.len());
for row in release_rows {
owned.insert(row.get::<i64, _>("id"), releases.len());
releases.push(CatalogRelease {
title: row.get("title"),
release_type: row.get("release_type"),
year: row.get("year"),
tracks: Vec::new(),
});
}
// Include the full tracklist of owned releases, but only the credited
// recordings on someone else's releases. UNION handles overlapping credits.
let release_ids: Vec<_> = owned.keys().copied().collect();
let track_rows = sqlx::query(
"WITH catalog_tracks AS (
SELECT id FROM furumusic__track WHERE release_id = ANY($1)
UNION
SELECT track_id FROM furumusic__track_artist
WHERE artist_id = $2 AND role IN ('main', 'featuring')
)
SELECT t.release_id, t.id, t.title, t.track_number, t.disc_number,
t.duration_seconds, c.content_id,
COALESCE(
array_agg(a.name::text ORDER BY ta.position)
@@ -617,52 +629,50 @@ async fn build_catalog(pool: &PgPool, own: &EndpointId, artist: &str) -> Result<
array_agg(a.name::text ORDER BY ta.position)
FILTER (WHERE ta.role = 'featuring'),
ARRAY[]::text[]
) AS featured_artists
FROM furumusic__track t
) AS featured_artists, r.title AS release_title, r.release_type, r.year
FROM catalog_tracks selected
JOIN furumusic__track t ON t.id = selected.id
JOIN furumusic__release r ON r.id = t.release_id AND NOT r.is_hidden
JOIN furumusic__media_file m ON m.id = t.audio_file_id
LEFT JOIN furumusic__federation_content_id_cache c
ON c.media_file_id = m.id AND c.sha256_hash = m.sha256_hash
LEFT JOIN furumusic__track_artist ta ON ta.track_id = t.id
LEFT JOIN furumusic__artist a ON a.id = ta.artist_id
WHERE t.release_id = ANY($1) AND t.is_hidden = false
WHERE NOT t.is_hidden
GROUP BY t.release_id, t.id, t.title, t.track_number, t.disc_number,
t.duration_seconds, c.content_id
t.duration_seconds, c.content_id, r.title, r.release_type, r.year
ORDER BY t.release_id, t.disc_number NULLS FIRST,
t.track_number NULLS LAST, t.title",
)
.bind(&release_ids)
.fetch_all(pool)
.await?
};
let mut tracks_by_release: HashMap<i64, Vec<CatalogTrack>> = HashMap::new();
)
.bind(release_ids)
.bind(artist_id)
.fetch_all(pool)
.await?;
let mut appears_on = Vec::new();
for row in track_rows {
let release_id: i64 = row.get(0);
let track_id: i64 = row.get(1);
let duration: f64 = row.get(5);
tracks_by_release
.entry(release_id)
.or_default()
.push(CatalogTrack {
title: row.get(2),
artists: row.get(7),
featured_artists: row.get(8),
track_number: row.get(3),
disc_number: row.get(4),
duration_seconds: (duration > 0.0).then_some(duration),
content_id: row.get(6),
item_id: item_id_of(own, track_id),
let release_id: i64 = row.get("release_id");
let track_id: i64 = row.get("id");
let duration: f64 = row.get("duration_seconds");
let track = CatalogTrack {
title: row.get("title"),
artists: row.get("artists"),
featured_artists: row.get("featured_artists"),
track_number: row.get("track_number"),
disc_number: row.get("disc_number"),
duration_seconds: (duration > 0.0).then_some(duration),
content_id: row.get("content_id"),
item_id: item_id_of(own, track_id),
};
if let Some(&index) = owned.get(&release_id) {
releases[index].tracks.push(track);
} else {
appears_on.push(CatalogAppearance {
release_title: row.get("release_title"),
release_type: row.get("release_type"),
year: row.get("year"),
track,
});
}
let mut releases = Vec::new();
for release_row in release_rows {
let release_id: i64 = release_row.get(0);
releases.push(CatalogRelease {
title: release_row.get(1),
release_type: release_row.get(2),
year: release_row.get(3),
tracks: tracks_by_release.remove(&release_id).unwrap_or_default(),
});
}
}
Ok(CatalogResponse {
@@ -670,12 +680,56 @@ async fn build_catalog(pool: &PgPool, own: &EndpointId, artist: &str) -> Result<
artist: Some(CatalogArtist {
name: artist_row.get(1),
releases,
appears_on: Vec::new(),
appears_on,
}),
..CatalogResponse::default()
})
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL"]
async fn postgres_catalog_separates_guest_tracks_from_owned_releases() -> Result<()> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&std::env::var("FURU_FEDERATION_TEST_DATABASE_URL")?)
.await?;
sqlx::raw_sql("
CREATE TEMP TABLE furumusic__artist(id bigint PRIMARY KEY, name text, is_hidden bool);
CREATE TEMP TABLE furumusic__release(id bigint PRIMARY KEY, title text, release_type text, year int, is_hidden bool);
CREATE TEMP TABLE furumusic__release_artist(release_id bigint, artist_id bigint);
CREATE TEMP TABLE furumusic__track(id bigint PRIMARY KEY, release_id bigint, title text, track_number int,
disc_number int DEFAULT 1, duration_seconds float8 DEFAULT 120, audio_file_id bigint DEFAULT 1, is_hidden bool DEFAULT false);
CREATE TEMP TABLE furumusic__track_artist(track_id bigint, artist_id bigint, role text, position int);
CREATE TEMP TABLE furumusic__media_file(id bigint, sha256_hash text);
CREATE TEMP TABLE furumusic__federation_content_id_cache(media_file_id bigint, sha256_hash text, content_id text);
INSERT INTO furumusic__artist VALUES (1,'Host',false), (2,'Guest',false);
INSERT INTO furumusic__release VALUES (1,'Album','album',2020,false), (2,'Hidden','single',2021,true);
INSERT INTO furumusic__release_artist VALUES (1,1),(2,1);
INSERT INTO furumusic__track(id,release_id,title,track_number,is_hidden)
VALUES (1,1,'Duet',1,false),(2,1,'Solo',2,false),(3,2,'Invisible release',1,false),(4,1,'Invisible track',3,true);
INSERT INTO furumusic__track_artist VALUES (1,1,'main',0),(1,2,'featuring',1),(2,1,'main',0),
(3,2,'featuring',1),(4,2,'featuring',1);
INSERT INTO furumusic__media_file VALUES (1,'sha');
INSERT INTO furumusic__federation_content_id_cache VALUES (1,'sha','content');
").execute(&pool).await?;
let own = music_dht::SecretKey::from_bytes(&[1; 32]).public();
let guest = build_catalog(&pool, &own, "Guest").await?.artist.unwrap();
assert!(guest.releases.is_empty());
assert_eq!(guest.appears_on.len(), 1);
let duet = &guest.appears_on[0];
assert_eq!(duet.release_title, "Album");
assert_eq!(duet.track.title, "Duet");
assert_eq!(duet.track.featured_artists, ["Guest"]);
assert_eq!(duet.track.content_id.as_deref(), Some("content"));
assert_eq!(duet.track.item_id, item_id_of(&own, 1));
let host = build_catalog(&pool, &own, "Host").await?.artist.unwrap();
assert!(host.appears_on.is_empty());
assert_eq!(host.releases.len(), 1);
assert_eq!(host.releases[0].tracks.len(), 2);
assert_eq!(host.releases[0].tracks[1].title, "Solo");
Ok(())
}
async fn build_artist_slice(
pool: &PgPool,
cursor: Option<String>,
+303 -10
View File
@@ -280,9 +280,93 @@ translations! {
// Player UI
player_library: "Library" , "Библиотека";
player_artists: "Artists" , "Артисты";
player_global_library: "Global" , "Global";
player_global_library: "Catalog" , "Каталог";
player_all_music: "All music" , "Вся музыка";
player_followed_page: "Followed" , "Подписки";
player_my_listening: "My listening" , "Мои прослушивания";
player_quick_access: "Quick access" , "Быстрый доступ";
player_my_playlists: "My playlists" , "Мои плейлисты";
player_pinned: "Pinned" , "Закреплено";
player_account_menu: "Account menu" , "Меню аккаунта";
player_offline_listening: "Offline listening" , "Офлайн-прослушивание";
player_offline_disabled: "Offline listening is off" , "Офлайн-режим выключен";
player_offline_online: "Online" , "Онлайн";
player_offline_manual: "Offline" , "Офлайн";
player_offline_saved_only: "Saved music only" , "Только сохранённая музыка";
player_offline_manual_reason: "Manual" , "Вручную";
player_offline_auto_reason: "No server" , "Нет связи";
player_offline_auto: "Offline · automatic" , "Офлайн · автоматически";
player_offline_manage: "Manage" , "Управление";
player_offline_manage_label: "Manage offline music" , "Управление офлайн-музыкой";
player_offline_mode: "Offline mode" , "Офлайн-режим";
player_offline_mode_hint: "Uses only the local cache. No network requests." , "Плеер работает только с локальным кешем, без сетевых запросов.";
player_offline_enable: "Save music on this device" , "Сохранять музыку на устройстве";
player_offline_preparing: "Preparing offline listening…" , "Готовим плеер для офлайн-прослушивания…";
player_offline_hint: "Played tracks are saved automatically. You can also save a track from its menu." , "Прослушанные треки сохраняются автоматически. Трек также можно сохранить через его меню.";
player_offline_unsupported: "This browser cannot store music offline." , "Этот браузер не поддерживает сохранение музыки офлайн.";
player_offline_used: "Audio and artwork" , "Аудио и обложки";
player_offline_limit: "Cache limit" , "Лимит кеша";
player_offline_saved: "Saved music" , "Сохранённая музыка";
player_offline_open_cache: "Open cache" , "Открыть кеш";
player_offline_back_settings: "Back to settings" , "Назад к настройкам";
player_offline_cache_search: "Search titles and artists" , "Поиск по трекам и артистам";
player_offline_sort: "Sort by" , "Сортировка";
player_offline_download_date: "Download date" , "Дата загрузки";
player_offline_last_played: "Last played" , "Последнее прослушивание";
player_offline_play_count: "Plays" , "Прослушивания";
player_offline_bitrate: "Bitrate" , "Битрейт";
player_offline_ascending: "Ascending order" , "По возрастанию";
player_offline_descending: "Descending order" , "По убыванию";
player_offline_manage_storage: "Manage storage" , "Освободить место";
player_offline_cleanup_scope: "Date filters apply to all saved music, including tracks outside the search results." , "Очистка по дате охватывает все сохранённые треки, включая те, которые не попали в результаты поиска.";
player_offline_remove_by: "Removal criterion" , "Критерий удаления";
player_offline_downloaded_before: "Downloaded before" , "Загружены до";
player_offline_played_before: "Last played before" , "Последнее прослушивание до";
player_offline_never_cleanup: "For tracks with no plays, the download date is used." , "Для треков без прослушиваний используется дата загрузки.";
player_offline_cutoff: "Cutoff date" , "Дата отсечения";
player_offline_preview_removal: "Preview removal" , "Проверить перед удалением";
player_offline_will_free: "Space to free" , "Освободится";
player_offline_remove_confirm: "Remove saved music?" , "Удалить сохранённую музыку?";
player_offline_saved_all: "All saved tracks on this device" , "Все сохранённые треки на этом устройстве";
player_offline_pages: "Saved music pages" , "Страницы сохранённой музыки";
player_offline_previous_page: "Previous page" , "Предыдущая страница";
player_offline_next_page: "Next page" , "Следующая страница";
player_offline_empty: "No music saved on this device yet." , "На этом устройстве пока нет сохранённой музыки.";
player_offline_empty_uploads: "None of your uploads are saved on this device." , "На этом устройстве пока нет треков из ваших загрузок.";
player_offline_empty_followed: "No music by your followed artists is saved on this device." , "На этом устройстве пока нет музыки артистов, на которых вы подписаны.";
player_offline_start: "Play a track online to add it to your offline library." , "Включите трек онлайн, чтобы сохранить его для прослушивания офлайн.";
player_offline_page_missing: "This page is unavailable offline." , "Эта страница недоступна в офлайн-режиме.";
player_offline_open_catalog: "Open saved catalog" , "Открыть сохранённый каталог";
player_offline_clear: "Clear cache" , "Очистить кеш";
player_offline_remove: "Remove from this device" , "Удалить с устройства";
player_offline_save: "Save for offline listening" , "Сохранить для офлайна";
player_offline_available: "Saved on this device" , "Сохранено на устройстве";
player_offline_saving: "Saving music…" , "Сохраняется музыка…";
player_offline_devices: "Devices are unavailable offline." , "Устройства недоступны в офлайн-режиме.";
player_connected_devices: "Connected devices", "Подключённые устройства";
player_device_web_sessions: "Browser sessions", "Сеансы в браузере";
player_device_trusted: "Trusted devices", "Доверенные устройства";
player_device_current: "This device", "Это устройство";
player_device_active: "Active", "Активен";
player_device_no_sessions: "No browser sessions", "Нет сеансов в браузере";
player_device_no_trusted: "No trusted devices", "Нет доверенных устройств";
player_device_sync: "Sync now", "Синхронизировать";
player_device_sync_details: "Sync details", "Детали синхронизации";
player_device_linked: "Linked devices", "Связанные устройства";
player_device_queued: "Queued changes", "Изменения в очереди";
player_device_unresolved: "Unresolved items", "Несопоставленные записи";
player_device_last_sync: "Last sync", "Последняя синхронизация";
player_device_pair: "Pair device", "Подключить устройство";
player_device_requests: "Pairing requests", "Запросы на подключение";
player_device_other_group: "Already in another sync group", "Состоит в другой группе синхронизации";
player_device_use_group: "Use existing group", "Использовать его группу";
player_device_revoke: "Revoke access", "Отозвать доступ";
player_device_generate: "Create invite", "Создать приглашение";
player_device_invite: "Device invite", "Приглашение устройства";
player_device_paste_invite: "Paste frid:// invite", "Вставьте приглашение frid://";
player_featured_only_artists: "Featured only" , "Только фиты";
player_release: "Release" , "Релиз";
player_album_cover: "Album cover" , "Обложка альбома";
player_releases: "Releases" , "Релизы";
player_tracks: "Tracks" , "Треки";
player_title: "Title" , "Название";
@@ -294,18 +378,26 @@ translations! {
player_follow_artist: "Follow artist" , "Подписаться на артиста";
player_no_followed_artists: "No followed artists" , "Нет подписок на артистов";
player_playlists: "Playlists" , "Плейлисты";
player_published_playlists: "Published Playlists" , "Опубликованные плейлисты";
player_public: "Public" , "Публичный";
player_published: "Published" , "Опубликован";
player_by: "by" , "от";
player_tracks_count: "tracks" , "треков";
player_track_one: "track" , "трек";
player_track_few: "tracks" , "трека";
player_files_count: "files" , "файлов";
player_releases_count: "releases" , "релизов";
player_release_one: "release" , "релиз";
player_release_few: "releases" , "релиза";
player_plays_count: "plays" , "прослушиваний";
player_play_one: "play" , "прослушивание";
player_play_few: "plays" , "прослушивания";
player_likes_count: "likes" , "лайков";
player_likes_playlist: "Likes" , "Лайки";
player_likes_playlist: "Liked songs" , "Мне нравится";
player_listened: "listened" , "прослушано";
player_search_placeholder: "Search artists, releases, tracks, podcasts..." , "Поиск артистов, релизов, треков, подкастов...";
player_playlist_search: "Search this playlist" , "Поиск по плейлисту";
player_clear_playlist_search: "Clear playlist search" , "Очистить поиск по плейлисту";
player_playlist_no_matches: "No matching tracks" , "Подходящих треков нет";
player_search_similar_to: "Search similar to:" , "Поиск похожих на:";
player_find_similar: "Find similar tracks" , "Найти похожие треки";
player_similarity_failed: "Similarity search failed" , "Не удалось найти похожие треки";
@@ -314,8 +406,28 @@ translations! {
player_active_device: "Active device" , "Активный девайс";
player_no_results: "No results found" , "Ничего не найдено";
player_new_playlist: "New Playlist" , "Новый плейлист";
player_sidebar_pin: "Pin to sidebar" , "Закрепить в меню";
player_sidebar_unpin: "Unpin from sidebar" , "Открепить из меню";
player_reorder_pin: "Move shortcut" , "Переместить в меню";
player_reorder_hint: "Drag or use the up and down arrows", "Перетащите или нажмите стрелку вверх или вниз";
player_pin_removed: "Unpinned" , "Откреплено";
player_pin_undo: "Undo" , "Отменить";
player_pin_failed: "Could not update this shortcut." , "Не удалось обновить закрепление.";
player_more_actions: "More actions" , "Ещё";
player_collection_empty: "No playlists yet." , "Плейлистов пока нет.";
player_rename_playlist: "Rename Playlist" , "Переименовать плейлист";
player_playlist_name: "Playlist name" , "Название плейлиста";
player_playlist_unavailable: "Playlist unavailable" , "Плейлист недоступен";
player_playlist_cover: "Playlist cover" , "Обложка плейлиста";
player_edit_playlist_cover: "Edit playlist cover" , "Изменить обложку плейлиста";
player_playlist_cover_auto: "Automatic" , "Авто";
player_playlist_cover_releases: "Artwork" , "Обложки";
player_playlist_cover_upload: "Upload image" , "Загрузить";
player_playlist_cover_select: "Choose 1 to 4 covers" , "Выберите от 1 до 4 обложек";
player_playlist_cover_empty: "No artwork in this playlist." , "В этом плейлисте нет обложек.";
player_choose_cover_file: "Choose image" , "Выбрать файл";
player_playlist_cover_invalid: "Choose a JPEG, PNG or WebP image up to 4 MiB" , "Выберите изображение JPEG, PNG или WebP до 4 МиБ";
player_playlist_header_failed: "Could not save the playlist. Try again." , "Не удалось сохранить плейлист. Попробуйте ещё раз.";
player_add_to_playlist: "Add to Playlist" , "Добавить в плейлист";
player_cancel: "Cancel" , "Отмена";
player_create: "Create" , "Создать";
@@ -326,14 +438,25 @@ translations! {
player_rename: "Rename" , "Переименовать";
player_close: "Close" , "Закрыть";
player_interface_language: "Interface language" , "Язык интерфейса";
player_language_description: "Choose the language used by the web player." , "Выберите язык интерфейса веб-плеера.";
player_switch_language: "Русский" , "English";
player_settings_connect: "Connect" , "Подключить";
player_settings_reconnect: "Reconnect" , "Переподключить";
player_settings_disconnect: "Disconnect" , "Отключить";
player_get_app: "Get app", "Скачать приложение";
player_app_terminal_client: "Terminal client", "Консольный клиент";
player_app_binaries: "Binaries", "Бинарники";
player_app_latest_release: "Latest release", "Последний релиз";
player_app_arch_repo: "Arch repository", "Репозиторий Arch";
player_app_arch_guide: "Check the Arch repository for package availability. You can also download the Linux archive, extract it, and run the binary from the extracted folder.", "Проверьте наличие пакета в репозитории Arch. Также можно скачать архив для Linux, распаковать его и запустить бинарник из распакованной папки.";
player_app_macos_guide: "On an Apple Silicon Mac with Homebrew, run these commands in Terminal.", "На Mac с Apple Silicon и установленным Homebrew выполните эти команды в Терминале.";
player_app_windows_guide: "Download the Windows x86-64 ZIP from the release assets, extract it, and run this command in PowerShell from the extracted folder.", "Скачайте ZIP для Windows x86-64 из файлов релиза, распакуйте его и выполните эту команду в PowerShell из распакованной папки.";
player_app_binary_guide: "In the release assets, choose the archive for your system and processor. Extract it and run the executable from the extracted folder.", "Выберите в файлах релиза архив для вашей системы и процессора. Распакуйте его и запустите исполняемый файл из распакованной папки.";
player_log_out: "Log out" , "Выйти";
player_admin_panel: "Admin Panel" , "Админка";
player_info: "Info" , "Информация";
player_no_details: "No details available." , "Нет подробностей.";
player_release_info: "Release info" , "Информация о релизе";
player_track_info: "Track info" , "Информация о треке";
player_track_actions: "Track actions" , "Действия с треком";
player_type: "Type" , "Тип";
player_year: "Year" , "Год";
player_uploaders: "Uploaders" , "Загрузили";
@@ -356,10 +479,10 @@ translations! {
player_lastfm_connected: "Connected as {user}" , "Подключён: {user}";
player_lastfm_reconnect: "Reconnect Last.fm" , "Переподключить Last.fm";
player_lastfm_not_configured: "Last.fm is not configured" , "Last.fm не настроен";
player_lastfm_status_connect: "connect account" , "подключить аккаунт";
player_lastfm_status_connected: "connected" , "подключён";
player_lastfm_status_reconnect: "reconnect account" , "переподключить аккаунт";
player_lastfm_status_not_configured: "not configured" , "не настроен";
player_lastfm_status_connect: "Not connected" , "Не подключён";
player_lastfm_status_connected: "Connected" , "Подключён";
player_lastfm_status_reconnect: "Sign in again" , "Нужен повторный вход";
player_lastfm_status_not_configured: "Not configured" , "Не настроен";
player_lastfm_disconnect_confirm: "Disconnect Last.fm account {user}?" , "Отвязать аккаунт Last.fm {user}?";
player_lastfm_connect_failed: "Could not open Last.fm connection" , "Не удалось открыть подключение Last.fm";
player_lastfm_disconnect_failed: "Could not disconnect Last.fm" , "Не удалось отвязать Last.fm";
@@ -384,6 +507,10 @@ translations! {
player_queue_empty: "Queue is empty" , "Очередь пуста";
player_shuffle: "Shuffle" , "Перемешать";
player_repeat: "Repeat" , "Повтор";
player_pause: "Pause" , "Пауза";
player_seek: "Playback position" , "Позиция воспроизведения";
player_mute: "Mute" , "Выключить звук";
player_unmute: "Unmute" , "Включить звук";
player_volume: "Volume" , "Громкость";
player_appears_on: "Appears on" , "Участвует в";
player_top_tracks: "Popular tracks" , "Популярные треки";
@@ -397,6 +524,28 @@ translations! {
// Player download/history UI
player_torrent_manager: "Download Manager" , "Менеджер загрузок";
player_download_title: "Downloads", "Загрузки";
player_download_music: "Add music", "Добавить музыку";
player_download_history_tab: "History", "История";
player_download_latest: "Latest upload", "Последняя загрузка";
player_download_select_page: "Select this page", "Выбрать на странице";
player_download_forget: "Remove", "Убрать";
player_download_forget_question: "Remove from history?", "Убрать из истории?";
player_download_forget_hint: "Music stays in your library. Ongoing transfers continue.", "Музыка останется в библиотеке. Активные загрузки продолжатся.";
player_download_forget_error: "Could not update the history. Try again.", "Не удалось обновить историю. Попробуйте ещё раз.";
player_download_file_one: "file", "файл";
player_download_file_few: "files", "файла";
player_download_overview: "Overview", "Обзор";
player_download_add: "Add", "Добавить";
player_download_imports: "Imports", "Импорт";
player_download_activity: "Recent activity", "Последние загрузки";
player_download_filter_all: "All statuses", "Все статусы";
player_download_filter_active: "In progress", "В работе";
player_download_filter_attention: "Needs attention", "Требуют внимания";
player_download_filter_history: "Finished", "Завершённые";
player_download_empty: "No downloads yet", "Загрузок пока нет";
player_download_empty_filter: "No downloads with this status", "Нет загрузок с таким статусом";
player_download_more: "Show more", "Показать ещё";
player_import_torrent: "Open Download Manager" , "Открыть менеджер загрузок";
player_youtube: "YouTube" , "YouTube";
player_torrents: "Torrents" , "Торренты";
@@ -413,6 +562,7 @@ translations! {
player_youtube_clear_selection: "Clear selection" , "Снять все";
player_youtube_selected_count: "selected" , "выбрано";
player_import_destination: "Add downloads to a playlist" , "Добавить загруженное в плейлист";
player_download_playlist_label: "Playlist" , "Плейлист";
player_import_destination_hint: "Selected audio tracks will be added automatically after processing, including tracks already in the library." , "Выбранные аудиотреки будут добавлены автоматически после обработки, включая уже имеющиеся в библиотеке.";
player_youtube_destination: "Add imported tracks to playlist" , "Добавить импортированные треки в плейлист";
player_youtube_no_destination: "Do not add to a playlist" , "Не добавлять в плейлист";
@@ -548,6 +698,8 @@ translations! {
player_magnet_link: "Magnet link" , "Magnet-ссылка";
player_upload_content: "Preview torrent" , "Проверить торрент";
player_add_torrent: "Add torrent" , "Добавить торрент";
player_download_another: "Add another", "Добавить ещё";
player_finish_upload: "Finish upload", "Завершить загрузку";
player_download_selected: "Download selected" , "Скачать выбранное";
player_pause_download: "Pause download" , "Поставить на паузу";
player_expand_all: "Expand all" , "Развернуть всё";
@@ -562,6 +714,7 @@ translations! {
player_failed: "Failed" , "Ошибка";
player_paused: "Paused" , "Пауза";
player_no_torrent_selected: "No torrent selected" , "Торрент не выбран";
player_no_torrent_files: "No files available" , "Нет доступных файлов";
player_downloaded: "Downloaded" , "Загружено";
player_speed: "Speed" , "Скорость";
player_down: "down" , "вниз";
@@ -571,8 +724,9 @@ translations! {
player_seen: "seen" , "видели";
player_eta: "eta" , "осталось";
player_loading_history: "Loading history..." , "Загрузка истории...";
player_loading_release: "Loading release…" , "Загрузка релиза…";
player_loading_content: "Loading…" , "Загрузка…";
player_release_unavailable: "Release unavailable" , "Релиз недоступен";
player_artist_unavailable: "Artist unavailable" , "Исполнитель недоступен";
player_federated_result: "Available from the federation" , "Доступно в федерации";
player_loading_more: "Loading more..." , "Загружаю ещё...";
player_failed_load_history: "Failed to load history" , "Не удалось загрузить историю";
@@ -605,4 +759,143 @@ translations! {
player_open_torrent_failed: "Could not open torrent" , "Не удалось открыть торрент";
player_delete_torrent_failed: "Could not remove torrent from history" , "Не удалось удалить торрент из истории";
player_load_ai_queue_failed: "Could not load AI queue" , "Не удалось загрузить очередь ИИ";
// Library import
player_import_library: "Import library" , "Импорт библиотеки";
player_import_new: "New import" , "Новый импорт";
player_import_sources: "Sources" , "Источники";
player_import_history: "History" , "История";
player_import_history_empty: "No imports yet. Start with New import." , "Импортов пока нет. Начните с кнопки «Новый импорт».";
player_import_load_failed: "Could not load imports." , "Не удалось загрузить импорты.";
player_import_request_failed: "The request failed. Try again." , "Запрос не выполнен. Попробуйте ещё раз.";
player_import_retry: "Retry" , "Повторить";
player_import_method_file: "Data export" , "Выгрузка данных";
player_import_method_file_hint: "ZIP archive from Download your data, or its playlist JSON files" , "ZIP-архив из «Скачать данные» или JSON-файлы плейлистов из него";
player_import_method_api: "Sign in with Spotify" , "Войти через Spotify";
player_import_method_api_hint: "Reads your own and collaborative playlists directly" , "Читает ваши и совместные плейлисты напрямую";
player_import_upload_help: "In Spotify, open Account, then Privacy settings, and request Account data. When the email arrives, choose the downloaded ZIP archive, or its Playlist1.json, Playlist2.json and YourLibrary.json files." , "В Spotify откройте «Аккаунт», затем «Настройки конфиденциальности» и запросите данные аккаунта. Когда придёт письмо, выберите скачанный ZIP-архив или файлы Playlist1.json, Playlist2.json и YourLibrary.json из него.";
player_import_privacy: "The archive is opened in your browser. Only playlists and saved tracks are sent to the server; listening history stays on this device." , "Архив открывается в браузере. На сервер уходят только плейлисты и сохранённые треки; история прослушиваний остаётся на этом устройстве.";
player_import_api_help: "Spotify asks you to allow read access to your playlists and saved tracks. In Development Mode only your own and collaborative playlists can be read; import other playlists from the data export." , "Spotify попросит разрешить чтение плейлистов и сохранённых треков. В режиме разработки читаются только ваши и совместные плейлисты; остальные импортируйте из выгрузки данных.";
player_import_choose_files: "Choose files" , "Выбрать файлы";
player_import_reading: "Reading the export…" , "Читаю выгрузку…";
player_import_files_read: "Files read: {count}." , "Прочитано файлов: {count}.";
player_import_files_skipped: "Other files were skipped: {count}." , "Другие файлы пропущены: {count}.";
player_import_no_files: "No playlist files found. Choose the export archive or its Playlist*.json and YourLibrary.json files." , "Файлы плейлистов не найдены. Выберите архив выгрузки или файлы Playlist*.json и YourLibrary.json.";
player_import_archive_too_large: "The archive is larger than 256 MB. Choose the account data export." , "Архив больше 256 МБ. Выберите выгрузку данных аккаунта.";
player_import_zip_too_many_entries: "The archive contains too many files." , "В архиве слишком много файлов.";
player_import_zip_too_many_files: "The export contains more than 256 playlist files." , "В выгрузке больше 256 файлов плейлистов.";
player_import_export_too_large: "The playlist files are larger than 32 MB in total." , "Файлы плейлистов в сумме больше 32 МБ.";
player_import_zip_invalid: "The file is not a valid ZIP archive." , "Файл не является корректным ZIP-архивом.";
player_import_zip_load_failed: "Could not load the archive reader. Check the connection and try again." , "Не удалось загрузить модуль чтения архивов. Проверьте соединение и попробуйте ещё раз.";
player_import_request_too_large: "The export is too large to send (32 MB at most)." , "Выгрузка слишком большая для отправки (не больше 32 МБ).";
player_import_sign_in: "Sign in with Spotify" , "Войти через Spotify";
player_import_sign_in_again: "Sign in to Spotify again" , "Войти в Spotify снова";
player_import_loading_playlists: "Loading playlists…" , "Загружаю плейлисты…";
player_import_select_playlists: "Playlists to import" , "Плейлисты для импорта";
player_import_select_all: "Select all" , "Выбрать все";
player_import_select_none: "Clear" , "Снять выбор";
player_import_selected_count: "Selected {count} of {total}" , "Выбрано {count} из {total}";
player_import_favorites: "Liked Songs" , "Любимые треки";
player_import_unsupported_count: "not supported: {count}" , "не поддерживается: {count}";
player_import_already_imported: "Already imported in #{id}" , "Уже импортирован в №{id}";
player_import_all_imported: "This export was already imported." , "Эта выгрузка уже импортирована.";
player_import_similar: "A similar playlist was imported in #{id}. A new playlist will be created." , "Похожий плейлист уже импортирован в №{id}. Будет создан новый плейлист.";
player_import_confirm_similar: "Create a new playlist" , "Создать новый плейлист";
player_import_confirm_similar_needed: "Confirm creating new playlists for the similar ones, or clear them." , "Подтвердите создание новых плейлистов для похожих или снимите их выбор.";
player_import_unavailable: "Only through the data export" , "Только через выгрузку данных";
player_import_federated: "Search in the federation" , "Искать в федерации";
player_import_federated_consent: "Tracks missing here are searched for in the catalogues of Furumi network participants. Participants receive only artist names." , "Недостающие треки ищутся в каталогах участников сети Furumi. Участникам сети будут отправлены только имена исполнителей.";
player_import_federated_off: "Federation is turned off on this server." , "Федерация на этом сервере выключена.";
player_import_start: "Start import" , "Начать";
player_import_starting: "Starting the import…" , "Запускаю импорт…";
player_import_back: "Back" , "Назад";
player_import_conflicts: "Some playlists were imported meanwhile and are no longer selected." , "Некоторые плейлисты уже импортированы, их выбор снят.";
player_import_similar_conflicts: "Similar playlists were imported before. Confirm creating new playlists for them." , "Похожие плейлисты уже импортированы. Подтвердите создание новых плейлистов.";
player_import_status_queued: "Queued" , "В очереди";
player_import_status_running: "Running" , "Выполняется";
player_import_status_done: "Done" , "Готово";
player_import_status_cancelled: "Cancelled" , "Отменён";
player_import_status_failed: "Failed" , "Ошибка";
player_import_status_needs_reauth: "Sign-in needed" , "Нужен вход";
player_import_status_cancelling: "Cancelling" , "Отменяется";
player_import_phase_fetching: "Reading playlists from Spotify" , "Чтение плейлистов из Spotify";
player_import_phase_resolve_local: "Matching with the library" , "Поиск в библиотеке";
player_import_phase_resolve_federation: "Searching the federation" , "Поиск в федерации";
player_import_phase_publish: "Adding tracks to playlists" , "Добавление треков в плейлисты";
player_import_phase_waiting: "Waiting to start" , "Ожидает запуска";
player_import_found_of: "{found} of {total} found" , "Найдено {found} из {total}";
player_import_number: "#{id}" , "№{id}";
player_import_playlists_more: "and {count} more" , "и ещё {count}";
player_import_retry_unmatched: "Retry unmatched" , "Искать ненайденные";
player_import_retry_started: "Unmatched tracks will be searched again." , "Поиск ненайденных треков запущен заново.";
player_import_cancel: "Cancel" , "Отменить";
player_import_cancel_requested: "The import stops after the current step. Added tracks stay." , "Импорт остановится после текущего шага. Добавленные треки останутся.";
player_import_delete_history: "Delete history" , "Удалить историю";
player_import_delete_confirm: "Delete this import history? Created playlists stay." , "Удалить историю этого импорта? Созданные плейлисты останутся.";
player_import_deleted: "Import history deleted. Playlists stay." , "История импорта удалена. Плейлисты остались.";
player_import_reauth_needed: "The Spotify sign-in has expired. Sign in again to continue this import." , "Вход в Spotify истёк. Войдите снова, чтобы продолжить этот импорт.";
player_import_stat_total: "Entries" , "Записей";
player_import_stat_found: "Found" , "Найдено";
player_import_stat_published: "Added to playlists" , "Добавлено в плейлисты";
player_import_stat_ambiguous: "Needs a choice" , "Нужен выбор";
player_import_stat_unmatched: "Not found" , "Не найдено";
player_import_stat_unsupported: "Not supported" , "Не поддерживается";
player_import_stat_failed: "Errors" , "Ошибки";
player_import_stat_deferred: "Deferred by the sync limit" , "Отложено из-за лимита синхронизации";
player_import_stat_duplicate: "Repeats" , "Повторы";
player_import_stat_already_present: "Already in the playlist or removed" , "Уже в плейлисте или удалены";
player_import_stat_paused: "Paused" , "Приостановлено";
player_import_stat_no_content: "No content id" , "Без идентификатора содержимого";
player_import_stat_publish_failed: "Not added" , "Не добавлено";
player_import_playlists: "Playlists" , "Плейлисты";
player_import_playlist_deleted: "The playlist was deleted" , "Плейлист удалён";
player_import_playlist_pending: "Not created yet" , "Ещё не создан";
player_import_recreate: "Create again" , "Создать заново";
player_import_recreate_started: "The playlist will be created again." , "Плейлист будет создан заново.";
player_import_entries: "Entries" , "Записи";
player_import_filter_all: "All" , "Все";
player_import_all_playlists: "All playlists" , "Все плейлисты";
player_import_search: "Search entries" , "Поиск по записям";
player_import_no_entries: "No entries to show." , "Записей нет.";
player_import_load_more: "Load more" , "Загрузить ещё";
player_import_loading: "Loading…" , "Загрузка…";
player_import_candidates: "Possible matches" , "Возможные совпадения";
player_import_choose: "Choose" , "Выбрать";
player_import_chosen: "The track will be added to the playlist." , "Трек будет добавлен в плейлист.";
player_import_origin_local: "Library" , "Библиотека";
player_import_origin_federation: "Federation" , "Федерация";
player_import_res_pending: "Waiting" , "Ожидает";
player_import_res_matched: "Found" , "Найден";
player_import_res_ambiguous: "Needs a choice" , "Нужен выбор";
player_import_res_unmatched: "Not found" , "Не найден";
player_import_res_unsupported: "Not supported" , "Не поддерживается";
player_import_res_failed: "Error" , "Ошибка";
player_import_pub_pending: "Waiting to be added" , "Ожидает добавления";
player_import_pub_published: "Added" , "Добавлен";
player_import_pub_duplicate: "Repeat in the source" , "Повтор в источнике";
player_import_pub_already_present: "Already in the playlist or removed" , "Уже в плейлисте или удалён";
player_import_pub_no_content_id: "No content id" , "Нет идентификатора содержимого";
player_import_pub_deferred: "Deferred by the sync limit" , "Отложен из-за лимита синхронизации";
player_import_pub_paused: "Playlist deleted" , "Плейлист удалён";
player_import_pub_failed: "Not added" , "Не добавлен";
player_import_note_not_found: "No such track" , "Такого трека нет";
player_import_note_version_mismatch: "Only other versions" , "Есть только другие версии";
player_import_note_duration_mismatch: "Duration differs" , "Длительность отличается";
player_import_note_federation_error: "Federation search failed" , "Поиск в федерации не удался";
player_import_note_federation_budget: "Federation search limit reached" , "Исчерпан лимит поиска в федерации";
player_import_note_federation_unavailable: "Federation unavailable" , "Федерация недоступна";
player_import_note_episode: "Podcast episode" , "Выпуск подкаста";
player_import_note_audiobook: "Audiobook" , "Аудиокнига";
player_import_note_local_file: "Local file" , "Локальный файл";
player_import_note_unknown_kind: "Unknown item" , "Неизвестная запись";
player_import_note_missing_title: "No title" , "Нет названия";
player_import_note_failed: "Processing error" , "Ошибка обработки";
player_import_oauth_state: "The sign-in could not be verified. Try again." , "Не удалось проверить вход. Попробуйте ещё раз.";
player_import_oauth_expired: "The sign-in took too long. Try again." , "Вход занял слишком много времени. Попробуйте ещё раз.";
player_import_oauth_denied: "Access was not granted." , "Доступ не предоставлен.";
player_import_oauth_not_configured: "Spotify sign-in is not configured on this server." , "Вход через Spotify на этом сервере не настроен.";
player_import_oauth_exchange: "Spotify did not confirm the sign-in. Try again." , "Spotify не подтвердил вход. Попробуйте ещё раз.";
player_import_oauth_not_allowed: "This Spotify account is not on the application user list. Ask the administrator, or use the data export." , "Этого аккаунта Spotify нет в списке пользователей приложения. Обратитесь к администратору или используйте выгрузку данных.";
player_import_oauth_unavailable: "Spotify is unavailable. Try again later." , "Spotify недоступен. Попробуйте позже.";
player_import_oauth_not_waiting: "This import is not waiting for a sign-in." , "Этот импорт не ожидает входа.";
player_import_oauth_account_mismatch: "Sign in with the Spotify account used for this import." , "Войдите в тот аккаунт Spotify, из которого делался этот импорт.";
}
+23 -11
View File
@@ -86,7 +86,8 @@ pub async fn reconcile(pool: &PgPool, user_id: Option<i64>) -> anyhow::Result<()
}
let mut added = Vec::new();
for track_id in track_ids {
if append_in_transaction(&mut transaction, user_id, playlist_id, track_id).await? {
if append_in_transaction(&mut transaction, user_id, playlist_id, track_id, None).await?
{
added.push(track_id);
}
}
@@ -109,7 +110,8 @@ pub(crate) async fn append_track_to_target_playlist(
track_id: i64,
) -> anyhow::Result<bool> {
let mut transaction = pool.begin().await?;
let added = append_in_transaction(&mut transaction, user_id, playlist_id, track_id).await?;
let added =
append_in_transaction(&mut transaction, user_id, playlist_id, track_id, None).await?;
transaction.commit().await?;
if added {
record_added(pool, user_id, playlist_id, &[track_id]).await;
@@ -117,11 +119,16 @@ pub(crate) async fn append_track_to_target_playlist(
Ok(added)
}
async fn append_in_transaction(
/// Appends a track the playlist does not contain yet, under the playlist's
/// row lock. `position` places it explicitly; `None` appends after the last
/// track. Returns `false` when the playlist is gone or not the user's, or
/// already contains the track.
pub(crate) async fn append_in_transaction(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
user_id: i64,
playlist_id: i64,
track_id: i64,
position: Option<i32>,
) -> anyhow::Result<bool> {
let playlist: Option<i64> = sqlx::query_scalar(
r#"SELECT id FROM furumusic__playlist
@@ -150,14 +157,19 @@ async fn append_in_transaction(
return Ok(false);
}
let position: i64 = sqlx::query_scalar(
r#"SELECT COALESCE(MAX(position), -1)::bigint + 1
FROM furumusic__playlist_track WHERE playlist_id = $1"#,
)
.bind(playlist_id)
.fetch_one(&mut **transaction)
.await?;
let position = i32::try_from(position).context("target playlist has too many tracks")?;
let position = match position {
Some(position) => position,
None => {
let position: i64 = sqlx::query_scalar(
r#"SELECT COALESCE(MAX(position), -1)::bigint + 1
FROM furumusic__playlist_track WHERE playlist_id = $1"#,
)
.bind(playlist_id)
.fetch_one(&mut **transaction)
.await?;
i32::try_from(position).context("target playlist has too many tracks")?
}
};
let now = now_string();
sqlx::query(
r#"INSERT INTO furumusic__playlist_track
+169 -93
View File
@@ -1,7 +1,12 @@
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{LazyLock, Mutex};
use sha2::{Digest, Sha256};
use super::inbox_review::{
finish_exact_review, reconcile_open_reviews, same_file_version, tracked_files,
};
pub use super::inbox_review::{link_exact_import, remove_exact_inbox_copy};
use crate::scheduler::{Job, JobContext, JobLog, PendingReview};
@@ -85,6 +90,7 @@ impl Job for InboxDiscoverJob {
return Ok(());
}
reconcile_open_reviews(&ctx.pool, config, log).await?;
let inbox = Path::new(&config.agent_inbox_dir);
if !inbox.exists() {
log.warn(&format!("Inbox path does not exist: {}", inbox.display()));
@@ -100,9 +106,32 @@ impl Job for InboxDiscoverJob {
log.info(&format!("Found {} audio files in inbox", audio_files.len()));
if audio_files.is_empty() {
INBOX_HASHES.lock().unwrap().clear();
return Ok(());
}
let relative_paths: Vec<_> = audio_files
.iter()
.filter_map(|path| crate::media_paths::path_for_root(&config.agent_inbox_dir, path))
.collect();
let tracked: HashMap<_, _> = tracked_files(&ctx.pool, &relative_paths)
.await?
.into_iter()
.map(|r| (r.input_path.clone(), r))
.collect();
let dismissed: HashSet<(String, String)> = sqlx::query_as(
"SELECT input_path, sha256 FROM furumusic__dismissed_review WHERE input_path = ANY($1)",
)
.bind(&relative_paths)
.fetch_all(&ctx.pool)
.await?
.into_iter()
.collect();
let present: HashSet<&PathBuf> = audio_files.iter().collect();
INBOX_HASHES
.lock()
.unwrap()
.retain(|path, _| present.contains(path));
let groups = group_by_folder(&audio_files);
log.info(&format!("Grouped into {} folder batches", groups.len()));
@@ -117,106 +146,102 @@ impl Job for InboxDiscoverJob {
crate::media_paths::path_for_root(&config.agent_inbox_dir, file_path)
.unwrap_or_else(|| file_path.to_string_lossy().to_string());
// One review row per path: any existing row blocks creating a
// new one. A stale "failed" row is requeued in place instead,
// so retries don't multiply rows. "rejected" stays rejected.
match PendingReview::latest_for_path(&ctx.pool, &input_path_str).await {
Ok(None) => {}
Ok(Some((id, status, updated_at))) => {
if status == "failed" {
let stale = chrono::DateTime::parse_from_rfc3339(&updated_at)
.map(|t| {
chrono::Utc::now().signed_duration_since(t).num_seconds()
>= FAILED_RETRY_COOLDOWN_SECS
})
.unwrap_or(true);
if stale {
match PendingReview::requeue_by_ids(&ctx.db, &[id]).await {
Ok(()) => requeued += 1,
Err(e) => log.warn(&format!(
"Failed to requeue review {id} for {input_path_str}: {e}"
)),
}
} else {
skipped_existing += 1;
}
} else {
skipped_existing += 1;
}
continue;
}
Err(e) => {
let existing = tracked.get(&input_path_str);
if existing.is_some_and(|r| r.status == "processing") {
skipped_existing += 1;
continue;
}
let (hash, file_size) = match observed_inbox_hash(file_path).await {
Ok(value) => value,
Err(error) => {
log.warn(&format!(
"Error checking existing review for {}: {e}",
input_path_str
"Could not inspect {}: {error}",
file_path.display()
));
continue;
}
};
if dismissed.contains(&(input_path_str.clone(), hash.clone())) {
skipped_existing += 1;
continue;
}
let same = existing.filter(|r| r.sha256.as_deref() == Some(hash.as_str()));
if let Some(review) = same
&& !matches!(review.status.as_str(), "approved" | "auto_approved")
{
if review.status == "failed" {
let stale = chrono::DateTime::parse_from_rfc3339(&review.updated_at)
.map(|t| {
chrono::Utc::now().signed_duration_since(t).num_seconds()
>= FAILED_RETRY_COOLDOWN_SECS
})
.unwrap_or(true);
if stale {
requeued += sqlx::query("UPDATE furumusic__pending_review SET status='queued',
error_message=NULL, updated_at=$3 WHERE id=$1 AND status='failed'
AND updated_at=$2 AND strpos(COALESCE(error_message,''), 'Duplicate check needs review: ') = 0")
.bind(review.id).bind(&review.updated_at)
.bind(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
.execute(&ctx.pool).await?.rows_affected();
}
}
skipped_existing += 1;
continue;
}
// Compute SHA-256 hash
let path_clone = file_path.to_path_buf();
let hash_start = std::time::Instant::now();
let (hash, file_size) =
match tokio::task::spawn_blocking(move || -> anyhow::Result<(String, i64)> {
let data = std::fs::read(&path_clone)?;
let digest = Sha256::digest(&data);
let hash = format!("{:x}", digest);
let size = data.len() as i64;
Ok((hash, size))
})
.await?
{
Ok(v) => {
crate::metrics::record_agent_file_hash(hash_start.elapsed(), v.1, "ok");
v
}
Err(e) => {
crate::metrics::record_agent_file_hash(
hash_start.elapsed(),
0,
"error",
);
log.warn(&format!("Failed to hash {}: {e}", file_path.display()));
continue;
}
};
// Skip if hash already in media_files
if crate::agent::rag::file_hash_exists_verified(
let exact = match crate::agent::rag::verified_audio_media(
&ctx.pool,
&hash,
&config.agent_storage_dir,
)
.await
.unwrap_or(false)
{
// Close the upload by removing the exact inbox duplicate;
// otherwise its history remains queued forever.
tokio::fs::remove_file(file_path).await?;
skipped_hash += 1;
Ok(media) => media,
Err(error) => {
log.warn(&format!(
"Could not verify catalog audio for {input_path_str}: {error}"
));
continue;
}
};
if let (Some(review), Some(media)) = (same, exact) {
match finish_exact_review(&ctx.pool, config, review, &hash, media).await {
Ok(true) => skipped_hash += 1,
Ok(false) => skipped_existing += 1,
Err(error) => log.warn(&format!(
"Could not reconcile review {}: {error:#}",
review.id
)),
}
continue;
}
// Extract raw metadata
let path_for_meta = file_path.to_path_buf();
let metadata_start = std::time::Instant::now();
let raw_meta = match tokio::task::spawn_blocking(move || {
crate::agent::metadata::extract(&path_for_meta)
})
.await?
{
Ok(m) => {
crate::metrics::record_agent_metadata(metadata_start.elapsed(), "ok");
m
}
Err(e) => {
crate::metrics::record_agent_metadata(metadata_start.elapsed(), "error");
log.warn(&format!(
"Failed to extract metadata from {}: {e}",
file_path.display()
));
continue;
let raw_meta = if exact.is_some() {
Default::default()
} else {
match tokio::task::spawn_blocking(move || {
crate::agent::metadata::extract(&path_for_meta)
})
.await?
{
Ok(m) => {
crate::metrics::record_agent_metadata(metadata_start.elapsed(), "ok");
m
}
Err(e) => {
crate::metrics::record_agent_metadata(
metadata_start.elapsed(),
"error",
);
log.warn(&format!(
"Failed to extract metadata from {}: {e}",
file_path.display()
));
continue;
}
}
};
@@ -250,18 +275,37 @@ impl Job for InboxDiscoverJob {
});
let context_str = serde_json::to_string(&context).unwrap_or_default();
// Create PendingReview with status "queued"
PendingReview::create_queued(
&ctx.db,
if PendingReview::enqueue_discovered(
&ctx.pool,
ctx.run_id,
"new_file",
Some(&input_path_str),
Some(&context_str),
&input_path_str,
&hash,
&context_str,
)
.await
.map_err(|e| anyhow::anyhow!("failed to create queued review: {e}"))?;
discovered += 1;
.await?
{
if let Some(media) = exact
&& let Some(review) =
tracked_files(&ctx.pool, std::slice::from_ref(&input_path_str))
.await?
.pop()
&& review.status == "queued"
&& review.sha256.as_deref() == Some(hash.as_str())
{
match finish_exact_review(&ctx.pool, config, &review, &hash, media).await {
Ok(true) => {
skipped_hash += 1;
continue;
}
Ok(false) => {}
Err(error) => log.warn(&format!(
"Could not reconcile review {}: {error:#}",
review.id
)),
}
}
discovered += 1;
}
}
}
@@ -314,6 +358,38 @@ impl Job for InboxDiscoverJob {
// Helpers (moved from inbox_scan.rs)
// ---------------------------------------------------------------------------
// Inbox files awaiting a human decision can be large. Rehash them only when
// their filesystem identity or timestamps change. Destructive operations
// always hash the live source again.
static INBOX_HASHES: LazyLock<Mutex<HashMap<PathBuf, (std::fs::Metadata, String)>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
async fn observed_inbox_hash(path: &Path) -> anyhow::Result<(String, i64)> {
let before = tokio::fs::metadata(path).await?;
{
let hashes = INBOX_HASHES.lock().unwrap();
if let Some((version, sha256)) = hashes.get(path)
&& same_file_version(version, &before)
{
return Ok((sha256.clone(), i64::try_from(before.len())?));
}
}
let start = std::time::Instant::now();
let sha256 = crate::agent::mover::sha256_file(path).await?;
let after = tokio::fs::metadata(path).await?;
anyhow::ensure!(
same_file_version(&before, &after),
"file changed during discovery"
);
let size = i64::try_from(after.len())?;
INBOX_HASHES
.lock()
.unwrap()
.insert(path.to_owned(), (after, sha256.clone()));
crate::metrics::record_agent_file_hash(start.elapsed(), size, "ok");
Ok((sha256, size))
}
pub fn group_by_folder(files: &[PathBuf]) -> Vec<(PathBuf, Vec<PathBuf>)> {
use std::collections::HashMap;
let mut map: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
+203 -109
View File
@@ -366,6 +366,18 @@ async fn process_folder_batch(
let mut merged_count = 0u64;
for mut review in reviews {
match review.claim_for_processing(pool, None).await {
Ok(true) => {}
Ok(false) => continue,
Err(error) => {
log.error(&format!(
"Failed to claim review {}: {error}",
review.id_val()
));
failed_reviews.push(review);
continue;
}
}
let stored_input_path = review.input_path_str().to_owned();
let file_path =
crate::media_paths::resolve_path_from_root(&config.agent_inbox_dir, &stored_input_path);
@@ -382,41 +394,24 @@ async fn process_folder_batch(
.and_then(|s| serde_json::from_str(s).ok())
.unwrap_or_default();
// Resolve duplicates and missing sources before any expensive work.
let sha = context
.get("sha256")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let file_exists = file_path.exists();
if !sha.is_empty()
&& crate::agent::rag::file_hash_exists_verified(pool, &sha, &config.agent_storage_dir)
.await
.unwrap_or(false)
{
// Identical content is already in the library — drop the inbox
// copy (same as mover::Merged) and close the review.
if file_exists {
let _ = tokio::fs::remove_file(&file_path).await;
match verify_queued_input(db, pool, config, &mut review, &mut context, &file_path).await {
Ok(true) => {
log.info(&format!(
"{filename}: exact audio already present in the library"
));
crate::metrics::record_agent_file_processed("ok", "merged_duplicate");
merged_count += 1;
continue;
}
Ok(false) => {}
Err(error) => {
let message = format!("{filename}: {error:#}");
log.error(&message);
let _ = review.set_failed(db, &message).await;
failed_reviews.push(review);
continue;
}
let _ = PendingReview::delete_by_ids(db, &[review.id_val()]).await;
log.info(&format!(
"{filename}: content already in library (sha256 match) — merged duplicate"
));
crate::metrics::record_agent_file_processed("ok", "merged_duplicate");
merged_count += 1;
continue;
}
if !file_exists {
let msg = format!("{filename}: source file missing: {stored_input_path}");
log.error(&msg);
let _ = review.set_failed(db, &msg).await;
failed_reviews.push(review);
continue;
}
// Set status → processing
let _ = review.set_processing(db).await;
// Extract metadata (with 60s timeout)
let path_for_meta = file_path.to_path_buf();
@@ -791,22 +786,15 @@ async fn process_folder_batch(
p.review.result_json = Some(result_json);
let _ = p.review.save(db).await;
let input_path = crate::media_paths::resolve_path_from_root(
&config.agent_inbox_dir,
p.review.input_path_str(),
);
let input_path_str = input_path.to_string_lossy().to_string();
if confidence >= config.agent_confidence_threshold {
match finalize_approved(
db,
pool,
config,
&input_path_str,
p.review.input_path_str(),
normalized,
&p.context,
&config.agent_storage_dir,
Some(llm_model),
ReviewApproval::Check(Some(llm_model)),
)
.await
{
@@ -877,20 +865,87 @@ async fn process_folder_batch(
(ok_count, fail_count)
}
/// Return true after satisfying the review with physically verified library audio.
/// Otherwise retain the source and ensure the queued metadata still belongs to it.
async fn verify_queued_input(
db: &Database,
pool: &sqlx::PgPool,
config: &AppConfig,
review: &mut PendingReview,
context: &mut serde_json::Value,
source: &Path,
) -> anyhow::Result<bool> {
let mut sha = context["sha256"].as_str().unwrap_or("").to_owned();
let mut observed = None;
if sha.is_empty() {
// Legacy reviews predate content identities. Establish one from this
// input before publishing a media row or recording a deduplication.
let metadata = tokio::fs::metadata(source).await?;
sha = mover::sha256_file(source).await?;
context["sha256"] = serde_json::json!(sha);
context["file_size"] = serde_json::json!(metadata.len());
review.context_json = Some(context.to_string());
review.save(db).await?;
observed = Some(sha.clone());
}
if let Some(media) =
crate::agent::rag::verified_audio_media(pool, &sha, &config.agent_storage_dir).await?
{
let tracked = super::inbox_review::ReviewFile {
id: review.id_val(),
input_path: review.input_path_str().to_owned(),
sha256: Some(sha.clone()),
status: review.status_str().to_owned(),
updated_at: review.updated_at.to_string(),
};
anyhow::ensure!(
super::inbox_review::finish_exact_review(pool, config, &tracked, &sha, media).await?,
"the review changed while verifying its library audio"
);
return Ok(true);
}
let actual = match observed {
Some(sha) => sha,
None => mover::sha256_file(source).await.map_err(|error| {
error.context(format!("could not read source {}", source.display()))
})?,
};
anyhow::ensure!(
actual == sha,
"source content changed since discovery: {}",
source.display()
);
Ok(false)
}
// ---------------------------------------------------------------------------
// Finalization (called on approve or auto-approve)
// ---------------------------------------------------------------------------
pub enum ReviewApproval<'a> {
Check(Option<&'a str>),
Separate(Option<&'a str>),
}
pub async fn finalize_approved(
db: &cot::db::Database,
pool: &sqlx::PgPool,
_config: &crate::config::AppConfig,
input_path_str: &str,
config: &AppConfig,
review_input_path: &str,
normalized: &NormalizedFields,
context: &serde_json::Value,
storage_dir_str: &str,
model_name: Option<&str>,
approval: ReviewApproval<'_>,
) -> anyhow::Result<()> {
let model_name = match approval {
ReviewApproval::Check(model) | ReviewApproval::Separate(model) => model,
};
anyhow::ensure!(
!review_input_path.trim().is_empty(),
"review has no input path"
);
let source_path =
crate::media_paths::resolve_path_from_root(&config.agent_inbox_dir, review_input_path);
let storage_dir_str = config.agent_storage_dir.as_str();
let artist_name = normalized.artist.as_deref().unwrap_or("Unknown Artist");
let release_title = normalized.album.as_deref().unwrap_or("Unknown Release");
let track_title = normalized.title.as_deref().unwrap_or("Unknown Title");
@@ -922,10 +977,80 @@ pub async fn finalize_approved(
.execute(&mut *import_lock)
.await?;
}
if crate::agent::dedup::merge_existing(
let sha256 = context.get("sha256").and_then(|v| v.as_str()).unwrap_or("");
let original_filename = source_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
let ext = source_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("flac");
let track_num = track_number.unwrap_or(0);
let dest_filename = if track_num > 0 {
format!(
"{:02} - {}.{}",
track_num,
sanitize_filename(track_title),
ext
)
} else {
format!("{}.{}", sanitize_filename(track_title), ext)
};
let storage_dir = crate::media_paths::resolve_config_path_buf(storage_dir_str);
let source_exists = tokio::fs::try_exists(&source_path).await?;
if source_exists && !sha256.is_empty() {
anyhow::ensure!(
mover::sha256_file(&source_path).await? == sha256,
"the file at {} has changed since discovery",
source_path.display()
);
}
if !sha256.is_empty()
&& let Some(media_id) =
crate::agent::rag::verified_audio_media(pool, sha256, storage_dir_str).await?
{
crate::jobs::inbox_discover::link_exact_import(pool, review_input_path, sha256, media_id)
.await?;
if source_exists {
crate::jobs::inbox_discover::remove_exact_inbox_copy(config, &source_path, sha256)
.await?;
}
import_lock.commit().await?;
return Ok(());
}
let moved_path = if source_exists {
None
} else {
// A previous approval may have finished or moved the bytes before a
// catalog write failed. Only accept content verified against the review.
let path = mover::find_moved_file(
&storage_dir,
artist_name,
release_title,
&dest_filename,
sha256,
)
.await?
.ok_or_else(|| {
anyhow::anyhow!(
"source file missing: {}; no matching audio found in storage",
source_path.display()
)
})?;
// Deduplication may remove or upgrade its input. Give it an inbox
// copy, keeping the already-published library file intact.
mover::publish_copy(&path, &source_path).await?;
Some(path)
};
if matches!(approval, ReviewApproval::Separate(_)) {
crate::agent::dedup::verify_separate_recording(&source_path).await?;
} else if crate::agent::dedup::merge_existing(
pool,
storage_dir_str,
Path::new(input_path_str),
&source_path,
normalized,
context,
)
@@ -967,7 +1092,33 @@ pub async fn finalize_approved(
.map_err(|e| anyhow::anyhow!("failed to link release-artist: {e}"))?;
}
let sha256 = context.get("sha256").and_then(|v| v.as_str()).unwrap_or("");
let destination = match moved_path {
Some(path) => {
tokio::fs::remove_file(&source_path).await?;
path
}
None => match mover::move_to_storage(
&storage_dir,
artist_name,
release_title,
&dest_filename,
&source_path,
)
.await?
{
mover::MoveOutcome::Moved(path) | mover::MoveOutcome::Merged(path) => path,
},
};
let storage_path =
crate::media_paths::media_file_path_for_storage(storage_dir_str, &destination).ok_or_else(
|| {
anyhow::anyhow!(
"storage destination is outside agent_storage_dir: {}",
destination.display()
)
},
)?;
let file_size = context
.get("file_size")
.and_then(|v| v.as_i64())
@@ -995,16 +1146,6 @@ pub async fn finalize_approved(
.filter(|value| !value.trim().is_empty())
.unwrap_or("UFO");
let source_path = Path::new(input_path_str);
let original_filename = source_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
let ext = source_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("flac");
let mime_type = match ext.to_lowercase().as_str() {
"mp3" => "audio/mpeg",
"flac" => "audio/flac",
@@ -1015,54 +1156,6 @@ pub async fn finalize_approved(
_ => "application/octet-stream",
};
let track_num = track_number.unwrap_or(0);
let dest_filename = if track_num > 0 {
format!(
"{:02} - {}.{}",
track_num,
sanitize_filename(track_title),
ext
)
} else {
format!("{}.{}", sanitize_filename(track_title), ext)
};
let storage_dir = crate::media_paths::resolve_config_path_buf(storage_dir_str);
let storage_path = if source_path.exists() {
match mover::move_to_storage(
&storage_dir,
artist_name,
release_title,
&dest_filename,
source_path,
)
.await?
{
mover::MoveOutcome::Moved(p) | mover::MoveOutcome::Merged(p) => {
crate::media_paths::media_file_path_for_storage(storage_dir_str, &p).ok_or_else(
|| {
anyhow::anyhow!(
"storage destination is outside agent_storage_dir: {}",
p.display()
)
},
)?
}
}
} else {
let expected_path = storage_dir
.join(sanitize_filename(artist_name))
.join(sanitize_filename(release_title))
.join(&dest_filename);
crate::media_paths::media_file_path_for_storage(storage_dir_str, &expected_path)
.ok_or_else(|| {
anyhow::anyhow!(
"storage destination is outside agent_storage_dir: {}",
expected_path.display()
)
})?
};
let reusable_media_id: Option<i64> = sqlx::query_scalar(
r#"SELECT media.id
FROM furumusic__media_file media
@@ -1198,7 +1291,7 @@ pub async fn finalize_approved(
// Cover art: if the release has no cover yet, try to find one
if release.cover_file_id.is_none() {
let source_folder = Path::new(input_path_str).parent().unwrap_or(Path::new("."));
let source_folder = source_path.parent().unwrap_or(Path::new("."));
// Collect audio files in the same folder to try embedded extraction
let audio_files_in_folder: Vec<std::path::PathBuf> = std::fs::read_dir(source_folder)
@@ -1271,7 +1364,8 @@ pub async fn finalize_approved(
}
}
if let Err(error) = crate::import_playlists::link_media(pool, sha256, media_file.id_val()).await {
if let Err(error) = crate::import_playlists::link_media(pool, sha256, media_file.id_val()).await
{
tracing::warn!(%error, "could not add imported tracks to destination playlists; will retry");
}
+197
View File
@@ -0,0 +1,197 @@
use std::path::Path;
use sqlx::PgPool;
use crate::agent::{mover, rag};
use crate::config::AppConfig;
use crate::scheduler::JobLog;
/// Record the existing audio as the outcome of this upload before closing its review.
pub async fn link_exact_import(
pool: &PgPool,
input_path: &str,
sha256: &str,
media_id: i64,
) -> anyhow::Result<()> {
crate::import_playlists::link_media(pool, sha256, media_id).await?;
sqlx::query(
"INSERT INTO furumusic__youtube_import_media (item_id, media_file_id)
SELECT id, $2 FROM furumusic__youtube_download_item
WHERE inbox_path = $1 OR left($1, length(inbox_path) + 1) = inbox_path || '/'
ON CONFLICT (item_id, media_file_id) DO NOTHING",
)
.bind(input_path)
.bind(media_id)
.execute(pool)
.await?;
crate::youtube::sync_target_playlists_for_imported_media(pool, media_id).await
}
/// A legacy review can point outside the current inbox. Only consume an inbox
/// copy that still contains the bytes recorded when the review was created.
pub async fn remove_exact_inbox_copy(
config: &AppConfig,
source: &Path,
sha256: &str,
) -> anyhow::Result<bool> {
if sha256.is_empty() || config.agent_inbox_dir.is_empty() || config.agent_storage_dir.is_empty()
{
return Ok(false);
}
let canonical = match tokio::fs::canonicalize(source).await {
Ok(path) => path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error.into()),
};
let inbox = tokio::fs::canonicalize(&config.agent_inbox_dir).await?;
let library = tokio::fs::canonicalize(&config.agent_storage_dir).await?;
if !canonical.starts_with(inbox) || canonical.starts_with(library) {
return Ok(false);
}
let before = tokio::fs::symlink_metadata(source).await?;
if !before.is_file() || mover::sha256_file(source).await? != sha256 {
return Ok(false);
}
let after = tokio::fs::symlink_metadata(source).await?;
if !same_file_version(&before, &after) {
return Ok(false);
}
tokio::fs::remove_file(source).await?;
Ok(true)
}
pub(super) fn same_file_version(left: &std::fs::Metadata, right: &std::fs::Metadata) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if (left.dev(), left.ino(), left.ctime(), left.ctime_nsec())
!= (right.dev(), right.ino(), right.ctime(), right.ctime_nsec())
{
return false;
}
}
left.len() == right.len()
&& left
.modified()
.is_ok_and(|t| Some(t) == right.modified().ok())
}
#[derive(sqlx::FromRow)]
pub(super) struct ReviewFile {
pub id: i64,
pub input_path: String,
pub sha256: Option<String>,
pub status: String,
pub updated_at: String,
}
pub(super) async fn tracked_files(
pool: &PgPool,
paths: &[String],
) -> anyhow::Result<Vec<ReviewFile>> {
Ok(sqlx::query_as(
r#"SELECT DISTINCT ON (input_path) id, input_path, status::text, updated_at::text,
substring(context_json from '"sha256"[[:space:]]*:[[:space:]]*"([0-9a-fA-F]{64})"') AS sha256
FROM furumusic__pending_review WHERE input_path = ANY($1) ORDER BY input_path, id DESC"#,
).bind(paths).fetch_all(pool).await?)
}
pub(super) async fn finish_exact_review(
pool: &PgPool,
config: &AppConfig,
review: &ReviewFile,
sha256: &str,
media_id: i64,
) -> anyhow::Result<bool> {
let mut tx = pool.begin().await?;
// Serialize against approval, dismissal, or the discovery of different bytes at this path.
let locked: Option<i64> = sqlx::query_scalar(
r#"SELECT r.id FROM furumusic__pending_review r
JOIN furumusic__media_file m ON m.id=$5 AND m.sha256_hash=$4 AND m.file_type='audio'
JOIN furumusic__track t ON t.audio_file_id=m.id
WHERE r.id=$1 AND r.status=$2 AND r.input_path=$3
AND substring(r.context_json from '"sha256"[[:space:]]*:[[:space:]]*"([0-9a-fA-F]{64})"')=$4
AND NOT EXISTS (SELECT 1 FROM furumusic__dismissed_review d
WHERE d.input_path=r.input_path AND d.sha256=lower($4))
ORDER BY t.id LIMIT 1 FOR UPDATE OF r FOR SHARE OF t,m"#,
).bind(review.id).bind(&review.status).bind(&review.input_path).bind(sha256).bind(media_id)
.fetch_optional(&mut *tx).await?;
if locked.is_none() {
return Ok(false);
}
link_exact_import(pool, &review.input_path, sha256, media_id).await?;
if !matches!(review.status.as_str(), "approved" | "auto_approved") {
sqlx::query(
"UPDATE furumusic__pending_review SET status='auto_approved', error_message=NULL,
updated_at=$2 WHERE id=$1",
)
.bind(review.id)
.bind(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
.execute(&mut *tx)
.await?;
}
let source =
crate::media_paths::resolve_path_from_root(&config.agent_inbox_dir, &review.input_path);
if let Err(error) = remove_exact_inbox_copy(config, &source, sha256).await {
tracing::warn!(review_id=review.id, %error, "could not clean up a verified library duplicate");
}
tx.commit().await?;
Ok(true)
}
pub(super) async fn reconcile_open_reviews(
pool: &PgPool,
config: &AppConfig,
log: &mut JobLog,
) -> anyhow::Result<()> {
// Older manual approvals recorded duplicate decisions as retryable failures.
sqlx::query("UPDATE furumusic__pending_review
SET status='pending', updated_at=$1,
error_message=substring(error_message FROM strpos(error_message, 'Duplicate check needs review:'))
WHERE (status='failed' OR (status='pending' AND error_message NOT LIKE 'Duplicate check needs review:%'))
AND strpos(error_message, 'Duplicate check needs review:') > 0")
.bind(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
.execute(pool).await?;
// Narrow the queue in PostgreSQL. Unrelated archive media never needs filesystem I/O.
let matches: Vec<ReviewFile> = sqlx::query_as(
r#"SELECT id, input_path, sha256, status::text, updated_at::text FROM (
SELECT r.*, substring(context_json from '"sha256"[[:space:]]*:[[:space:]]*"([0-9a-fA-F]{64})"') AS sha256
FROM furumusic__pending_review r
WHERE status IN ('queued','failed','pending') AND input_path IS NOT NULL
) review WHERE EXISTS (
SELECT 1 FROM furumusic__media_file m JOIN furumusic__track t ON t.audio_file_id=m.id
WHERE m.file_type='audio' AND m.sha256_hash=review.sha256
) AND NOT EXISTS (SELECT 1 FROM furumusic__dismissed_review d
WHERE d.input_path=review.input_path AND d.sha256=lower(review.sha256))
ORDER BY id"#,
).fetch_all(pool).await?;
let mut completed = 0;
for review in matches {
let Some(sha256) = review.sha256.as_deref() else {
continue;
};
let reconciliation = async {
let Some(media) =
rag::verified_audio_media(pool, sha256, &config.agent_storage_dir).await?
else {
return Ok(false);
};
finish_exact_review(pool, config, &review, sha256, media).await
}
.await;
match reconciliation {
Ok(true) => completed += 1,
Ok(false) => {}
Err(error) => log.warn(&format!(
"Review {}: could not confirm import in the library: {error:#}",
review.id
)),
}
}
if completed > 0 {
log.info(&format!(
"Completed {completed} reviews for audio verified in the library"
));
}
Ok(())
}
+210
View File
@@ -0,0 +1,210 @@
use super::inbox_discover::InboxDiscoverJob;
use crate::agent::dto::NormalizedFields;
use crate::config::AppConfig;
use crate::scheduler::{Job, JobContext, JobLog, JobRegistry, PendingReview};
use cot::App;
use cot::db::Database;
use cot::db::migrations::MigrationEngine;
use serde_json::json;
use sha2::{Digest, Sha256};
use sqlx::PgPool;
use std::fs;
fn tagged_mp3(title: &str) -> anyhow::Result<Vec<u8>> {
let output = std::process::Command::new("ffmpeg")
.args([
"-nostdin",
"-v",
"error",
"-f",
"lavfi",
"-i",
"sine=duration=0.25",
"-metadata",
&format!("title={title}"),
"-f",
"mp3",
"pipe:1",
])
.output()?;
anyhow::ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(output.stdout)
}
fn hash(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
async fn reviews_for_path(pool: &PgPool, path: &str) -> anyhow::Result<Vec<(i64, String, String)>> {
Ok(sqlx::query_as(
"SELECT id, status::text, context_json::jsonb->>'sha256'
FROM furumusic__pending_review WHERE input_path = $1 ORDER BY id",
)
.bind(path)
.fetch_all(pool)
.await?)
}
async fn review_for_hash(db: &Database, path: &str, sha: &str) -> anyhow::Result<PendingReview> {
Ok(PendingReview::create(
db,
0,
"new_file",
Some(path),
Some(&json!({"sha256": sha}).to_string()),
Some(r#"{"title":"saved title"}"#),
)
.await?)
}
async fn scan(ctx: &JobContext) -> anyhow::Result<()> {
InboxDiscoverJob.run(ctx, &mut JobLog::new()).await
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL in FURU_IMPORT_TEST_DATABASE_URL"]
async fn inbox_review_rediscovery_respects_dismissals_and_verifies_catalog_bytes()
-> anyhow::Result<()> {
let url = std::env::var("FURU_IMPORT_TEST_DATABASE_URL")?;
let db = Database::new(&url).await?;
let registry = std::sync::Arc::new(JobRegistry::new());
let app = crate::admin::AdminApp::new(Default::default(), registry.clone(), Default::default());
MigrationEngine::new(app.migrations())?.run(&db).await?;
let root = tempfile::tempdir()?;
let inbox = root.path().join("inbox");
let library = root.path().join("library");
let scope = uuid::Uuid::new_v4().to_string();
let ctx = JobContext {
config: AppConfig {
agent_inbox_dir: inbox.to_str().unwrap().into(),
agent_storage_dir: library.to_str().unwrap().into(),
..Default::default()
}
.into(),
db,
pool: PgPool::connect(&url).await?,
run_id: 0,
registry,
};
fs::create_dir_all(inbox.join(&scope))?;
let path = format!("{scope}/upload.mp3");
let first = tagged_mp3(&format!("{scope} first"))?;
let replacement = tagged_mp3(&format!("{scope} replacement"))?;
fs::write(inbox.join(&path), &first)?;
scan(&ctx).await?;
let reviews = reviews_for_path(&ctx.pool, &path).await?;
assert_eq!(reviews.len(), 1);
assert_eq!(
PendingReview::dismiss(&ctx.pool, &[reviews[0].0], None).await?,
1
);
scan(&ctx).await?;
assert!(reviews_for_path(&ctx.pool, &path).await?.is_empty());
assert_eq!(fs::read(inbox.join(&path))?, first);
fs::write(inbox.join(&path), &replacement)?;
scan(&ctx).await?;
let reviews = reviews_for_path(&ctx.pool, &path).await?;
assert_eq!(reviews.len(), 1);
assert_eq!(reviews[0].1, "queued");
assert_eq!(reviews[0].2, hash(&replacement));
let fields = NormalizedFields {
artist: Some(scope.clone()),
title: Some("original".into()),
album: Some("album".into()),
..Default::default()
};
let import_path = format!("{scope}/library.mp3");
fs::write(inbox.join(&import_path), &first)?;
let sha = hash(&first);
scan(&ctx).await?;
let newly_uploaded = reviews_for_path(&ctx.pool, &import_path).await?;
assert_eq!(newly_uploaded.len(), 1);
assert_eq!(newly_uploaded[0].2, sha);
super::inbox_process::finalize_approved(
&ctx.db,
&ctx.pool,
&ctx.config,
&import_path,
&fields,
&json!({ "sha256": sha, "file_size": first.len() }),
super::inbox_process::ReviewApproval::Check(None),
)
.await?;
let stored = library.join(&scope).join("album/original.mp3");
assert_eq!(fs::read(&stored)?, first);
let missing_path = format!("{scope}/consumed.mp3");
let consumed = review_for_hash(&ctx.db, &missing_path, &sha).await?;
fs::remove_file(inbox.join(&path))?;
// A catalog row with the right hash but different bytes cannot resolve a review.
fs::write(&stored, b"wrong contents")?;
scan(&ctx).await?;
assert_ne!(
PendingReview::get_by_id(&ctx.db, consumed.id_val())
.await?
.unwrap()
.status_str(),
"auto_approved"
);
fs::write(&stored, &first)?;
scan(&ctx).await?;
let consumed = PendingReview::get_by_id(&ctx.db, consumed.id_val())
.await?
.unwrap();
assert_eq!(consumed.status_str(), "auto_approved");
assert_eq!(consumed.result_json_str(), r#"{"title":"saved title"}"#);
assert!(consumed.error_message.is_none());
assert!(!inbox.join(&missing_path).exists());
fs::create_dir_all(inbox.join(&scope))?;
let conflict_path = format!("{scope}/edition.mp3");
let conflict_bytes = tagged_mp3(&format!("{scope} another edition"))?;
fs::write(inbox.join(&conflict_path), &conflict_bytes)?;
let mut conflict = review_for_hash(&ctx.db, &conflict_path, &hash(&conflict_bytes)).await?;
let error = crate::agent::dedup::DuplicateReview("track 42: duration differs".into()).into();
conflict.set_approval_error(&ctx.db, &error).await?;
assert_eq!(conflict.status_str(), "pending");
// Older approvals persisted the same conflict as a failure eligible for hourly retry.
let reason = "Review approval failed: Duplicate check needs review: track 42: duration differs";
conflict.set_failed(&ctx.db, reason).await?;
sqlx::query(
"UPDATE furumusic__pending_review SET updated_at='2001-01-01T00:00:00Z' WHERE id=$1",
)
.bind(conflict.id_val())
.execute(&ctx.pool)
.await?;
let changed_path = format!("{scope}/replaced.mp3");
let stale = review_for_hash(&ctx.db, &changed_path, &sha).await?;
fs::write(inbox.join(&changed_path), &replacement)?;
let duplicate_path = format!("{scope}/another-copy.mp3");
let duplicate = review_for_hash(&ctx.db, &duplicate_path, &sha).await?;
fs::write(inbox.join(&duplicate_path), &first)?;
scan(&ctx).await?;
scan(&ctx).await?;
let duplicate = PendingReview::get_by_id(&ctx.db, duplicate.id_val())
.await?
.unwrap();
assert_eq!(duplicate.status_str(), "auto_approved");
assert!(!inbox.join(&duplicate_path).exists());
assert_eq!(fs::read(inbox.join(&changed_path))?, replacement);
let queued: Vec<_> = reviews_for_path(&ctx.pool, &changed_path)
.await?
.into_iter()
.filter(|(_, status, _)| status == "queued")
.collect();
assert_eq!(queued.len(), 1);
assert_eq!(queued[0].2, hash(&replacement));
assert_ne!(queued[0].0, stale.id_val());
let conflict = PendingReview::get_by_id(&ctx.db, conflict.id_val())
.await?
.unwrap();
assert_eq!(conflict.status_str(), "pending");
assert!(conflict.error_message_str().contains("duration differs"));
assert_eq!(fs::read(inbox.join(&conflict_path))?, conflict_bytes);
Ok(())
}
+38
View File
@@ -293,6 +293,44 @@ async fn postgres_cache_retry_content_binding_and_manual_versions() {
.unwrap()
.is_empty()
);
// Federated alternatives are durable, deduplicated and bound to exact local audio.
let content_id = format!("b3:{}", "a".repeat(64));
sqlx::query(
"INSERT INTO furumusic__federation_content_id_cache(media_file_id,sha256_hash,content_id)
VALUES(1,'audio-a',$1)",
)
.bind(&content_id)
.execute(&pool)
.await
.unwrap();
let existing = crate::lyrics::versions(&pool, "audio-a").await.unwrap();
let mut alternative = automatic.clone();
alternative.plain_text = Some("Words from a peer".into());
alternative.synced_lrc = None;
for _ in 0..2 {
crate::lyrics::save_peer_versions(&pool, &content_id, std::slice::from_ref(&alternative))
.await
.unwrap();
}
let served_hash = crate::lyrics::visible_content_hash(&pool, &content_id)
.await
.unwrap()
.unwrap();
let merged = crate::lyrics::versions(&pool, &served_hash).await.unwrap();
assert_eq!(merged.len(), existing.len() + 1);
assert!(existing.iter().all(|version| merged.contains(version)));
assert!(
merged.iter().any(|version| version.source == "federation"
&& crate::lyrics::same_text(version, &alternative))
);
assert_eq!(
crate::lyrics::track_content_id(&pool, 1, true)
.await
.unwrap()
.as_deref(),
Some(content_id.as_str())
);
// Visibility is enforced independently of whether lyrics exist.
sqlx::query("UPDATE furumusic__track SET is_hidden=true WHERE id=1")
.execute(&pool)
+4
View File
@@ -2,6 +2,10 @@ pub mod archive_cleanup;
pub mod artwork_backfill;
pub mod inbox_discover;
pub mod inbox_process;
mod inbox_review;
pub(crate) use inbox_review::remove_exact_inbox_copy;
#[cfg(test)]
mod inbox_review_tests;
pub mod lastfm_popularity;
pub mod lastfm_scrobble;
pub mod lyrics_backfill;
@@ -0,0 +1,148 @@
{
"playlists": [
{
"name": "Road trip",
"lastModifiedDate": "2026-10-02",
"collaborators": [],
"items": [
{
"track": {
"trackName": "Paranoid Android",
"artistName": "Radiohead",
"albumName": "OK Computer",
"trackUri": "spotify:track:6LgJvl0Xdtc73RJ1mmpotq"
},
"episode": null,
"audiobook": null,
"localTrack": null,
"addedDate": "2026-09-14"
},
{
"track": {
"trackName": "Come Together - Remastered 2009",
"artistName": "The Beatles",
"albumName": "Abbey Road (Remastered)",
"trackUri": "spotify:track:2EqlS6tkEnglzr7tkKAAYD"
},
"episode": null,
"audiobook": null,
"localTrack": null,
"addedDate": "2026-09-14"
},
{
"track": null,
"episode": {
"episodeName": "Episode 12: Tour stories",
"showName": "Example Music Podcast",
"episodeUri": "spotify:episode:4rOoJ6Egrf8K2IrywzwOMk"
},
"audiobook": null,
"localTrack": null,
"addedDate": "2026-09-15"
},
{
"track": {
"trackName": "Paranoid Android",
"artistName": "Radiohead",
"albumName": "OK Computer",
"trackUri": "spotify:track:6LgJvl0Xdtc73RJ1mmpotq"
},
"episode": null,
"audiobook": null,
"localTrack": null,
"addedDate": "2026-09-20"
},
{
"track": null,
"episode": null,
"audiobook": null,
"localTrack": {
"uri": "spotify:local:My+Band:Garage+Tapes:Demo+Song:215"
},
"addedDate": "2026-09-21"
},
{
"track": null,
"episode": null,
"audiobook": {
"audiobookName": "Example Audiobook",
"chapterName": "Chapter 1",
"audiobookUri": "spotify:show:7iHfbu1YPACw6oZPAFJtqe"
},
"localTrack": null,
"addedDate": "2026-09-22"
},
{
"track": null,
"episode": null,
"audiobook": null,
"localTrack": null,
"addedDate": "2026-09-23"
},
{
"track": {
"trackName": "",
"artistName": "Unknown Artist",
"albumName": "",
"trackUri": "spotify:track:0aaaaaaaaaaaaaaaaaaaaa"
},
"episode": null,
"audiobook": null,
"localTrack": null,
"addedDate": "2026-09-24"
}
],
"description": "Songs for the long drive",
"numberOfFollowers": 0
},
{
"name": "Русский рок",
"lastModifiedDate": "2026-08-30",
"collaborators": [],
"items": [
{
"track": {
"trackName": "Звезда по имени Солнце",
"artistName": "Кино",
"albumName": "Звезда по имени Солнце",
"trackUri": "spotify:track:1bbbbbbbbbbbbbbbbbbbbb"
},
"episode": null,
"localTrack": null,
"addedDate": "2026-08-30"
},
{
"track": {
"trackName": "Что такое осень",
"artistName": "ДДТ",
"albumName": "Актриса Весна",
"trackUri": "spotify:track:2ccccccccccccccccccccc"
},
"episode": null,
"localTrack": null,
"addedDate": "2026-08-30"
},
{
"track": {
"trackName": "Восьмиклассница",
"artistName": "Кино",
"albumName": "45",
"trackUri": "spotify:track:3ddddddddddddddddddddd"
},
"episode": null,
"localTrack": null,
"addedDate": "2026-08-31"
}
],
"description": null,
"numberOfFollowers": 2
},
{
"name": "Empty",
"lastModifiedDate": "2026-07-01",
"items": [],
"description": null,
"numberOfFollowers": 0
}
]
}
@@ -0,0 +1,52 @@
{
"tracks": [
{
"artist": "Massive Attack",
"album": "Mezzanine",
"track": "Teardrop",
"uri": "spotify:track:67Hna13dNDkZvBpTXRIaOJ"
},
{
"artist": "Björk",
"album": "Homogenic",
"track": "Jóga",
"uri": "spotify:track:4eeeeeeeeeeeeeeeeeeeee"
},
{
"artist": "Кино",
"album": "Группа крови",
"track": "Группа крови",
"uri": "spotify:track:5fffffffffffffffffffff"
},
{
"artist": "Queen",
"album": "Live at Wembley Stadium",
"track": "Bohemian Rhapsody - Live at Wembley Stadium",
"uri": "spotify:track:6ggggggggggggggggggggg"
}
],
"albums": [
{
"artist": "Radiohead",
"album": "OK Computer",
"uri": "spotify:album:6dVIqQ8qmQ5GBnJ9shOYGE"
}
],
"shows": [
{
"name": "Example Music Podcast",
"publisher": "Example Publisher",
"uri": "spotify:show:2hhhhhhhhhhhhhhhhhhhhh"
}
],
"episodes": [],
"bannedTracks": [],
"artists": [
{
"name": "Кино",
"uri": "spotify:artist:7iiiiiiiiiiiiiiiiiiiii"
}
],
"bannedArtists": [],
"other": []
}
+232
View File
@@ -0,0 +1,232 @@
//! File adapters convert exported provider data into [`ImportedLibrary`].
//!
//! Adapters are pure: they receive file names and bytes and never touch the
//! database or the network.
pub mod spotify_export;
use std::collections::HashSet;
use std::fmt;
use sha2::{Digest, Sha256};
use super::model::{ImportedLibrary, ImportedPlaylist, ProviderInfo, SourceType};
/// One uploaded file. Raw files are parsed in memory and never stored.
#[derive(Debug, Clone)]
pub struct InputFile {
pub name: String,
pub data: Vec<u8>,
}
/// Entries (tracks and other items) and playlists one upload may hold. A
/// 32 MiB request of real export JSON holds far fewer; the limit keeps tiny
/// hand-made entries from turning into gigabytes of parsed tracks.
pub const MAX_ENTRIES: usize = 200_000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdapterError {
/// None of the files belongs to this provider's export.
NoSupportedFiles,
/// A recognised file could not be parsed. The message never contains file contents.
Invalid { file: String, reason: String },
/// More than [`MAX_ENTRIES`] entries or playlists.
TooManyEntries,
}
impl fmt::Display for AdapterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoSupportedFiles => f.write_str("no supported files in the upload"),
Self::Invalid { file, reason } => write!(f, "{file}: {reason}"),
Self::TooManyEntries => write!(
f,
"the export has more than {MAX_ENTRIES} entries or playlists"
),
}
}
}
impl std::error::Error for AdapterError {}
pub trait FileAdapter: Send + Sync {
/// Provider id stored in `furumusic__library_import.provider`.
fn provider(&self) -> &'static str;
/// Name shown in the import wizard.
fn display_name(&self) -> &'static str;
/// Whether a file name belongs to this provider's export.
fn accepts(&self, file_name: &str) -> bool;
fn parse(&self, files: &[InputFile]) -> Result<ImportedLibrary, AdapterError>;
}
/// File adapters available on this instance.
pub fn file_adapters() -> &'static [&'static dyn FileAdapter] {
&[&spotify_export::SpotifyExport]
}
pub fn file_adapter(provider: &str) -> Option<&'static dyn FileAdapter> {
file_adapters()
.iter()
.copied()
.find(|adapter| adapter.provider() == provider)
}
/// The base name of an uploaded path such as `Spotify Account Data/Playlist1.json`.
pub fn base_name(name: &str) -> &str {
name.rsplit(['/', '\\']).next().unwrap_or(name)
}
/// The version marker a title carries, such as `Live` in `Song - Live` or
/// `Remix` in `Song (Remix)`. The matcher makes the final decision.
pub fn version_hint(title: &str) -> Option<String> {
let title = title.trim();
let (base, hint) = if let Some(split) = title.rsplit_once(" - ") {
split
} else {
let (close, open) = match title.chars().last()? {
')' => (')', '('),
']' => (']', '['),
_ => return None,
};
let inner = title.strip_suffix(close)?;
let index = inner.rfind(open)?;
(&inner[..index], &inner[index + 1..])
};
let hint = hint.trim();
(!base.trim().is_empty() && !hint.is_empty()).then(|| hint.to_owned())
}
/// Re-import keys of `library.entries()`, in the same order.
///
/// A provider playlist id is the key when there is one. Otherwise the key is
/// a hash of the kind, the title and the ordered track keys, so the same
/// export gives the same keys while a changed one does not. Equal playlists
/// inside one library get their position appended to stay distinct.
pub fn source_keys(library: &ImportedLibrary) -> Vec<String> {
let mut seen = HashSet::new();
library
.entries()
.enumerate()
.map(|(ordinal, playlist)| {
let key = playlist
.source_id
.clone()
.unwrap_or_else(|| content_key(playlist));
if seen.insert(key.clone()) {
key
} else {
format!("{key}#{ordinal}")
}
})
.collect()
}
fn content_key(playlist: &ImportedPlaylist) -> String {
let mut hash = Sha256::new();
hash.update(playlist.kind.as_str());
hash.update([0]);
hash.update(playlist.title.trim());
for track in &playlist.tracks {
hash.update([0]);
match &track.source_id {
Some(id) => hash.update(id),
None => {
hash.update(track.kind.as_str());
for part in std::iter::once(&track.title)
.chain(&track.artists)
.chain(&track.album)
{
hash.update([1]);
hash.update(music_dht::normalize_name(part));
}
}
}
}
format!("sha256:{:x}", hash.finalize())
}
/// Providers with a file import path. API methods are added by provider integrations.
pub fn file_providers() -> Vec<ProviderInfo> {
file_adapters()
.iter()
.map(|adapter| ProviderInfo {
id: adapter.provider(),
name: adapter.display_name(),
methods: vec![SourceType::File],
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::library_import::model::{ImportedTrack, PlaylistKind};
#[test]
fn version_hints_come_from_suffixes_and_brackets() {
for (title, hint) in [
("Wonderwall - Remastered 2014", Some("Remastered 2014")),
("Song (Live at Wembley)", Some("Live at Wembley")),
("Song [Demo]", Some("Demo")),
("Song", None),
("(Untitled)", None),
("Song ()", None),
] {
assert_eq!(version_hint(title).as_deref(), hint, "{title}");
}
}
#[test]
fn base_names_drop_archive_folders() {
assert_eq!(
base_name("Spotify Account Data/Playlist1.json"),
"Playlist1.json"
);
assert_eq!(
base_name("my_spotify_data\\YourLibrary.json"),
"YourLibrary.json"
);
assert_eq!(base_name("Playlist2.json"), "Playlist2.json");
}
fn playlist(title: &str, ids: &[&str]) -> ImportedPlaylist {
ImportedPlaylist {
kind: PlaylistKind::Playlist,
title: title.into(),
tracks: ids
.iter()
.enumerate()
.map(|(position, id)| ImportedTrack {
source_id: Some((*id).into()),
position: position as u32,
title: (*id).into(),
..ImportedTrack::default()
})
.collect(),
..ImportedPlaylist::default()
}
}
#[test]
fn source_keys_follow_contents_and_stay_unique() {
let library = ImportedLibrary {
playlists: vec![
playlist("Mix", &["a", "b"]),
playlist("Mix", &["a", "b"]),
playlist("Mix", &["b", "a"]),
ImportedPlaylist {
source_id: Some("spotify:playlist:1".into()),
..playlist("Mix", &["a", "b"])
},
],
..ImportedLibrary::default()
};
let keys = source_keys(&library);
assert!(keys[0].starts_with("sha256:"));
assert_eq!(keys[1], format!("{}#1", keys[0]));
assert_ne!(keys[2], keys[0], "order is part of the key");
assert_eq!(keys[3], "spotify:playlist:1");
// The same export gives the same keys.
assert_eq!(source_keys(&library.clone()), keys);
}
}
@@ -0,0 +1,730 @@
//! Spotify "Download your data" export.
//!
//! The browser unpacks the ZIP and sends only `Playlist*.json` and
//! `YourLibrary.json`; listening history never leaves it. Spotify does not
//! publish the schema (support.spotify.com/article/understanding-my-data), so
//! parsing is tolerant: unknown keys are ignored, missing or mistyped values
//! become empty, and an entry that cannot be read is kept as unsupported
//! instead of being dropped.
//!
//! `Playlist*.json`: `playlists[].{name, description, items[].{track{trackName,
//! artistName, albumName, trackUri}, episode, audiobook, localTrack}}`.
//! `YourLibrary.json`: `tracks[].{artist, album, track, uri}` → favorites.
//! The export has no playlist ids, durations or ISRC codes.
//!
//! Files are read without building a JSON tree: values are borrowed from the
//! uploaded bytes and parsed one entry at a time, and at most
//! [`MAX_ENTRIES`] entries and playlists are taken.
use std::fmt;
use std::marker::PhantomData;
use serde::de::{IgnoredAny, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer};
use serde_json::value::RawValue;
use super::{AdapterError, FileAdapter, InputFile, MAX_ENTRIES, base_name, version_hint};
use crate::library_import::model::{
ImportedLibrary, ImportedPlaylist, ImportedTrack, PlaylistKind, TrackKind,
};
pub const PROVIDER: &str = "spotify";
/// Title of the favorites playlist; the export does not name it.
pub const FAVORITES_TITLE: &str = "Liked Songs";
pub struct SpotifyExport;
impl FileAdapter for SpotifyExport {
fn provider(&self) -> &'static str {
PROVIDER
}
fn display_name(&self) -> &'static str {
"Spotify"
}
fn accepts(&self, file_name: &str) -> bool {
playlist_file_number(file_name).is_some() || is_library_file(file_name)
}
fn parse(&self, files: &[InputFile]) -> Result<ImportedLibrary, AdapterError> {
let mut playlist_files: Vec<(u32, &InputFile)> = files
.iter()
.filter_map(|file| playlist_file_number(&file.name).map(|number| (number, file)))
.collect();
let library_files: Vec<&InputFile> = files
.iter()
.filter(|file| is_library_file(&file.name))
.collect();
if playlist_files.is_empty() && library_files.is_empty() {
return Err(AdapterError::NoSupportedFiles);
}
// Playlist1.json, Playlist2.json, …, Playlist10.json keep the export order.
playlist_files.sort_by_key(|(number, _)| *number);
let mut library = ImportedLibrary {
provider: PROVIDER.to_owned(),
..ImportedLibrary::default()
};
let mut entries = Entries::default();
for (_, file) in playlist_files {
let content: PlaylistFile = parse_json(file)?;
for raw in entries.take_playlists(content.playlists)? {
let raw: RawPlaylist = lenient_raw(raw);
let items = entries.take(raw.items)?;
library
.playlists
.push(playlist(raw.name, raw.description, items));
}
}
let mut favorites = Vec::new();
for file in library_files {
let content: LibraryFile = parse_json(file)?;
favorites.extend(entries.take(content.tracks)?);
}
if !favorites.is_empty() {
library.favorites = Some(ImportedPlaylist {
kind: PlaylistKind::Favorites,
source_id: None,
title: FAVORITES_TITLE.to_owned(),
description: None,
tracks: favorites
.into_iter()
.enumerate()
.map(|(position, raw)| saved_track(position, lenient_raw(raw)))
.collect(),
});
}
Ok(library)
}
}
/// Counts the entries and playlists of one upload against [`MAX_ENTRIES`].
#[derive(Default)]
struct Entries {
entries: usize,
playlists: usize,
}
impl Entries {
fn take<'a>(&mut self, elements: Elements<'a>) -> Result<Vec<&'a RawValue>, AdapterError> {
self.entries += elements.0.len();
if self.entries > MAX_ENTRIES {
return Err(AdapterError::TooManyEntries);
}
Ok(elements.0)
}
fn take_playlists<'a>(
&mut self,
elements: Elements<'a>,
) -> Result<Vec<&'a RawValue>, AdapterError> {
self.playlists += elements.0.len();
if self.playlists > MAX_ENTRIES {
return Err(AdapterError::TooManyEntries);
}
Ok(elements.0)
}
}
fn playlist_file_number(name: &str) -> Option<u32> {
let name = base_name(name);
let stem = name.strip_suffix(".json")?.strip_prefix("Playlist")?;
if stem.is_empty() {
return Some(0);
}
stem.bytes()
.all(|byte| byte.is_ascii_digit())
.then(|| stem.parse().ok())
.flatten()
}
fn is_library_file(name: &str) -> bool {
base_name(name) == "YourLibrary.json"
}
/// Parses a file whose top level must be a JSON object. Errors name the file
/// and the position only: serde messages can quote the content.
fn parse_json<'a, T: Deserialize<'a> + Default>(file: &'a InputFile) -> Result<T, AdapterError> {
let invalid = |reason: String| AdapterError::Invalid {
file: base_name(&file.name).to_owned(),
reason,
};
let raw: &RawValue = serde_json::from_slice(&file.data).map_err(|error| {
invalid(format!(
"not valid JSON (line {}, column {})",
error.line(),
error.column()
))
})?;
if !raw.get().starts_with('{') {
return Err(invalid("not a Spotify export file".to_owned()));
}
Ok(lenient_raw(raw))
}
/// Deserializes `raw` as `T`, falling back to `T::default()` when the shape differs.
fn lenient_raw<'a, T: Deserialize<'a> + Default>(raw: &'a RawValue) -> T {
serde_json::from_str(raw.get()).unwrap_or_default()
}
fn lenient<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + Default,
{
Ok(lenient_raw(<&'de RawValue>::deserialize(deserializer)?))
}
/// The elements of a JSON array, borrowed from the file. One more than
/// [`MAX_ENTRIES`] are kept, so the caller can tell the limit was exceeded;
/// the rest is only checked as JSON.
#[derive(Default)]
struct Elements<'a>(Vec<&'a RawValue>);
impl<'de: 'a, 'a> Deserialize<'de> for Elements<'a> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct ElementsVisitor<'a>(PhantomData<&'a ()>);
impl<'de: 'a, 'a> Visitor<'de> for ElementsVisitor<'a> {
type Value = Elements<'a>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("an array")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut elements = Vec::new();
while elements.len() <= MAX_ENTRIES {
match seq.next_element::<&'de RawValue>()? {
Some(element) => elements.push(element),
None => return Ok(Elements(elements)),
}
}
while seq.next_element::<IgnoredAny>()?.is_some() {}
Ok(Elements(elements))
}
}
deserializer.deserialize_seq(ElementsVisitor(PhantomData))
}
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct PlaylistFile<'a> {
#[serde(borrow, deserialize_with = "lenient")]
playlists: Elements<'a>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct LibraryFile<'a> {
#[serde(borrow, deserialize_with = "lenient")]
tracks: Elements<'a>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct RawPlaylist<'a> {
#[serde(deserialize_with = "lenient")]
name: Option<String>,
#[serde(deserialize_with = "lenient")]
description: Option<String>,
#[serde(borrow, deserialize_with = "lenient")]
items: Elements<'a>,
}
#[derive(Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct RawItem {
#[serde(deserialize_with = "lenient")]
track: Option<RawTrack>,
#[serde(deserialize_with = "lenient")]
episode: Option<RawEpisode>,
#[serde(deserialize_with = "lenient")]
audiobook: Option<RawAudiobook>,
#[serde(deserialize_with = "lenient")]
local_track: Option<RawLocalTrack>,
}
#[derive(Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct RawTrack {
#[serde(deserialize_with = "lenient")]
track_name: Option<String>,
#[serde(deserialize_with = "lenient")]
artist_name: Option<String>,
#[serde(deserialize_with = "lenient")]
album_name: Option<String>,
#[serde(deserialize_with = "lenient")]
track_uri: Option<String>,
}
#[derive(Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct RawEpisode {
#[serde(deserialize_with = "lenient")]
episode_name: Option<String>,
#[serde(deserialize_with = "lenient")]
show_name: Option<String>,
#[serde(deserialize_with = "lenient")]
episode_uri: Option<String>,
}
#[derive(Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct RawAudiobook {
#[serde(deserialize_with = "lenient")]
audiobook_name: Option<String>,
#[serde(deserialize_with = "lenient")]
chapter_name: Option<String>,
#[serde(deserialize_with = "lenient")]
audiobook_uri: Option<String>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct RawLocalTrack {
#[serde(deserialize_with = "lenient")]
uri: Option<String>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct RawSavedTrack {
#[serde(deserialize_with = "lenient")]
artist: Option<String>,
#[serde(deserialize_with = "lenient")]
album: Option<String>,
#[serde(deserialize_with = "lenient")]
track: Option<String>,
#[serde(deserialize_with = "lenient")]
uri: Option<String>,
}
fn text(value: Option<String>) -> Option<String> {
value
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
fn playlist(
name: Option<String>,
description: Option<String>,
items: Vec<&RawValue>,
) -> ImportedPlaylist {
ImportedPlaylist {
kind: PlaylistKind::Playlist,
source_id: None,
title: text(name).unwrap_or_default(),
description: text(description),
tracks: items
.into_iter()
.enumerate()
.map(|(position, raw)| playlist_item(position, lenient_raw(raw)))
.collect(),
}
}
fn position(index: usize) -> u32 {
u32::try_from(index).unwrap_or(u32::MAX)
}
fn playlist_item(index: usize, item: RawItem) -> ImportedTrack {
let mut entry = ImportedTrack {
position: position(index),
..ImportedTrack::default()
};
if let Some(track) = item.track {
entry.kind = TrackKind::Track;
entry.title = text(track.track_name).unwrap_or_default();
entry.artists = text(track.artist_name).into_iter().collect();
entry.album = text(track.album_name);
entry.source_id = text(track.track_uri);
entry.version_hint = version_hint(&entry.title);
} else if let Some(local) = item.local_track {
entry.kind = TrackKind::LocalFile;
if let Some(parsed) = text(local.uri).as_deref().and_then(local_file_uri) {
entry.title = parsed.title;
entry.artists = parsed.artist.into_iter().collect();
entry.album = parsed.album;
entry.duration_ms = parsed.duration_ms;
}
} else if let Some(episode) = item.episode {
entry.kind = TrackKind::Episode;
entry.title = text(episode.episode_name).unwrap_or_default();
entry.artists = text(episode.show_name).into_iter().collect();
entry.source_id = text(episode.episode_uri);
} else if let Some(audiobook) = item.audiobook {
entry.kind = TrackKind::Audiobook;
entry.title = text(audiobook.chapter_name)
.or_else(|| text(audiobook.audiobook_name.clone()))
.unwrap_or_default();
entry.album = text(audiobook.audiobook_name);
entry.source_id = text(audiobook.audiobook_uri);
} else {
entry.kind = TrackKind::Unknown;
}
entry
}
fn saved_track(index: usize, raw: RawSavedTrack) -> ImportedTrack {
let title = text(raw.track).unwrap_or_default();
ImportedTrack {
kind: TrackKind::Track,
source_id: text(raw.uri),
position: position(index),
version_hint: version_hint(&title),
title,
artists: text(raw.artist).into_iter().collect(),
album: text(raw.album),
duration_ms: None,
isrc: None,
}
}
#[derive(Debug, PartialEq)]
struct LocalFile {
artist: Option<String>,
album: Option<String>,
title: String,
duration_ms: Option<u64>,
}
/// `spotify:local:<artist>:<album>:<title>:<seconds>`, each part
/// form-encoded (`+` for spaces). Shown to the user; never matched.
fn local_file_uri(uri: &str) -> Option<LocalFile> {
let mut parts = uri.strip_prefix("spotify:local:")?.split(':');
let artist = text(parts.next().map(form_decode));
let album = text(parts.next().map(form_decode));
let title = text(parts.next().map(form_decode))?;
let duration_ms = parts
.next()
.and_then(|seconds| seconds.parse::<u64>().ok())
.map(|seconds| seconds * 1000);
Some(LocalFile {
artist,
album,
title,
duration_ms,
})
}
fn form_decode(value: &str) -> String {
fn hex(byte: u8) -> Option<u8> {
(byte as char).to_digit(16).map(|digit| digit as u8)
}
let bytes = value.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
let byte = bytes[index];
let escaped = (byte == b'%')
.then(|| Some(hex(*bytes.get(index + 1)?)? << 4 | hex(*bytes.get(index + 2)?)?))
.flatten();
match (byte, escaped) {
(_, Some(escaped)) => {
decoded.push(escaped);
index += 3;
}
(b'+', None) => {
decoded.push(b' ');
index += 1;
}
(byte, None) => {
decoded.push(byte);
index += 1;
}
}
}
String::from_utf8_lossy(&decoded).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::library_import::adapters::source_keys;
use crate::library_import::model::ResolutionStatus;
// SYNTHETIC FIXTURE. These files were written by hand after the documented
// export layout and the shape of exports seen in the wild; they are not a
// real export. Plan §4.2 makes a fresh anonymized real "Download your data"
// export a condition for accepting this change: add it next to these files
// and run `parses_the_synthetic_export_fixture` against it as well.
const FIXTURE_PLAYLIST: &str = include_str!("fixtures/spotify_export/Playlist1.json");
const FIXTURE_LIBRARY: &str = include_str!("fixtures/spotify_export/YourLibrary.json");
fn file(name: &str, data: &str) -> InputFile {
InputFile {
name: name.into(),
data: data.as_bytes().to_vec(),
}
}
fn parse(files: &[InputFile]) -> ImportedLibrary {
SpotifyExport.parse(files).unwrap()
}
#[test]
fn accepts_only_playlist_and_library_files() {
let adapter = SpotifyExport;
for name in [
"Playlist1.json",
"Spotify Account Data/Playlist12.json",
"Playlist.json",
"MyData/YourLibrary.json",
] {
assert!(adapter.accepts(name), "{name}");
}
for name in [
"StreamingHistory_music_0.json",
"Playlist1.json.bak",
"PlaylistA.json",
"Userdata.json",
"YourLibrary.JSON",
] {
assert!(!adapter.accepts(name), "{name}");
}
}
#[test]
fn parses_the_synthetic_export_fixture() {
let library = parse(&[
file("Spotify Account Data/YourLibrary.json", FIXTURE_LIBRARY),
file("Spotify Account Data/Playlist1.json", FIXTURE_PLAYLIST),
]);
assert_eq!(library.provider, "spotify");
let titles: Vec<&str> = library
.playlists
.iter()
.map(|playlist| playlist.title.as_str())
.collect();
assert_eq!(titles, ["Road trip", "Русский рок", "Empty"]);
let road = &library.playlists[0];
assert_eq!(
road.description.as_deref(),
Some("Songs for the long drive")
);
let kinds: Vec<TrackKind> = road.tracks.iter().map(|track| track.kind).collect();
assert_eq!(
kinds,
[
TrackKind::Track,
TrackKind::Track,
TrackKind::Episode,
TrackKind::Track,
TrackKind::LocalFile,
TrackKind::Audiobook,
TrackKind::Unknown,
TrackKind::Track,
]
);
let first = &road.tracks[0];
assert_eq!(first.title, "Paranoid Android");
assert_eq!(first.artists, ["Radiohead"]);
assert_eq!(first.album.as_deref(), Some("OK Computer"));
assert_eq!(
first.source_id.as_deref(),
Some("spotify:track:6LgJvl0Xdtc73RJ1mmpotq")
);
// Repeats stay separate entries at their own positions.
assert_eq!(road.tracks[3].source_id, first.source_id);
assert_eq!(road.tracks[3].position, 3);
assert_eq!(
road.tracks[1].version_hint.as_deref(),
Some("Remastered 2009")
);
let local = &road.tracks[4];
assert_eq!(local.title, "Demo Song");
assert_eq!(local.artists, ["My Band"]);
assert_eq!(local.duration_ms, Some(215_000));
assert_eq!(local.source_id, None);
// A track without a name is kept and becomes unsupported.
assert_eq!(road.tracks[7].title, "");
assert_eq!(
road.tracks[7].initial_resolution(),
(ResolutionStatus::Unsupported, Some("missing_title"))
);
for (index, note) in [
(2, "episode"),
(4, "local_file"),
(5, "audiobook"),
(6, "unknown_kind"),
] {
assert_eq!(
road.tracks[index].initial_resolution(),
(ResolutionStatus::Unsupported, Some(note)),
"entry {index}"
);
}
let russian = &library.playlists[1];
assert_eq!(russian.tracks.len(), 3);
assert_eq!(russian.tracks[0].artists, ["Кино"]);
assert!(library.playlists[2].tracks.is_empty());
let favorites = library.favorites.as_ref().unwrap();
assert_eq!(favorites.kind, PlaylistKind::Favorites);
assert_eq!(favorites.title, FAVORITES_TITLE);
assert_eq!(favorites.tracks.len(), 4);
assert_eq!(favorites.tracks[2].title, "Группа крови");
assert_eq!(
favorites.tracks[3].version_hint.as_deref(),
Some("Live at Wembley Stadium")
);
// Favorites come first in import order.
assert_eq!(
library.entries().next().unwrap().kind,
PlaylistKind::Favorites
);
assert_eq!(source_keys(&library).len(), 4);
}
#[test]
fn playlist_files_keep_their_numeric_order() {
let playlist = |name: &str| format!(r#"{{"playlists":[{{"name":"{name}","items":[]}}]}}"#);
let library = parse(&[
file("Playlist10.json", &playlist("ten")),
file("Playlist2.json", &playlist("two")),
file("Playlist1.json", &playlist("one")),
]);
let titles: Vec<&str> = library
.playlists
.iter()
.map(|playlist| playlist.title.as_str())
.collect();
assert_eq!(titles, ["one", "two", "ten"]);
assert!(library.favorites.is_none());
}
#[test]
fn missing_and_unexpected_keys_are_tolerated() {
let data = r#"{
"playlists": [
{"items": [{"track": {"trackName": 7, "artistName": null, "albumName": ["x"]}}]},
{"name": " Extra ", "unknown": {"nested": true}, "items": "not a list"},
"not an object",
{"name": "Shapes", "items": [
{"track": "not an object"},
17,
{"track": {"trackName": "Song", "artistName": "Artist", "extra": 1}, "addedDate": "2024-01-01"}
]}
],
"version": 3
}"#;
let library = parse(&[file("Playlist1.json", data)]);
assert_eq!(library.playlists.len(), 4);
let first = &library.playlists[0];
assert_eq!(first.title, "");
assert_eq!(first.tracks.len(), 1);
assert_eq!(first.tracks[0].kind, TrackKind::Track);
assert_eq!(first.tracks[0].title, "");
assert!(first.tracks[0].artists.is_empty());
assert_eq!(library.playlists[1].title, "Extra");
assert!(library.playlists[1].tracks.is_empty());
assert_eq!(library.playlists[2].title, "");
let shapes = &library.playlists[3].tracks;
assert_eq!(shapes.len(), 3, "malformed entries are kept");
assert_eq!(shapes[0].kind, TrackKind::Unknown);
assert_eq!(shapes[1].kind, TrackKind::Unknown);
assert_eq!(shapes[2].title, "Song");
assert_eq!(shapes[2].position, 2);
// A file without the expected keys gives an empty library.
let empty = parse(&[file("Playlist1.json", "{}")]);
assert!(empty.playlists.is_empty());
}
#[test]
fn invalid_files_are_reported_without_their_content() {
let error = SpotifyExport
.parse(&[file("data/Playlist1.json", r#"{"playlists": ["secret""#)])
.unwrap_err();
let AdapterError::Invalid { file: name, reason } = &error else {
panic!("unexpected {error:?}");
};
assert_eq!(name, "Playlist1.json");
assert!(!reason.contains("secret"), "{reason}");
assert!(matches!(
SpotifyExport.parse(&[file("YourLibrary.json", r#"["array"]"#)]),
Err(AdapterError::Invalid { .. })
));
assert_eq!(
SpotifyExport
.parse(&[file("StreamingHistory0.json", "{}")])
.unwrap_err(),
AdapterError::NoSupportedFiles
);
}
#[test]
fn entries_beyond_the_limit_are_refused() {
let items = |count: usize| vec!["{}"; count].join(",");
let at_limit = format!(
r#"{{"playlists": [{{"items": [{}]}}, {{"items": []}}]}}"#,
items(MAX_ENTRIES)
);
let library = parse(&[file("Playlist1.json", &at_limit)]);
assert_eq!(library.playlists[0].tracks.len(), MAX_ENTRIES);
// Over the limit in one playlist, or across playlists and favorites.
let over = format!(
r#"{{"playlists": [{{"items": [{}]}}]}}"#,
items(MAX_ENTRIES + 1)
);
assert_eq!(
SpotifyExport.parse(&[file("Playlist1.json", &over)]),
Err(AdapterError::TooManyEntries)
);
let library_file = r#"{"tracks": [{"track": "Liked"}]}"#;
assert_eq!(
SpotifyExport.parse(&[
file("Playlist1.json", &at_limit),
file("YourLibrary.json", library_file)
]),
Err(AdapterError::TooManyEntries)
);
let playlists = format!(r#"{{"playlists": [{}]}}"#, items(MAX_ENTRIES + 1));
assert_eq!(
SpotifyExport.parse(&[file("Playlist1.json", &playlists)]),
Err(AdapterError::TooManyEntries)
);
// What lies beyond the limit is still checked as JSON.
let broken = format!(
r#"{{"playlists": [{{"items": [{},]}}]}}"#,
items(MAX_ENTRIES + 1)
);
assert!(matches!(
SpotifyExport.parse(&[file("Playlist1.json", &broken)]),
Err(AdapterError::Invalid { .. })
));
}
#[test]
fn local_file_uris_are_decoded() {
assert_eq!(
local_file_uri("spotify:local:AC%2FDC:Back+in+Black:Hells+Bells:312"),
Some(LocalFile {
artist: Some("AC/DC".into()),
album: Some("Back in Black".into()),
title: "Hells Bells".into(),
duration_ms: Some(312_000),
})
);
assert_eq!(
local_file_uri("spotify:local:::Untitled+%E2%84%961:"),
Some(LocalFile {
artist: None,
album: None,
title: "Untitled №1".into(),
duration_ms: None,
})
);
assert_eq!(local_file_uri("spotify:local:a:b::1"), None);
assert_eq!(local_file_uri("spotify:track:1"), None);
assert_eq!(form_decode("100%"), "100%");
assert_eq!(form_decode("%zz%4"), "%zz%4");
assert_eq!(form_decode("%Ж1"), "%Ж1");
}
}
File diff suppressed because it is too large. Load diff
+766
View File
@@ -0,0 +1,766 @@
//! `library_import` background job: claims imports stored in PostgreSQL and
//! runs their phases under a renewable lease.
//!
//! Work is durable: the phase and every entry state live in PostgreSQL, so an
//! interrupted import resumes from its stored phase. A worker that dies
//! without a server restart stops renewing its lease; the sweeper notices the
//! expired lease and starts a new worker, which takes the import over.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;
use anyhow::Result;
use sqlx::PgPool;
use super::model::Phase;
use super::model::ResolutionStatus;
use super::providers::{FetchError, LibraryFetcher, ProviderFetchers, TokenVault};
use super::publisher::{Progress, Publisher, Step};
use super::resolver::{
FEDERATION_BUDGET, FEDERATION_UNAVAILABLE, FederationAccess, GroupOutcome, NetworkSearch,
NodeFederation, Resolver,
};
use super::store::{self, ClaimedImport, Control, FinishOutcome, NewItem, Resolution};
use crate::config::AppConfig;
use crate::scheduler::{Job, JobContext, JobLog, SchedulerHandle};
pub const JOB_NAME: &str = "library_import";
/// Lease length. Renewed every [`HEARTBEAT`], so a live worker never loses it.
pub const LEASE: Duration = Duration::from_secs(120);
const HEARTBEAT: Duration = Duration::from_secs(30);
/// How often the sweeper looks for imports without a live worker.
const SWEEP_INTERVAL: Duration = Duration::from_secs(30);
/// Workers per process. More triggers return at once; queued imports are
/// taken by running workers or by the next sweep.
const MAX_WORKERS: usize = 2;
static ACTIVE_WORKERS: AtomicUsize = AtomicUsize::new(0);
/// A worker slot, released on return and on panic.
struct WorkerSlot;
impl WorkerSlot {
fn acquire() -> Option<Self> {
let slot = Self;
// Dropping the slot gives the increment back when the limit is reached.
(ACTIVE_WORKERS.fetch_add(1, Ordering::AcqRel) < MAX_WORKERS).then_some(slot)
}
}
impl Drop for WorkerSlot {
fn drop(&mut self) {
ACTIVE_WORKERS.fetch_sub(1, Ordering::AcqRel);
}
}
pub struct LibraryImportJob;
#[async_trait::async_trait]
impl Job for LibraryImportJob {
fn name(&self) -> &'static str {
JOB_NAME
}
fn description(&self) -> &'static str {
"Match imported music libraries and publish them as playlists"
}
fn default_cron(&self) -> &'static str {
""
}
async fn run(&self, ctx: &JobContext, log: &mut JobLog) -> Result<()> {
run_worker(&ctx.pool, Arc::clone(&ctx.config), ctx.run_id, log).await
}
}
/// Processes claimable imports until none is left.
pub async fn run_worker(
pool: &PgPool,
config: Arc<AppConfig>,
run_id: i64,
log: &mut JobLog,
) -> Result<()> {
run_worker_with(
pool,
config,
run_id,
log,
Arc::new(ProviderFetchers),
Arc::new(NodeFederation),
)
.await
}
/// [`run_worker`] with the provider API client and the federation given by the caller.
pub async fn run_worker_with(
pool: &PgPool,
config: Arc<AppConfig>,
run_id: i64,
log: &mut JobLog,
fetcher: Arc<dyn LibraryFetcher>,
federation: Arc<dyn FederationAccess>,
) -> Result<()> {
let Some(_slot) = WorkerSlot::acquire() else {
log.info("Library import workers are busy; queued imports will be taken by them");
return Ok(());
};
let worker = Worker {
pool: pool.clone(),
config,
run_id,
fetcher,
federation,
};
let mut processed = 0usize;
while let Some(import) = store::claim_next(pool, run_id, LEASE).await? {
processed += 1;
log.info(&format!(
"Library import {}: claimed (phase {})",
import.id,
import.phase.map_or("start", Phase::as_str)
));
worker.process(&import, log).await?;
}
if processed == 0 {
log.info("No library imports waiting");
}
Ok(())
}
struct Worker {
pool: PgPool,
config: Arc<AppConfig>,
run_id: i64,
fetcher: Arc<dyn LibraryFetcher>,
federation: Arc<dyn FederationAccess>,
}
/// Renews the lease in the background while the worker owns an import.
struct Heartbeat {
task: tokio::task::JoinHandle<()>,
lost: Arc<AtomicBool>,
}
impl Heartbeat {
fn start(pool: PgPool, import_id: i64, run_id: i64) -> Self {
let lost = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&lost);
let task = tokio::spawn(async move {
let mut interval = tokio::time::interval(HEARTBEAT);
interval.tick().await;
loop {
interval.tick().await;
match store::renew_lease(&pool, import_id, run_id, LEASE).await {
Ok(true) => {}
Ok(false) => {
flag.store(true, Ordering::Release);
return;
}
// A temporary database error is retried; the lease covers several beats.
Err(error) => {
tracing::warn!(import_id, %error, "library import lease renewal failed")
}
}
}
});
Self { task, lost }
}
fn lost(&self) -> bool {
self.lost.load(Ordering::Acquire)
}
}
impl Drop for Heartbeat {
fn drop(&mut self) {
self.task.abort();
}
}
enum Stop {
Cancelled,
LeaseLost,
/// The provider token is missing or expired; the user signs in again.
NeedsReauth,
}
impl Worker {
async fn process(&self, import: &ClaimedImport, log: &mut JobLog) -> Result<()> {
let heartbeat = Heartbeat::start(self.pool.clone(), import.id, self.run_id);
if !store::open_attempt(&self.pool, import.id, self.run_id).await? {
log.warn(&format!(
"Library import {}: lease lost before start",
import.id
));
return Ok(());
}
let mut resume_from = import.phase;
loop {
match self.run_phases(import, resume_from, &heartbeat, log).await {
Ok(None) => {}
Ok(Some(Stop::Cancelled)) => {
TokenVault::shared().forget_import(import.id);
if store::cancel_by_worker(&self.pool, import.id, self.run_id).await? {
log.info(&format!("Library import {}: cancelled", import.id));
}
return Ok(());
}
Ok(Some(Stop::NeedsReauth)) => {
if store::wait_for_reauth(&self.pool, import.id, self.run_id).await? {
log.info(&format!(
"Library import {}: waiting for the user to sign in to {} again",
import.id, import.provider
));
}
return Ok(());
}
Ok(Some(Stop::LeaseLost)) => {
log.warn(&format!(
"Library import {}: lease lost; another worker continues",
import.id
));
return Ok(());
}
Err(error) => {
tracing::warn!(import_id = import.id, %error, "library import phase failed");
if store::fail(
&self.pool,
import.id,
self.run_id,
"Import processing failed; retry unmatched to continue",
)
.await?
{
log.error(&format!("Library import {}: failed", import.id));
}
return Ok(());
}
}
match store::finish(&self.pool, import.id, self.run_id).await? {
FinishOutcome::Done(statistics) => {
log.info(&format!(
"Library import {}: done ({} entries, {} matched, {} published)",
import.id,
statistics.total,
statistics.matched(),
statistics.published
));
return Ok(());
}
FinishOutcome::Rerun => {
log.info(&format!(
"Library import {}: changed; running again",
import.id
));
resume_from = None;
}
FinishOutcome::LeaseLost => {
log.warn(&format!("Library import {}: lease lost", import.id));
return Ok(());
}
}
}
}
/// Runs the phases left after `resume_from`. Cancellation and lease loss
/// are checked before every phase; later stages check them inside phases too.
async fn run_phases(
&self,
import: &ClaimedImport,
resume_from: Option<Phase>,
heartbeat: &Heartbeat,
log: &mut JobLog,
) -> Result<Option<Stop>> {
for &phase in Phase::remaining(import.source_type, resume_from) {
if heartbeat.lost() {
return Ok(Some(Stop::LeaseLost));
}
match store::control(&self.pool, import.id, self.run_id).await? {
Control::Continue => {}
Control::Cancel => return Ok(Some(Stop::Cancelled)),
Control::LeaseLost => return Ok(Some(Stop::LeaseLost)),
}
if !store::set_phase(&self.pool, import.id, self.run_id, phase).await? {
return Ok(Some(Stop::LeaseLost));
}
match phase {
Phase::Fetching => {
if let Some(stop) = self.fetch(import, heartbeat, log).await? {
return Ok(Some(stop));
}
}
Phase::ResolveLocal => {
if let Some(stop) = self.resolve_local(import, heartbeat, log).await? {
return Ok(Some(stop));
}
}
Phase::ResolveFederation => {
if let Some(stop) = self.resolve_federation(import, heartbeat, log).await? {
return Ok(Some(stop));
}
}
Phase::Publish => {
if let Some(stop) = self.publish(import, heartbeat, log).await? {
return Ok(Some(stop));
}
}
}
store::refresh_statistics(&mut *self.pool.acquire().await?, import.id).await?;
}
Ok(None)
}
/// Fetches the entries of the selected playlists of an API import. Each
/// playlist is stored with its `fetched_at` in one transaction, so a
/// continued import skips the playlists it already has. The token is
/// dropped once everything is fetched.
async fn fetch(
&self,
import: &ClaimedImport,
heartbeat: &Heartbeat,
log: &mut JobLog,
) -> Result<Option<Stop>> {
let vault = TokenVault::shared();
let pending = store::playlists_to_fetch(&self.pool, import.id).await?;
if pending.is_empty() {
vault.forget_import(import.id);
return Ok(None);
}
let Some(token) = vault.import_token(import.id) else {
return Ok(Some(Stop::NeedsReauth));
};
let (mut fetched, mut refused, mut entries) = (0usize, 0usize, 0usize);
for playlist in &pending {
if heartbeat.lost() {
return Ok(Some(Stop::LeaseLost));
}
match store::control(&self.pool, import.id, self.run_id).await? {
Control::Continue => {}
Control::Cancel => return Ok(Some(Stop::Cancelled)),
Control::LeaseLost => return Ok(Some(Stop::LeaseLost)),
}
let tracks = match self
.fetcher
.fetch_playlist(&import.provider, &token, &playlist.target)
.await
{
Ok(tracks) => tracks,
Err(FetchError::Unauthorized) => {
vault.forget_import(import.id);
return Ok(Some(Stop::NeedsReauth));
}
// Development Mode refuses playlists of other owners, and a
// playlist may be gone; it stays in the import without entries.
Err(FetchError::Forbidden | FetchError::NotFound) => {
refused += 1;
Vec::new()
}
Err(error) => return Err(error.into()),
};
let items: Vec<NewItem> = tracks
.iter()
.map(|track| NewItem::from_track(track, super::model::artist_key(track)))
.collect();
if !store::store_fetched(
&self.pool,
import.id,
self.run_id,
playlist.playlist_id,
&items,
)
.await?
{
return Ok(Some(Stop::LeaseLost));
}
fetched += 1;
entries += items.len();
}
vault.forget_import(import.id);
log.info(&format!(
"Library import {}: fetched {fetched} playlists with {entries} entries ({refused} not readable)",
import.id
));
Ok(None)
}
/// Whether entries without a local match wait for the network stage.
fn searches_network(&self, import: &ClaimedImport) -> bool {
import.federated_search && self.config.federation_enabled
}
/// Matches pending entries against the local library and the federated
/// tracks this server already knows (resolver stages 1–2), without the
/// network. Decisions are written after each artist group; a group that
/// fails is marked failed and the import continues. When the network
/// stage follows, entries without a match stay pending with their reason.
async fn resolve_local(
&self,
import: &ClaimedImport,
heartbeat: &Heartbeat,
log: &mut JobLog,
) -> Result<Option<Stop>> {
let entries = store::pending_entries(&self.pool, import.id).await?;
if entries.is_empty() {
return Ok(None);
}
let prepared = Resolver::prepare(
&self.pool,
import.user_id,
entries,
self.config.agent_storage_dir.clone(),
)
.await?;
let defer = self.searches_network(import);
let mut counts = ResolveCounts::default();
if !prepared.invalid.is_empty() {
if !self.store_resolutions(import, &prepared.invalid).await? {
return Ok(Some(Stop::LeaseLost));
}
counts.add(&prepared.invalid);
}
for group in &prepared.groups {
if heartbeat.lost() {
return Ok(Some(Stop::LeaseLost));
}
match store::control(&self.pool, import.id, self.run_id).await? {
Control::Continue => {}
Control::Cancel => return Ok(Some(Stop::Cancelled)),
Control::LeaseLost => return Ok(Some(Stop::LeaseLost)),
}
let resolutions = match prepared
.resolver
.resolve_group(&self.pool, group, defer)
.await
{
Ok(resolutions) => resolutions,
Err(error) => {
tracing::warn!(
import_id = import.id,
entries = group.len(),
%error,
"library import group failed"
);
group
.iter()
.map(|entry| Resolution::failed(entry.id, "resolve_failed"))
.collect()
}
};
if !self.store_resolutions(import, &resolutions).await? {
return Ok(Some(Stop::LeaseLost));
}
counts.add(&resolutions);
}
log.info(&format!(
"Library import {}: resolved {} entries locally ({} matched, {} ambiguous, {} unmatched, {} failed, {} left for the network)",
import.id,
counts.total,
counts.matched,
counts.ambiguous,
counts.unmatched,
counts.failed,
counts.deferred
));
Ok(None)
}
/// Writes decisions; a write that fails marks the entries failed instead.
async fn store_resolutions(
&self,
import: &ClaimedImport,
resolutions: &[Resolution],
) -> Result<bool> {
match store::store_resolutions(&self.pool, import.id, self.run_id, resolutions).await {
Ok(owned) => Ok(owned),
Err(error) => {
tracing::warn!(
import_id = import.id,
entries = resolutions.len(),
%error,
"library import could not store decisions"
);
let failed: Vec<Resolution> = resolutions
.iter()
.map(|resolution| Resolution::failed(resolution.item_id, "write_failed"))
.collect();
Ok(store::store_resolutions(&self.pool, import.id, self.run_id, &failed).await?)
}
}
}
/// Searches artist catalogues on the network (resolver stage 3), only
/// with the user's consent and enabled federation. Without consent the
/// federation is not even asked whether it runs. Entries that stages 1–2
/// left pending are decided per artist group; cancellation and lease loss
/// stop a running group, which cancels its search and catalogue requests.
async fn resolve_federation(
&self,
import: &ClaimedImport,
heartbeat: &Heartbeat,
log: &mut JobLog,
) -> Result<Option<Stop>> {
if !import.federated_search {
// Entries wait for the network only with consent; after a change
// they keep their local reason.
return self.finish_deferred(import, None).await;
}
if !self.config.federation_enabled {
log.info(&format!(
"Library import {}: federation is disabled; network search skipped",
import.id
));
return self.finish_deferred(import, None).await;
}
if !self.federation.is_running().await {
log.info(&format!(
"Library import {}: federation is not running; network search skipped",
import.id
));
return self
.finish_deferred(import, Some(FEDERATION_UNAVAILABLE))
.await;
}
let entries: Vec<_> = store::pending_entries(&self.pool, import.id)
.await?
.into_iter()
.filter(|entry| entry.note.is_some())
.collect();
if entries.is_empty() {
return Ok(None);
}
let mut prepared = Resolver::prepare(
&self.pool,
import.user_id,
entries,
self.config.agent_storage_dir.clone(),
)
.await?;
if !prepared.invalid.is_empty()
&& !self.store_resolutions(import, &prepared.invalid).await?
{
return Ok(Some(Stop::LeaseLost));
}
let mut search = NetworkSearch::new(&mut prepared.resolver, &*self.federation);
let poll = search.limits().poll;
let (mut counts, mut catalogs, mut catalog_errors) = (ResolveCounts::default(), 0, 0);
let mut ending = None;
for group in &prepared.groups {
if heartbeat.lost() {
return Ok(Some(Stop::LeaseLost));
}
match store::control(&self.pool, import.id, self.run_id).await? {
Control::Continue => {}
Control::Cancel => return Ok(Some(Stop::Cancelled)),
Control::LeaseLost => return Ok(Some(Stop::LeaseLost)),
}
if search.exhausted() {
ending = Some(FEDERATION_BUDGET);
break;
}
// Dropping the group future cancels its lookups.
let outcome = tokio::select! {
outcome = search.resolve_group(group) => outcome,
stop = self.watch(import, heartbeat, poll) => return Ok(Some(stop)),
};
match outcome {
GroupOutcome::Resolved {
resolutions,
catalogs: received,
catalog_errors: lost,
} => {
if !store::add_catalog_errors(&self.pool, import.id, self.run_id, lost).await?
|| !self.store_resolutions(import, &resolutions).await?
{
return Ok(Some(Stop::LeaseLost));
}
counts.add(&resolutions);
catalogs += received;
catalog_errors += lost;
}
GroupOutcome::Unavailable => {
ending = Some(FEDERATION_UNAVAILABLE);
break;
}
}
}
let groups = search.groups();
log.info(&format!(
"Library import {}: searched the network for {groups} artists ({catalogs} catalogues, {catalog_errors} lost); {} entries: {} matched, {} ambiguous, {} unmatched, {} failed",
import.id, counts.total, counts.matched, counts.ambiguous, counts.unmatched, counts.failed
));
if let Some(note) = ending {
log.info(&format!(
"Library import {}: network search stopped ({note}); the remaining entries stay unmatched",
import.id
));
return self.finish_deferred(import, Some(note)).await;
}
Ok(None)
}
/// Entries still waiting for the network become unmatched.
async fn finish_deferred(
&self,
import: &ClaimedImport,
note: Option<&str>,
) -> Result<Option<Stop>> {
Ok(
(!store::finish_deferred(&self.pool, import.id, self.run_id, note).await?)
.then_some(Stop::LeaseLost),
)
}
/// Resolves once the running group must stop: the lease is lost or the
/// user cancelled. A failed check is repeated at the next poll.
async fn watch(&self, import: &ClaimedImport, heartbeat: &Heartbeat, poll: Duration) -> Stop {
loop {
tokio::time::sleep(poll).await;
if heartbeat.lost() {
return Stop::LeaseLost;
}
match store::control(&self.pool, import.id, self.run_id).await {
Ok(Control::Continue) | Err(_) => {}
Ok(Control::Cancel) => return Stop::Cancelled,
Ok(Control::LeaseLost) => return Stop::LeaseLost,
}
}
}
/// Adds matched entries to the target playlists, creating each target on
/// the first pass. Cancellation and lease loss are checked between
/// batches; a committed batch stays published.
async fn publish(
&self,
import: &ClaimedImport,
heartbeat: &Heartbeat,
log: &mut JobLog,
) -> Result<Option<Stop>> {
let mut publisher = Publisher::new(&self.pool, import, self.run_id, &self.config).await?;
for target in store::publish_targets(&self.pool, import.id).await? {
let mut progress = Progress::new(target);
loop {
if heartbeat.lost() {
return Ok(Some(Stop::LeaseLost));
}
match store::control(&self.pool, import.id, self.run_id).await? {
Control::Continue => {}
Control::Cancel => return Ok(Some(Stop::Cancelled)),
Control::LeaseLost => return Ok(Some(Stop::LeaseLost)),
}
match publisher.step(&mut progress).await? {
Step::More => {}
Step::Finished => break,
Step::LeaseLost => return Ok(Some(Stop::LeaseLost)),
}
}
}
let report = publisher.report;
log.info(&format!(
"Library import {}: published {} entries into {} new playlists ({} already present, {} repeated, {} deferred by the Device Sync budget, {} without content id, {} failed; {} playlists paused, {} not created within the budget)",
import.id,
report.published,
report.created,
report.already_present,
report.duplicate,
report.deferred,
report.no_content_id,
report.failed,
report.paused_playlists,
report.deferred_playlists
));
Ok(None)
}
}
/// Decisions of one resolver pass, for the job log.
#[derive(Default)]
struct ResolveCounts {
total: usize,
matched: usize,
ambiguous: usize,
unmatched: usize,
failed: usize,
/// Left pending for the network stage.
deferred: usize,
}
impl ResolveCounts {
fn add(&mut self, resolutions: &[Resolution]) {
for resolution in resolutions {
self.total += 1;
match resolution.status {
ResolutionStatus::Matched => self.matched += 1,
ResolutionStatus::Ambiguous => self.ambiguous += 1,
ResolutionStatus::Failed => self.failed += 1,
ResolutionStatus::Pending => self.deferred += 1,
_ => self.unmatched += 1,
}
}
}
}
// ---------------------------------------------------------------------------
// Boot hook and sweeper
// ---------------------------------------------------------------------------
/// Whether the sweeper should start a worker: an import waits for one (queued,
/// or running under an expired lease) and this process has a free worker slot.
pub async fn needs_worker(pool: &PgPool) -> sqlx::Result<bool> {
if ACTIVE_WORKERS.load(Ordering::Acquire) >= MAX_WORKERS {
return Ok(false);
}
store::has_claimable(pool).await
}
/// Requeues imports of the previous process, then starts a worker whenever an
/// import waits without one. Runs for the lifetime of the server.
pub fn spawn_boot(
config: Arc<AppConfig>,
scheduler: Arc<tokio::sync::OnceCell<Arc<SchedulerHandle>>>,
) {
if config.database_url.is_empty() {
return;
}
tokio::spawn(async move {
// The scheduler marks runs of the previous process failed before it is published.
let handle = loop {
if let Some(handle) = scheduler.get() {
break Arc::clone(handle);
}
tokio::time::sleep(Duration::from_secs(1)).await;
};
let pool = match sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect_lazy(&config.database_url)
{
Ok(pool) => pool,
Err(error) => {
tracing::error!(%error, "library import sweeper could not configure its pool");
return;
}
};
match store::requeue_orphaned(&pool).await {
Ok(0) => {}
Ok(count) => tracing::info!(count, "requeued interrupted library imports"),
Err(error) => tracing::warn!(%error, "failed to requeue interrupted library imports"),
}
let mut interval = tokio::time::interval(SWEEP_INTERVAL);
loop {
interval.tick().await;
match needs_worker(&pool).await {
Ok(true) => {
if let Err(error) = Arc::clone(&handle)
.trigger_job_now_background(JOB_NAME)
.await
{
tracing::warn!(%error, "failed to start a library import worker");
}
}
Ok(false) => {}
Err(error) => tracing::warn!(%error, "library import sweep failed"),
}
}
});
}
+19
View File
@@ -0,0 +1,19 @@
//! Matching of source entries against library and federation candidates
//! (plan §5).
//!
//! This module is pure: it does not depend on the database, the web framework
//! or the async runtime. The resolver collects candidates, prepares them once
//! and asks [`decide`] for a decision.
mod normalize;
mod score;
#[cfg(test)]
mod tests;
pub use normalize::{
KnownArtists, NameKey, artist_name_variants, folded, parse_title, split_artists,
};
pub use score::{
Candidate, Decision, MAX_CANDIDATES, NOT_FOUND, Origin, PreparedCandidate, PreparedSource,
Ranked, Source, decide,
};
+545
View File
@@ -0,0 +1,545 @@
//! Comparison keys, artist splitting and version tags of titles and albums.
use std::collections::{BTreeSet, HashSet};
use unicode_normalization::UnicodeNormalization;
/// The comparison key shared with the federation and the player search:
/// NFKC, lowercase, non-alphanumerics collapsed to single spaces, `ё` = `е`.
pub fn key(text: &str) -> String {
music_dht::normalize_name(text).replace('ё', "е")
}
/// The fallback key without diacritics: `Beyoncé` = `Beyonce`. Only the
/// combining diacritical marks block is dropped, so kana keep their voicing
/// marks and Cyrillic and Japanese text keeps its letters.
pub fn folded(text: &str) -> String {
let stripped: String = text
.nfkd()
.filter(|ch| !('\u{300}'..='\u{36f}').contains(ch))
.collect();
key(&stripped)
}
/// A name or title with its primary and fallback key.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NameKey {
pub key: String,
pub folded: String,
}
impl NameKey {
pub fn new(text: &str) -> Self {
let primary = key(text);
if primary.is_empty() {
// Titles made only of symbols still compare by their text.
let raw = text.trim().to_lowercase();
return Self {
key: raw.clone(),
folded: raw,
};
}
Self {
key: primary,
folded: folded(text),
}
}
pub fn is_empty(&self) -> bool {
self.key.is_empty()
}
/// Equal by the primary key, then by the key without diacritics.
pub fn matches(&self, other: &Self) -> bool {
(!self.key.is_empty() && self.key == other.key)
|| (!self.folded.is_empty() && self.folded == other.folded)
}
}
/// Artist names known to the library, the known federated tracks and the
/// fetched catalogues. Only known names are split into several artists.
#[derive(Debug, Clone, Default)]
pub struct KnownArtists {
names: HashSet<String>,
}
impl KnownArtists {
pub fn insert(&mut self, name: &str) {
let name = NameKey::new(name);
if name.is_empty() {
return;
}
self.names.insert(name.folded);
self.names.insert(name.key);
}
pub fn contains(&self, name: &str) -> bool {
let name = NameKey::new(name);
!name.is_empty() && (self.names.contains(&name.key) || self.names.contains(&name.folded))
}
}
/// Markers that always separate featured artists, in an artist string or a title.
const FEATURING: [&str; 5] = [" featuring ", " feat. ", " feat ", " ft. ", " ft "];
/// Bracketed featuring prefixes. `with` is accepted in titles only.
const BRACKET_FEATURING: [&str; 5] = ["featuring ", "feat. ", "feat ", "ft. ", "ft "];
/// Separators of collaborations, applied only when every part is a known artist.
const SEPARATORS: [&str; 4] = [", ", " & ", " x ", " and "];
/// Collaborations with more parts are kept whole.
const MAX_PARTS: usize = 8;
/// Splits an unbracketed `A feat. B` into `A` and `B`.
fn split_featuring(text: &str) -> (&str, Option<&str>) {
let lower = text.to_ascii_lowercase();
FEATURING
.iter()
.filter_map(|marker| lower.find(marker).map(|index| (index, marker.len())))
.filter(|(index, _)| *index > 0)
.min_by_key(|(index, _)| *index)
.map_or((text, None), |(index, len)| {
(&text[..index], Some(&text[index + len..]))
})
}
/// Removes bracketed featuring groups such as `(feat. X)` and collects their artists.
fn take_bracket_featuring(text: &str, with: bool, featured: &mut Vec<String>) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(open) = rest.find(['(', '[']) {
let close_char = if rest.as_bytes()[open] == b'(' {
')'
} else {
']'
};
let Some(close) = rest[open + 1..]
.find(close_char)
.map(|index| open + 1 + index)
else {
break;
};
let inner = rest[open + 1..close].trim();
let lower = inner.to_ascii_lowercase();
let prefix = BRACKET_FEATURING
.iter()
.copied()
.chain(with.then_some("with "))
.find(|prefix| lower.starts_with(prefix));
match prefix {
Some(prefix) if inner.len() > prefix.len() => {
featured.push(inner[prefix.len()..].trim().to_owned());
out.push_str(rest[..open].trim_end());
}
_ => out.push_str(&rest[..=close]),
}
rest = &rest[close + 1..];
}
out.push_str(rest);
out.trim().to_owned()
}
/// Byte ranges of the parts of `text` between collaboration separators.
fn separator_parts(text: &str) -> Vec<(usize, usize)> {
let lower = text.to_ascii_lowercase();
let mut parts = Vec::new();
let mut start = 0;
loop {
let next = SEPARATORS
.iter()
.filter_map(|separator| {
lower[start..]
.find(separator)
.map(|index| (start + index, separator.len()))
})
.min_by_key(|(index, _)| *index);
match next {
Some((index, len)) => {
parts.push((start, index));
start = index + len;
}
None => {
parts.push((start, text.len()));
return parts;
}
}
}
}
/// Contiguous groups of parts, each a known artist, with the fewest groups.
fn known_segments(
text: &str,
parts: &[(usize, usize)],
known: &KnownArtists,
) -> Option<Vec<String>> {
let count = parts.len();
// best[j]: fewest known segments covering parts[..j], and where the last one starts.
let mut best: Vec<Option<(usize, usize)>> = vec![None; count + 1];
best[0] = Some((0, 0));
for end in 1..=count {
for start in 0..end {
let Some((segments, _)) = best[start] else {
continue;
};
let segment = text[parts[start].0..parts[end - 1].1].trim();
if !known.contains(segment) {
continue;
}
if best[end].is_none_or(|(current, _)| segments + 1 < current) {
best[end] = Some((segments + 1, start));
}
}
}
best[count]?;
let mut names = Vec::new();
let mut end = count;
while end > 0 {
let (_, start) = best[end]?;
names.push(text[parts[start].0..parts[end - 1].1].trim().to_owned());
end = start;
}
names.reverse();
Some(names)
}
fn push_collaboration(text: &str, known: &KnownArtists, names: &mut Vec<String>) {
let text = text.trim();
if text.is_empty() {
return;
}
if !known.contains(text) {
let parts = separator_parts(text);
if (2..=MAX_PARTS).contains(&parts.len())
&& let Some(segments) = known_segments(text, &parts, known)
{
names.extend(segments);
return;
}
}
names.push(text.to_owned());
}
/// Splits a source artist string. `feat.`, `ft.` and `featuring` always
/// separate artists. A string known as a whole stays one artist (`Tyler, The
/// Creator`); otherwise it is split at `, `, ` & `, ` x ` and ` and ` only when
/// every part is a known artist. The main artist comes first.
pub fn split_artists(raw: &str, known: &KnownArtists) -> Vec<String> {
let mut featured = Vec::new();
let text = take_bracket_featuring(raw, false, &mut featured);
let (main, after) = split_featuring(&text);
let mut names = Vec::new();
push_collaboration(main, known, &mut names);
if let Some(after) = after {
push_collaboration(after, known, &mut names);
}
for name in &featured {
push_collaboration(name, known, &mut names);
}
dedupe_names(names)
}
/// Drops repeated names, keeping the first spelling.
pub fn dedupe_names(names: Vec<String>) -> Vec<String> {
let mut seen = HashSet::new();
names
.into_iter()
.filter(|name| {
let key = NameKey::new(name);
!key.is_empty() && seen.insert(key.key)
})
.collect()
}
/// Every name an artist string may resolve to: the whole string, its
/// featured artists and each contiguous group of its collaboration parts.
/// The resolver looks these up to build [`KnownArtists`].
pub fn artist_name_variants(raw: &str) -> Vec<String> {
let mut featured = Vec::new();
let text = take_bracket_featuring(raw, false, &mut featured);
let (main, after) = split_featuring(&text);
let mut variants = vec![raw.trim().to_owned()];
for text in std::iter::once(main)
.chain(after)
.chain(featured.iter().map(String::as_str))
{
let text = text.trim();
let parts = separator_parts(text);
let parts = if parts.len() > MAX_PARTS {
&parts[..1]
} else {
&parts[..]
};
for start in 0..parts.len() {
for end in start + 1..=parts.len() {
variants.push(text[parts[start].0..parts[end - 1].1].trim().to_owned());
}
}
}
variants.retain(|name| !name.is_empty());
variants.sort();
variants.dedup();
variants
}
// ---------------------------------------------------------------------------
// Version tags
// ---------------------------------------------------------------------------
/// Version markers of a title or album, by class.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VersionTags {
/// Must be equal on both sides: live, remixes, edits, covers, versions.
pub hard: BTreeSet<String>,
/// Never equivalent automatically: remaster (with year), mono, stereo, explicit, clean.
pub editorial: BTreeSet<String>,
/// Lower the score slightly: deluxe, bonus track, album or single version.
pub soft: BTreeSet<String>,
}
impl VersionTags {
pub fn is_empty(&self) -> bool {
self.hard.is_empty() && self.editorial.is_empty() && self.soft.is_empty()
}
pub fn extend(&mut self, other: VersionTags) {
self.hard.extend(other.hard);
self.editorial.extend(other.editorial);
self.soft.extend(other.soft);
// A dated remaster names the plain one more precisely.
if self
.editorial
.iter()
.any(|tag| tag.starts_with("remaster:"))
{
self.editorial.remove("remaster");
}
}
}
fn is_year(token: &str) -> bool {
token.len() == 4
&& token.bytes().all(|byte| byte.is_ascii_digit())
&& (token.starts_with("19") || token.starts_with("20"))
}
/// Tags of one part of a decoration such as `Live at Wembley` or `2011 Remaster`.
fn classify_part(tokens: &[&str], tags: &mut VersionTags) {
let Some(&last) = tokens.last() else {
return;
};
let has = |word: &str| tokens.contains(&word);
// A remix names its remixer; the name is not scanned for other markers.
if let Some(index) = tokens
.iter()
.position(|token| matches!(*token, "remix" | "remixed" | "rmx"))
{
let name = if tokens[index] == "remixed" && tokens.get(index + 1) == Some(&"by") {
tokens[index + 2..].join(" ")
} else {
tokens[..index].join(" ")
};
tags.hard.insert(if name.is_empty() {
"remix".to_owned()
} else {
format!("remix:{name}")
});
return;
}
if last == "mix" {
let name = tokens[..tokens.len() - 1].join(" ");
match name.as_str() {
"original" | "album" => tags.soft.insert("original_mix".to_owned()),
"radio" | "single" => tags.hard.insert("edit".to_owned()),
_ if has("extended") => tags.hard.insert("extended".to_owned()),
"" => tags.hard.insert("mix".to_owned()),
_ => tags.hard.insert(format!("mix:{name}")),
};
return;
}
let before = tags.clone();
let mut hard = |tag: &str| {
tags.hard.insert(tag.to_owned());
};
if has("live") || has("unplugged") || tokens.windows(2).any(|pair| pair == ["in", "concert"]) {
hard("live");
}
for word in [
"acoustic",
"instrumental",
"karaoke",
"demo",
"extended",
"slowed",
"cover",
] {
if has(word) {
hard(word);
}
}
if has("edit") {
hard("edit");
}
if ((has("sped") || has("speed")) && has("up")) || has("spedup") || has("nightcore") {
hard("sped_up");
}
if tokens.iter().any(|token| token.starts_with("remaster")) {
tags.editorial
.insert(match tokens.iter().find(|token| is_year(token)) {
Some(year) => format!("remaster:{year}"),
None => "remaster".to_owned(),
});
}
for word in ["mono", "stereo", "explicit", "clean"] {
if has(word) {
tags.editorial.insert(word.to_owned());
}
}
if has("deluxe") {
tags.soft.insert("deluxe".to_owned());
}
if has("bonus") {
tags.soft.insert("bonus".to_owned());
}
if has("edition") {
tags.soft.insert("edition".to_owned());
}
// `From "Film"` and similar soundtrack notes.
if tokens[0] == "from" && tokens.len() > 1 {
tags.soft.insert("from".to_owned());
}
if *tags == before
&& let Some(index) = tokens.iter().position(|token| *token == "version")
{
let name = tokens[..index].join(" ");
match name.as_str() {
"" | "album" | "single" | "original" | "lp" | "studio" => {
tags.soft.insert("version".to_owned());
}
"radio" => {
tags.hard.insert("edit".to_owned());
}
_ => {
tags.hard.insert(format!("version:{name}"));
}
}
}
}
/// Tags of a decoration, or `None` when it carries no known marker and
/// belongs to the title itself (`Part 2`).
fn classify(decoration: &str) -> Option<VersionTags> {
let mut tags = VersionTags::default();
for part in decoration
.split(['/', ';', ','])
.flat_map(|part| part.split(" - "))
{
let part = key(part);
let tokens: Vec<&str> = part.split(' ').filter(|token| !token.is_empty()).collect();
classify_part(&tokens, &mut tags);
}
(!tags.is_empty()).then_some(tags)
}
/// `(inner)` or `[inner]` at the end of `text`, with the text before it.
fn trailing_group(text: &str) -> Option<(&str, &str)> {
let open = match text.chars().last()? {
')' => '(',
']' => '[',
_ => return None,
};
let inner = &text[..text.len() - 1];
let index = inner.rfind(open)?;
Some((&inner[..index], &inner[index + 1..]))
}
/// The text after the last ` - `, ` – ` or ` — `.
fn trailing_dash(text: &str) -> Option<(&str, &str)> {
[" - ", " – ", " — "]
.iter()
.filter_map(|dash| text.rfind(dash).map(|index| (index, dash.len())))
.max_by_key(|(index, _)| *index)
.map(|(index, len)| (&text[..index], &text[index + len..]))
}
/// Strips trailing decorations with known markers: `Song (Live) - Remastered 2011`.
fn strip_decorations(text: &str) -> (String, VersionTags) {
let mut core = text.trim();
let mut tags = VersionTags::default();
loop {
let stripped = [trailing_group(core), trailing_dash(core)]
.into_iter()
.flatten()
.find_map(|(base, decoration)| {
let base = base.trim();
if base.is_empty() {
return None;
}
classify(decoration).map(|found| (base, found))
});
match stripped {
Some((base, found)) => {
tags.extend(found);
core = base;
}
None => return (core.to_owned(), tags),
}
}
}
/// A track title split into its core, featured artists and version tags.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ParsedTitle {
/// The title without featuring groups and known decorations.
pub core: String,
pub key: NameKey,
/// Raw featured artist strings found in the title.
pub featured: Vec<String>,
pub tags: VersionTags,
}
pub fn parse_title(title: &str) -> ParsedTitle {
let mut featured = Vec::new();
let text = take_bracket_featuring(title, true, &mut featured);
let (mut core, tags) = strip_decorations(&text);
if let (main, Some(after)) = split_featuring(&core)
&& !main.trim().is_empty()
{
featured.push(after.trim().to_owned());
core = main.trim().to_owned();
}
featured.retain(|name| !name.is_empty());
ParsedTitle {
key: NameKey::new(&core),
core,
featured,
tags,
}
}
/// An album title split into its core and version tags.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ParsedAlbum {
pub key: NameKey,
pub tags: VersionTags,
}
/// Albums carry version markers too: `Abbey Road (Remastered 2009)` or a
/// concert album such as `Live at Leeds` or `MTV Unplugged`.
pub fn parse_album(album: &str) -> ParsedAlbum {
let (core, mut tags) = strip_decorations(album);
let key = NameKey::new(&core);
let tokens: Vec<&str> = key.key.split(' ').collect();
let concert = match tokens.as_slice() {
["live"] => true,
["live", next, ..] => {
matches!(
*next,
"at" | "in" | "from" | "on" | "aus" | "au" | "à" | "en"
) || is_year(next)
}
_ => false,
} || tokens.contains(&"unplugged")
|| tokens.windows(2).any(|pair| pair == ["in", "concert"]);
if concert {
tags.hard.insert("live".to_owned());
}
ParsedAlbum { key, tags }
}
+406
View File
@@ -0,0 +1,406 @@
//! Candidate scores and the decision for one source entry.
use std::borrow::Borrow;
use std::cmp::Ordering;
use serde::Serialize;
use super::normalize::{
KnownArtists, NameKey, VersionTags, dedupe_names, parse_album, parse_title, split_artists,
};
/// Where a candidate comes from. Local tracks win over federated copies of
/// the same recording.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
Local,
Federation,
}
impl Origin {
pub fn as_str(self) -> &'static str {
match self {
Self::Local => "local",
Self::Federation => "federation",
}
}
}
/// How well a candidate fits. Only `Strong` and `Exact` are chosen automatically.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Level {
Reject,
Weak,
Strong,
Exact,
}
/// Why a candidate was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RejectReason {
Title,
Artist,
Version,
Duration,
}
impl RejectReason {
/// The `resolution_note` of an entry whose candidates were all rejected.
pub fn note(self) -> &'static str {
match self {
Self::Title | Self::Artist => NOT_FOUND,
Self::Version => "version_mismatch",
Self::Duration => "duration_mismatch",
}
}
}
/// `resolution_note` of an entry without any usable candidate.
pub const NOT_FOUND: &str = "not_found";
/// Ambiguous entries keep this many candidates for manual selection.
pub const MAX_CANDIDATES: usize = 5;
/// A source entry as the matcher sees it.
#[derive(Debug, Clone, Default)]
pub struct Source {
pub title: String,
pub artists: Vec<String>,
pub album: Option<String>,
pub duration_ms: Option<u64>,
}
/// A library or federated track that may be the source entry.
#[derive(Debug, Clone)]
pub struct Candidate {
pub origin: Origin,
pub title: String,
pub artists: Vec<String>,
pub featured_artists: Vec<String>,
pub album: Option<String>,
/// Federated durations are whole seconds.
pub duration_seconds: Option<f64>,
pub content_id: Option<String>,
/// Federation peers offering the track.
pub owners: u32,
}
/// Normalized fields shared by sources and candidates.
#[derive(Debug, Clone)]
struct Prepared {
title: NameKey,
artists: Vec<NameKey>,
album: Option<NameKey>,
tags: VersionTags,
duration: Option<f64>,
}
impl Prepared {
fn new(
title: &str,
artists: &[String],
album: Option<&str>,
duration: Option<f64>,
known: &KnownArtists,
) -> (Self, Vec<String>, String) {
let parsed = parse_title(title);
let names = dedupe_names(
artists
.iter()
.chain(&parsed.featured)
.flat_map(|raw| split_artists(raw, known))
.collect(),
);
let mut tags = parsed.tags;
let album = album
.map(str::trim)
.filter(|album| !album.is_empty())
.map(|album| {
let parsed = parse_album(album);
tags.extend(parsed.tags);
parsed.key
});
let prepared = Self {
title: parsed.key,
artists: names.iter().map(|name| NameKey::new(name)).collect(),
album: album.filter(|album| !album.is_empty()),
tags,
duration: duration.filter(|seconds| seconds.is_finite() && *seconds > 0.0),
};
(prepared, names, parsed.core)
}
fn album_matches(&self, other: &Self) -> bool {
matches!((&self.album, &other.album), (Some(a), Some(b)) if a.matches(b))
}
}
/// A source entry prepared once for scoring against many candidates.
#[derive(Debug, Clone)]
pub struct PreparedSource {
inner: Prepared,
artist_names: Vec<String>,
search_title: String,
}
impl PreparedSource {
pub fn new(source: &Source, known: &KnownArtists) -> Self {
let (inner, artist_names, core) = Prepared::new(
&source.title,
&source.artists,
source.album.as_deref(),
source.duration_ms.map(|ms| ms as f64 / 1000.0),
known,
);
Self {
inner,
artist_names,
search_title: core.to_lowercase(),
}
}
/// Artists after featuring extraction and splitting, the main one first.
pub fn artist_names(&self) -> &[String] {
&self.artist_names
}
pub fn title_key(&self) -> &NameKey {
&self.inner.title
}
/// Lowercase title core for a trigram search of the library.
pub fn search_title(&self) -> &str {
&self.search_title
}
}
/// A candidate prepared once for scoring.
#[derive(Debug, Clone)]
pub struct PreparedCandidate {
inner: Prepared,
origin: Origin,
owners: u32,
content_id: Option<String>,
}
impl PreparedCandidate {
pub fn new(candidate: &Candidate, known: &KnownArtists) -> Self {
let artists: Vec<String> = candidate
.artists
.iter()
.chain(&candidate.featured_artists)
.cloned()
.collect();
let (inner, _, _) = Prepared::new(
&candidate.title,
&artists,
candidate.album.as_deref(),
candidate.duration_seconds,
known,
);
Self {
inner,
origin: candidate.origin,
owners: candidate.owners,
content_id: candidate.content_id.clone(),
}
}
pub fn title_key(&self) -> &NameKey {
&self.inner.title
}
/// Whole-second durations are compared with one extra second.
fn tolerance(&self) -> f64 {
match self.origin {
Origin::Local => 0.0,
Origin::Federation => 1.0,
}
}
}
/// The score of one candidate.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Scored {
pub level: Level,
pub score: f32,
pub reason: Option<RejectReason>,
}
impl Scored {
fn reject(reason: RejectReason) -> Self {
Self {
level: Level::Reject,
score: 0.0,
reason: Some(reason),
}
}
}
/// Scores a candidate against a source entry (plan §5).
pub fn score(source: &PreparedSource, candidate: &PreparedCandidate) -> Scored {
let src = &source.inner;
let cand = &candidate.inner;
if !src.title.matches(&cand.title) {
return Scored::reject(RejectReason::Title);
}
if !src
.artists
.iter()
.any(|artist| cand.artists.iter().any(|other| artist.matches(other)))
{
return Scored::reject(RejectReason::Artist);
}
if src.tags.hard != cand.tags.hard {
return Scored::reject(RejectReason::Version);
}
let album = src.album_matches(cand);
let mut penalty = 0.0f32;
let mut level = match (src.duration, cand.duration) {
(Some(a), Some(b)) => {
let delta = ((a - b).abs() - candidate.tolerance()).max(0.0);
penalty += (delta as f32 * 0.01).min(0.1);
if delta <= 3.0 {
if album { Level::Exact } else { Level::Strong }
} else if delta <= 10.0 {
if album { Level::Strong } else { Level::Weak }
} else {
return Scored::reject(RejectReason::Duration);
}
}
// A unique candidate is not a confirmation: without durations only
// the album confirms the recording.
_ if album => Level::Strong,
_ => Level::Weak,
};
if src.tags.editorial != cand.tags.editorial {
level = level.min(Level::Weak);
}
let soft = src.tags.soft.symmetric_difference(&cand.tags.soft).count();
penalty += (soft as f32 * 0.05).min(0.15);
let base = match level {
Level::Exact => 1.0,
Level::Strong => 0.8,
_ => 0.5,
};
Scored {
level,
score: (base - penalty).max(0.05),
reason: None,
}
}
/// A scored candidate in decision order.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ranked {
pub index: usize,
pub level: Level,
pub score: f32,
}
/// The decision for one source entry.
#[derive(Debug, Clone, PartialEq)]
pub enum Decision {
/// One recording fits; `index` is the chosen candidate.
Matched(Ranked),
/// Several recordings, or only weak candidates: the user chooses.
Ambiguous(Vec<Ranked>),
Unmatched {
reason: &'static str,
},
}
/// Preference among candidates of one recording: local, more owners, then
/// the smallest content id; candidates without a content id come last.
fn preference(a: &PreparedCandidate, b: &PreparedCandidate) -> Ordering {
(a.origin != Origin::Local)
.cmp(&(b.origin != Origin::Local))
.then_with(|| b.owners.cmp(&a.owners))
.then_with(|| match (&a.content_id, &b.content_id) {
(Some(x), Some(y)) => x.cmp(y),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
})
}
/// Whether two accepted candidates are the same recording: durations within
/// 2 s, or, without durations, the same album and editorial tags.
fn same_recording(a: &PreparedCandidate, b: &PreparedCandidate) -> bool {
match (a.inner.duration, b.inner.duration) {
(Some(x), Some(y)) => (x - y).abs() - a.tolerance().max(b.tolerance()) <= 2.0,
_ => a.inner.album_matches(&b.inner) && a.inner.tags.editorial == b.inner.tags.editorial,
}
}
fn find(parent: &mut [usize], mut node: usize) -> usize {
while parent[node] != node {
parent[node] = parent[parent[node]];
node = parent[node];
}
node
}
/// Decides an entry from its candidates (plan §5, «Решение по записи»).
pub fn decide<C: Borrow<PreparedCandidate>>(source: &PreparedSource, candidates: &[C]) -> Decision {
let mut accepted = Vec::new();
let mut reason: Option<RejectReason> = None;
for (index, candidate) in candidates.iter().enumerate() {
let scored = score(source, candidate.borrow());
match scored.reason {
Some(rejected) => reason = reason.max(Some(rejected)),
None => accepted.push(Ranked {
index,
level: scored.level,
score: scored.score,
}),
}
}
if accepted.is_empty() {
return Decision::Unmatched {
reason: reason.map_or(NOT_FOUND, RejectReason::note),
};
}
accepted.sort_by(|a, b| {
b.level
.cmp(&a.level)
.then_with(|| b.score.total_cmp(&a.score))
.then_with(|| preference(candidates[a.index].borrow(), candidates[b.index].borrow()))
.then_with(|| a.index.cmp(&b.index))
});
let strong: Vec<Ranked> = accepted
.iter()
.copied()
.filter(|ranked| ranked.level >= Level::Strong)
.collect();
if !strong.is_empty() {
let mut parent: Vec<usize> = (0..strong.len()).collect();
for a in 0..strong.len() {
for b in a + 1..strong.len() {
if same_recording(
candidates[strong[a].index].borrow(),
candidates[strong[b].index].borrow(),
) {
let (root_a, root_b) = (find(&mut parent, a), find(&mut parent, b));
parent[root_a] = root_b;
}
}
}
let root = find(&mut parent, 0);
if (1..strong.len()).all(|node| find(&mut parent, node) == root) {
let chosen = strong
.iter()
.copied()
.min_by(|a, b| {
preference(candidates[a.index].borrow(), candidates[b.index].borrow())
.then_with(|| b.level.cmp(&a.level))
.then_with(|| a.index.cmp(&b.index))
})
.expect("a group has members");
return Decision::Matched(chosen);
}
}
accepted.truncate(MAX_CANDIDATES);
Decision::Ambiguous(accepted)
}
+568
View File
@@ -0,0 +1,568 @@
//! Reference table of the matcher (plan §5) and the extra acceptance cases.
use super::normalize::*;
use super::score::*;
fn known(names: &[&str]) -> KnownArtists {
let mut known = KnownArtists::default();
for name in names {
known.insert(name);
}
known
}
fn source(title: &str, artist: &str, album: Option<&str>, seconds: Option<f64>) -> Source {
Source {
title: title.into(),
artists: vec![artist.into()],
album: album.map(Into::into),
duration_ms: seconds.map(|seconds| (seconds * 1000.0) as u64),
}
}
fn local(title: &str, artist: &str, album: &str, seconds: Option<f64>) -> Candidate {
Candidate {
origin: Origin::Local,
title: title.into(),
artists: vec![artist.into()],
featured_artists: Vec::new(),
album: Some(album.into()),
duration_seconds: seconds,
content_id: None,
owners: 0,
}
}
fn federated(title: &str, artist: &str, album: &str, seconds: Option<f64>, id: &str) -> Candidate {
Candidate {
origin: Origin::Federation,
content_id: Some(id.into()),
owners: 1,
..local(title, artist, album, seconds)
}
}
#[derive(Debug, PartialEq)]
enum Outcome {
Matched(usize),
Ambiguous,
Unmatched(&'static str),
}
fn outcome(source: &Source, known: &KnownArtists, candidates: &[Candidate]) -> Outcome {
let prepared = PreparedSource::new(source, known);
let candidates: Vec<PreparedCandidate> = candidates
.iter()
.map(|candidate| PreparedCandidate::new(candidate, known))
.collect();
match decide(&prepared, &candidates) {
Decision::Matched(ranked) => Outcome::Matched(ranked.index),
Decision::Ambiguous(ranked) => {
assert!(!ranked.is_empty() && ranked.len() <= MAX_CANDIDATES);
Outcome::Ambiguous
}
Decision::Unmatched { reason } => Outcome::Unmatched(reason),
}
}
/// One candidate against one source entry, both with the same album unless given.
fn single(source: Source, candidate: Candidate) -> Outcome {
outcome(&source, &KnownArtists::default(), &[candidate])
}
#[test]
fn keys_ignore_case_punctuation_and_yo() {
assert_eq!(key("AC/DC"), key("ac-dc"));
assert_eq!(key(" Hello, WORLD! "), "hello world");
assert_eq!(key("Ёлка"), key("Елка"));
assert_ne!(key("Beyoncé"), key("Beyonce"));
assert_eq!(folded("Beyoncé"), folded("Beyonce"));
assert!(NameKey::new("Beyoncé").matches(&NameKey::new("BEYONCE")));
// Folding keeps Cyrillic and kana letters.
assert_eq!(folded("Звезда по имени Солнце"), "звезда по имени солнце");
assert_eq!(key("ガーゴイル"), "ガーゴイル");
assert_eq!(folded("が"), "が");
assert!(!NameKey::new("ガーゴイル").matches(&NameKey::new("カーゴイル")));
}
#[test]
fn reference_table() {
let none = KnownArtists::default();
let cases: Vec<(&str, Source, Vec<Candidate>, Outcome)> = vec![
(
"case and punctuation",
source(
"HIGHWAY TO HELL!",
"AC/DC",
Some("Highway to Hell"),
Some(208.0),
),
vec![local(
"Highway to Hell",
"AC-DC",
"Highway To Hell",
Some(208.4),
)],
Outcome::Matched(0),
),
(
"ё equals е",
source("Ёлка", "Ёлка", Some("Ёлка"), Some(180.0)),
vec![local("Елка", "Елка", "Елка", Some(180.0))],
Outcome::Matched(0),
),
(
"diacritics fold",
source("Formation", "Beyonce", Some("Lemonade"), Some(206.0)),
vec![local("Formation", "Beyoncé", "Lemonade", Some(206.0))],
Outcome::Matched(0),
),
(
"featured artist in the title",
source("Song (feat. X)", "A", Some("Album"), Some(200.0)),
vec![Candidate {
featured_artists: vec!["X".into()],
..local("Song", "A", "Album", Some(200.0))
}],
Outcome::Matched(0),
),
(
"live rejects the studio version",
source("Song - Live", "A", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Album", Some(200.0))],
Outcome::Unmatched("version_mismatch"),
),
(
"remix rejects the original",
source("Song (X Remix)", "A", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Album", Some(200.0))],
Outcome::Unmatched("version_mismatch"),
),
(
"radio edit rejects the album version",
source("Song - Radio Edit", "A", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Album", Some(200.0))],
Outcome::Unmatched("version_mismatch"),
),
(
"other remixer",
source("Song (X Remix)", "A", Some("Album"), Some(200.0)),
vec![local("Song - Y Remix", "A", "Album", Some(200.0))],
Outcome::Unmatched("version_mismatch"),
),
(
"same remix spelled differently",
source("Song - X Remix", "A", Some("Album"), Some(200.0)),
vec![local("Song (X Remix)", "A", "Album", Some(200.0))],
Outcome::Matched(0),
),
(
"remaster only on one side",
source("Song - Remastered 2011", "A", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Album", Some(200.0))],
Outcome::Ambiguous,
),
(
"mono against stereo",
source("Song (Mono)", "A", Some("Album"), Some(200.0)),
vec![local("Song (Stereo)", "A", "Album", Some(200.0))],
Outcome::Ambiguous,
),
(
"remaster years differ",
source("Song - Remastered 2009", "A", Some("Album"), Some(200.0)),
vec![local("Song - 2011 Remaster", "A", "Album", Some(200.0))],
Outcome::Ambiguous,
),
(
"same remaster year",
source("Song - Remastered 2009", "A", Some("Album"), Some(200.0)),
vec![local("Song (2009 Remaster)", "A", "Album", Some(200.0))],
Outcome::Matched(0),
),
(
"remaster marker only in the album title",
source(
"Come Together",
"The Beatles",
Some("Abbey Road (Remastered 2009)"),
Some(259.0),
),
vec![local(
"Come Together",
"The Beatles",
"Abbey Road",
Some(259.0),
)],
Outcome::Ambiguous,
),
(
"remaster marker in both album titles",
source(
"Come Together",
"The Beatles",
Some("Abbey Road (Remastered 2009)"),
Some(259.0),
),
vec![local(
"Come Together - 2009 Remaster",
"The Beatles",
"Abbey Road",
Some(259.0),
)],
Outcome::Matched(0),
),
(
"concert album marks the track live",
source("Song", "A", Some("Live at Wembley"), Some(200.0)),
vec![local("Song", "A", "Album", Some(200.0))],
Outcome::Unmatched("version_mismatch"),
),
(
"live marker in the album title on both sides",
source("Song", "A", Some("MTV Unplugged in New York"), Some(200.0)),
vec![local("Song (Live)", "A", "Unplugged", Some(200.0))],
Outcome::Matched(0),
),
(
"delta 2 s",
source("Song", "A", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Other album", Some(202.0))],
Outcome::Matched(0),
),
(
"delta 7 s with another album",
source("Song", "A", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Other album", Some(207.0))],
Outcome::Ambiguous,
),
(
"delta 7 s with the same album",
source("Song", "A", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Album", Some(207.0))],
Outcome::Matched(0),
),
(
"delta 30 s",
source("Song", "A", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Album", Some(230.0))],
Outcome::Unmatched("duration_mismatch"),
),
(
"federated whole seconds get one more second",
source("Song", "A", Some("Other"), Some(203.9)),
vec![federated("Song", "A", "Album", Some(200.0), "b3:1")],
Outcome::Matched(0),
),
(
"two copies of one recording prefer the local file",
source("Song", "A", Some("Album"), Some(200.0)),
vec![
federated("Song", "A", "Album", Some(200.0), "b3:1"),
local("Song", "A", "Album", Some(200.4)),
],
Outcome::Matched(1),
),
(
"two recordings are ambiguous",
source("Song", "A", Some("Album"), Some(200.0)),
vec![
local("Song", "A", "Album", Some(200.0)),
local("Song", "A", "Album", Some(206.0)),
],
Outcome::Ambiguous,
),
(
"without duration the album confirms",
source("Song", "A", Some("Album (Deluxe Edition)"), None),
vec![local("Song", "A", "Album", Some(200.0))],
Outcome::Matched(0),
),
(
"without duration another album is ambiguous",
source("Song", "A", Some("Album"), None),
vec![
local("Song", "A", "Greatest Hits", Some(200.0)),
local("Other", "A", "Album", Some(200.0)),
],
Outcome::Ambiguous,
),
(
"a single candidate with another album is not a match",
source("Song", "A", Some("Album"), None),
vec![local("Song", "A", "Greatest Hits", Some(200.0))],
Outcome::Ambiguous,
),
(
"without album nothing confirms",
source("Song", "A", None, None),
vec![local("Song", "A", "Album", None)],
Outcome::Ambiguous,
),
(
"other artist",
source("Song", "B", Some("Album"), Some(200.0)),
vec![local("Song", "A", "Album", Some(200.0))],
Outcome::Unmatched(NOT_FOUND),
),
(
"other title",
source("Song", "A", Some("Album"), Some(200.0)),
vec![local("Song 2", "A", "Album", Some(200.0))],
Outcome::Unmatched(NOT_FOUND),
),
(
"parts stay in the title",
source("Song (Part 1)", "A", Some("Album"), Some(200.0)),
vec![local("Song (Part 2)", "A", "Album", Some(200.0))],
Outcome::Unmatched(NOT_FOUND),
),
(
"Cyrillic",
source(
"Звезда по имени Солнце",
"Кино",
Some("Звезда по имени Солнце"),
Some(225.0),
),
vec![local(
"Звезда по имени солнце",
"КИНО",
"Звезда по имени Солнце",
Some(225.3),
)],
Outcome::Matched(0),
),
(
"Japanese",
source("夜に駆ける", "YOASOBI", Some("THE BOOK"), Some(261.0)),
vec![local("夜に駆ける", "YOASOBI", "THE BOOK", Some(261.0))],
Outcome::Matched(0),
),
(
"Japanese titles differ",
source("夜に駆ける", "YOASOBI", Some("THE BOOK"), Some(261.0)),
vec![local("群青", "YOASOBI", "THE BOOK", Some(261.0))],
Outcome::Unmatched(NOT_FOUND),
),
(
"no candidates",
source("Song", "A", None, None),
Vec::new(),
Outcome::Unmatched(NOT_FOUND),
),
];
for (name, source, candidates, expected) in cases {
assert_eq!(outcome(&source, &none, &candidates), expected, "{name}");
}
}
#[test]
fn collaborations_split_only_into_known_artists() {
let dictionary = known(&[
"A",
"B",
"Tyler, The Creator",
"Tyler",
"Frank Ocean",
"Foo",
]);
assert_eq!(split_artists("A & B", &dictionary), ["A", "B"]);
assert_eq!(split_artists("A x B", &dictionary), ["A", "B"]);
// Known as a whole: never split, even when its parts are known.
assert_eq!(
split_artists("Tyler, The Creator", &dictionary),
["Tyler, The Creator"]
);
assert_eq!(
split_artists("Tyler, The Creator & Frank Ocean", &dictionary),
["Tyler, The Creator", "Frank Ocean"]
);
// An unknown part keeps the string whole.
assert_eq!(split_artists("Foo, Bar", &dictionary), ["Foo, Bar"]);
assert_eq!(
split_artists("Tyler, The Creator", &KnownArtists::default()),
["Tyler, The Creator"]
);
// Featuring always separates.
assert_eq!(
split_artists("A feat. Somebody", &KnownArtists::default()),
["A", "Somebody"]
);
assert_eq!(
split_artists("A (ft. B)", &KnownArtists::default()),
["A", "B"]
);
assert_eq!(
split_artists("Simon & Garfunkel", &dictionary),
["Simon & Garfunkel"]
);
let variants = artist_name_variants("Tyler, The Creator & Frank Ocean");
for expected in [
"Tyler",
"Tyler, The Creator",
"The Creator & Frank Ocean",
"Frank Ocean",
] {
assert!(variants.iter().any(|name| name == expected), "{expected}");
}
}
#[test]
fn collaborations_match_main_and_featured_artists() {
let dictionary = known(&["A", "B"]);
let candidate = Candidate {
featured_artists: vec!["B".into()],
..local("Song", "A", "Album", Some(200.0))
};
assert_eq!(
outcome(
&source("Song", "A & B", Some("Album"), Some(200.0)),
&dictionary,
std::slice::from_ref(&candidate)
),
Outcome::Matched(0)
);
// B alone also identifies the track through the featured credit.
let b_only = known(&["B", "C"]);
assert_eq!(
outcome(
&source("Song", "C & B", Some("Album"), Some(200.0)),
&b_only,
&[candidate]
),
Outcome::Matched(0)
);
// Known as a whole: "Tyler, The Creator" is one artist and matches as such.
let tyler = known(&["Tyler, The Creator", "Tyler"]);
let song = |artist: &str| local("EARFQUAKE", artist, "IGOR", Some(190.0));
let src = source("EARFQUAKE", "Tyler, The Creator", Some("IGOR"), Some(190.0));
assert_eq!(
outcome(&src, &tyler, &[song("Tyler, The Creator")]),
Outcome::Matched(0)
);
assert_eq!(
outcome(&src, &tyler, &[song("Tyler")]),
Outcome::Unmatched(NOT_FOUND)
);
// An unknown part keeps "Foo, Bar" whole, so it does not match Foo.
let foo = known(&["Foo"]);
assert_eq!(
outcome(
&source("Song", "Foo, Bar", Some("Album"), Some(200.0)),
&foo,
&[local("Song", "Foo", "Album", Some(200.0))]
),
Outcome::Unmatched(NOT_FOUND)
);
}
#[test]
fn single_candidates_follow_the_same_rules() {
assert_eq!(
single(
source("Song", "A", Some("Album"), Some(200.0)),
local("Song", "A", "Album", Some(200.0))
),
Outcome::Matched(0)
);
assert_eq!(
single(
source("Song", "A", Some("Album"), None),
federated("Song", "A", "Other", None, "b3:1")
),
Outcome::Ambiguous
);
}
#[test]
fn titles_split_into_core_featured_and_tags() {
let parsed = parse_title("Song (feat. X & Y) - Remastered 2011");
assert_eq!(parsed.core, "Song");
assert_eq!(parsed.featured, ["X & Y"]);
assert_eq!(
parsed.tags.editorial.iter().collect::<Vec<_>>(),
["remaster:2011"]
);
let parsed = parse_title("Song (with Somebody) [Live at Wembley / 1986 Remaster]");
assert_eq!(parsed.core, "Song");
assert_eq!(parsed.featured, ["Somebody"]);
assert!(parsed.tags.hard.contains("live"));
assert!(parsed.tags.editorial.contains("remaster:1986"));
let parsed = parse_title("Song feat. X - Club Mix");
assert_eq!(
(parsed.core.as_str(), parsed.featured.as_slice()),
("Song", &["X".to_owned()][..])
);
assert!(parsed.tags.hard.contains("mix:club"));
for (title, tag) in [
("Song - Acoustic Version", "acoustic"),
("Song (Instrumental)", "instrumental"),
("Song - Demo", "demo"),
("Song (Extended Mix)", "extended"),
("Song (Sped Up)", "sped_up"),
("Song (Slowed + Reverb)", "slowed"),
("Song - Radio Version", "edit"),
("Song (Taylor's Version)", "version:taylor s"),
] {
assert!(parse_title(title).tags.hard.contains(tag), "{title}");
}
for (title, tag) in [
("Song - Single Version", "version"),
("Song (Bonus Track)", "bonus"),
("Song - Original Mix", "original_mix"),
("Song - From \"Some Film\"", "from"),
] {
let parsed = parse_title(title);
assert!(
parsed.tags.soft.contains(tag) && parsed.tags.hard.is_empty(),
"{title}"
);
}
// Unknown decorations and markers inside the title stay in the core.
assert_eq!(parse_title("Live and Let Die").core, "Live and Let Die");
assert_eq!(
parse_title("Movement I - Allegro").core,
"Movement I - Allegro"
);
assert_eq!(parse_title("(Live)").core, "(Live)");
assert_eq!(
parse_title("Song (Clean Bandit Remix)")
.tags
.editorial
.len(),
0
);
}
#[test]
fn album_titles_carry_version_markers() {
let album = parse_album("Abbey Road (Remastered 2009)");
assert_eq!(album.key.key, "abbey road");
assert!(album.tags.editorial.contains("remaster:2009"));
for title in [
"Live at Leeds",
"Live",
"Live 1975-85",
"MTV Unplugged",
"Queen in Concert",
"Album (Live)",
] {
assert!(parse_album(title).tags.hard.contains("live"), "{title}");
}
for title in ["Live Through This", "Alive 2007", "Abbey Road"] {
assert!(parse_album(title).tags.hard.is_empty(), "{title}");
}
assert!(
parse_album("Album (Super Deluxe Edition)")
.tags
.soft
.contains("deluxe")
);
}
+57
View File
@@ -0,0 +1,57 @@
//! Music library import: provider exports are stored as durable imports,
//! matched against the library and the federation, and published as ordinary
//! private playlists.
//!
//! The subsystem owns the `furumusic__library_import*` tables. It touches the
//! rest of Furumi only when publishing: target playlists, their tracks and the
//! existing Device Sync operations.
// Imports are processed by the resolver and publisher; until those are wired
// in, parts of the model and the storage layer are used by the tests only.
pub mod adapters;
mod handlers;
pub mod job;
pub mod matcher;
#[allow(dead_code)]
pub mod model;
pub mod providers;
pub mod publisher;
pub mod resolver;
#[allow(dead_code)]
pub mod store;
#[cfg(test)]
mod tests;
pub use handlers::ImportApp;
pub use job::LibraryImportJob;
pub mod db_migrations {
use cot::db::migrations::{self, Operation, SyncDynMigration};
#[cot::db::migrations::migration_op]
async fn create_library_import(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> {
for statement in include_str!("schema.sql").split(';') {
if !statement.trim().is_empty() {
ctx.db.raw(statement).await?;
}
}
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0065CreateLibraryImport;
impl migrations::Migration for M0065CreateLibraryImport {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0065_create_library_import";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0064_review_dismissals",
)];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(create_library_import).build()];
}
pub const MIGRATIONS: &[&SyncDynMigration] = &[&M0065CreateLibraryImport];
}
+711
View File
@@ -0,0 +1,711 @@
//! Provider-neutral import model, statuses and API views.
//!
//! This module is pure: it does not depend on the database, the web framework
//! or the async runtime.
use std::fmt;
use std::str::FromStr;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// A provider library converted by an adapter.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ImportedLibrary {
pub provider: String,
pub account_ref: Option<String>,
pub playlists: Vec<ImportedPlaylist>,
pub favorites: Option<ImportedPlaylist>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ImportedPlaylist {
pub kind: PlaylistKind,
pub source_id: Option<String>,
pub title: String,
pub description: Option<String>,
pub tracks: Vec<ImportedTrack>,
}
/// One source entry. Entries without usable metadata are kept as unsupported;
/// order and repeats come from the source.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ImportedTrack {
pub kind: TrackKind,
pub source_id: Option<String>,
pub position: u32,
pub title: String,
pub artists: Vec<String>,
pub album: Option<String>,
pub duration_ms: Option<u64>,
pub isrc: Option<String>,
pub version_hint: Option<String>,
}
impl ImportedLibrary {
/// Playlists in import order: favorites first, then the source playlists.
pub fn entries(&self) -> impl Iterator<Item = &ImportedPlaylist> {
self.favorites.iter().chain(self.playlists.iter())
}
}
impl ImportedTrack {
/// The initial resolution of a stored entry and the reason it cannot be matched.
pub fn initial_resolution(&self) -> (ResolutionStatus, Option<&'static str>) {
match self.kind {
TrackKind::Track if self.title.trim().is_empty() => {
(ResolutionStatus::Unsupported, Some("missing_title"))
}
TrackKind::Track => (ResolutionStatus::Pending, None),
TrackKind::Episode => (ResolutionStatus::Unsupported, Some("episode")),
TrackKind::Audiobook => (ResolutionStatus::Unsupported, Some("audiobook")),
TrackKind::LocalFile => (ResolutionStatus::Unsupported, Some("local_file")),
TrackKind::Unknown => (ResolutionStatus::Unsupported, Some("unknown_kind")),
}
}
/// Metadata stored in `furumusic__library_import_item.metadata`. Source ids
/// and positions have their own columns.
pub fn metadata(&self) -> ItemMetadata {
ItemMetadata {
kind: self.kind,
title: self.title.clone(),
artists: self.artists.clone(),
album: self.album.clone(),
duration_ms: self.duration_ms,
isrc: self.isrc.clone(),
version_hint: self.version_hint.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ItemMetadata {
pub kind: TrackKind,
#[serde(default)]
pub title: String,
#[serde(default)]
pub artists: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub album: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub duration_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub isrc: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version_hint: Option<String>,
}
macro_rules! text_enum {
($(#[$meta:meta])* $name:ident { $($(#[$variant_meta:meta])* $variant:ident => $text:literal),+ $(,)? }) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum $name {
$($(#[$variant_meta])* #[serde(rename = $text)] $variant),+
}
impl $name {
pub const ALL: &'static [Self] = &[$(Self::$variant),+];
pub fn as_str(self) -> &'static str {
match self {
$(Self::$variant => $text),+
}
}
}
impl FromStr for $name {
type Err = UnknownValue;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
$($text => Ok(Self::$variant),)+
_ => Err(UnknownValue),
}
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnknownValue;
impl fmt::Display for UnknownValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("unknown value")
}
}
text_enum!(
#[derive(Default)]
TrackKind {
#[default]
Track => "track",
Episode => "episode",
Audiobook => "audiobook",
LocalFile => "local_file",
Unknown => "unknown",
});
text_enum!(
#[derive(Default)]
PlaylistKind {
#[default]
Playlist => "playlist",
Favorites => "favorites",
});
text_enum!(SourceType {
File => "file",
Api => "api",
});
text_enum!(
/// Lifecycle of an import as a whole.
ImportStatus {
Queued => "queued",
Running => "running",
Done => "done",
Cancelled => "cancelled",
Failed => "failed",
NeedsReauth => "needs_reauth",
}
);
impl ImportStatus {
/// A worker owns or will own the import; history cannot be deleted.
pub fn is_active(self) -> bool {
matches!(self, Self::Queued | Self::Running)
}
}
text_enum!(
/// Durable worker phases. A resumed import continues from the stored phase.
Phase {
Fetching => "fetching",
ResolveLocal => "resolve_local",
ResolveFederation => "resolve_federation",
Publish => "publish",
}
);
impl Phase {
/// Phases for a source type. Only API imports fetch entries in the worker.
pub fn sequence(source_type: SourceType) -> &'static [Phase] {
match source_type {
SourceType::Api => &[
Phase::Fetching,
Phase::ResolveLocal,
Phase::ResolveFederation,
Phase::Publish,
],
SourceType::File => &[
Phase::ResolveLocal,
Phase::ResolveFederation,
Phase::Publish,
],
}
}
/// Phases left to run, starting at the stored phase when it belongs to the sequence.
pub fn remaining(source_type: SourceType, stored: Option<Phase>) -> &'static [Phase] {
let sequence = Self::sequence(source_type);
let start = stored
.and_then(|phase| sequence.iter().position(|candidate| *candidate == phase))
.unwrap_or(0);
&sequence[start..]
}
}
text_enum!(ResolutionStatus {
Pending => "pending",
Matched => "matched",
Ambiguous => "ambiguous",
Unmatched => "unmatched",
Unsupported => "unsupported",
Failed => "failed",
});
text_enum!(PublicationStatus {
NotReady => "not_ready",
Pending => "pending",
Published => "published",
Duplicate => "duplicate",
AlreadyPresent => "already_present",
NoContentId => "no_content_id",
DeferredSyncLimit => "deferred_sync_limit",
Paused => "paused",
Failed => "failed",
});
text_enum!(AttemptKind {
Initial => "initial",
Resync => "resync",
Publish => "publish",
});
text_enum!(AttemptStatus {
Running => "running",
Done => "done",
Cancelled => "cancelled",
Failed => "failed",
});
/// Comparison key of a playlist title: a re-export with changed tracks keeps
/// its title, so the key finds playlists imported before (`similar_to`).
pub fn title_key(title: &str) -> String {
let key = music_dht::normalize_name(title);
if key.is_empty() {
title.trim().to_lowercase()
} else {
key
}
}
/// Normalized main artist used to group entries for the resolver.
pub fn artist_key(track: &ImportedTrack) -> Option<String> {
track
.artists
.iter()
.map(|artist| music_dht::normalize_name(artist))
.find(|key| !key.is_empty())
}
/// A source playlist imported earlier by the same user from the same provider.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportedBefore {
pub source_key: String,
pub kind: PlaylistKind,
pub title: String,
pub import_id: i64,
pub target_playlist_id: Option<i64>,
}
/// An earlier import of a playlist with the same title and kind but other
/// contents: importing it again creates a new playlist after confirmation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct SimilarTo {
pub import_id: i64,
pub target_playlist_id: Option<i64>,
}
/// How a source playlist relates to the user's import history.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct HistoryMatch {
/// The first import of exactly this playlist; it cannot be imported again.
pub already_imported_in: Option<i64>,
pub similar_to: Option<SimilarTo>,
}
/// Compares a source playlist with the history. An exact repeat wins over a
/// similar playlist; among similar ones the latest import is reported.
pub fn history_match(
source_key: &str,
kind: PlaylistKind,
title: &str,
history: &[ImportedBefore],
) -> HistoryMatch {
let already_imported_in = history
.iter()
.filter(|before| before.source_key == source_key)
.map(|before| before.import_id)
.min();
if already_imported_in.is_some() {
return HistoryMatch {
already_imported_in,
similar_to: None,
};
}
let key = title_key(title);
let similar_to = history
.iter()
.filter(|before| before.kind == kind && title_key(&before.title) == key)
.max_by_key(|before| before.import_id)
.map(|before| SimilarTo {
import_id: before.import_id,
target_playlist_id: before.target_playlist_id,
});
HistoryMatch {
already_imported_in,
similar_to,
}
}
/// A source playlist offered for selection by the import wizard.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PreviewPlaylist {
pub source_key: String,
pub kind: PlaylistKind,
pub title: String,
pub description: Option<String>,
pub track_count: usize,
/// Entries that cannot be matched (episodes, local files); unknown before an API fetch.
pub unsupported_count: Option<usize>,
/// Whether the entries can be read by this method. The Spotify API in
/// Development Mode reads only the user's own and collaborative playlists.
pub available: bool,
pub already_imported_in: Option<i64>,
pub similar_to: Option<SimilarTo>,
}
impl PreviewPlaylist {
pub fn with_history(mut self, history: &[ImportedBefore]) -> Self {
let found = history_match(&self.source_key, self.kind, &self.title, history);
self.already_imported_in = found.already_imported_in;
self.similar_to = found.similar_to;
self
}
}
/// Counters cached on the import and its attempts.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ImportStatistics {
pub total: i64,
pub pending: i64,
pub matched_local: i64,
pub matched_federation: i64,
pub ambiguous: i64,
pub unmatched: i64,
pub unsupported: i64,
pub failed: i64,
pub published: i64,
pub publication_pending: i64,
pub duplicate: i64,
pub already_present: i64,
pub no_content_id: i64,
pub deferred_sync_limit: i64,
pub paused: i64,
pub publication_failed: i64,
/// Peer catalogues lost by the network search of the current or last attempt.
pub catalog_errors: i64,
}
impl ImportStatistics {
/// Adds `count` entries with the given resolution, origin and publication state.
pub fn add(
&mut self,
resolution: Option<ResolutionStatus>,
origin: Option<&str>,
publication: Option<PublicationStatus>,
count: i64,
) {
self.total += count;
match resolution {
Some(ResolutionStatus::Pending) | None => self.pending += count,
Some(ResolutionStatus::Matched) if origin == Some("federation") => {
self.matched_federation += count
}
Some(ResolutionStatus::Matched) => self.matched_local += count,
Some(ResolutionStatus::Ambiguous) => self.ambiguous += count,
Some(ResolutionStatus::Unmatched) => self.unmatched += count,
Some(ResolutionStatus::Unsupported) => self.unsupported += count,
Some(ResolutionStatus::Failed) => self.failed += count,
}
match publication {
Some(PublicationStatus::Published) => self.published += count,
Some(PublicationStatus::Pending) => self.publication_pending += count,
Some(PublicationStatus::Duplicate) => self.duplicate += count,
Some(PublicationStatus::AlreadyPresent) => self.already_present += count,
Some(PublicationStatus::NoContentId) => self.no_content_id += count,
Some(PublicationStatus::DeferredSyncLimit) => self.deferred_sync_limit += count,
Some(PublicationStatus::Paused) => self.paused += count,
Some(PublicationStatus::Failed) => self.publication_failed += count,
Some(PublicationStatus::NotReady) | None => {}
}
}
pub fn matched(&self) -> i64 {
self.matched_local + self.matched_federation
}
}
/// A source offered by `GET /api/imports/providers`.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ProviderInfo {
pub id: &'static str,
pub name: &'static str,
pub methods: Vec<SourceType>,
}
/// One import in the history list.
#[derive(Debug, Clone, Serialize)]
pub struct ImportSummary {
pub id: i64,
pub provider: String,
pub source_type: String,
pub status: String,
pub phase: Option<String>,
pub federated_search: bool,
pub cancel_requested: bool,
pub statistics: Value,
pub error: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub last_resync_at: Option<DateTime<Utc>>,
pub playlists: Vec<PlaylistLink>,
}
/// A target playlist link shown in the history list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlaylistLink {
pub id: i64,
pub title: String,
pub target_playlist_id: Option<i64>,
pub target_deleted: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct ImportDetail {
#[serde(flatten)]
pub summary: ImportSummary,
pub source_playlists: Vec<PlaylistView>,
pub attempt: Option<AttemptView>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PlaylistView {
pub id: i64,
pub kind: String,
pub ordinal: i32,
pub title: String,
pub description: Option<String>,
pub target_playlist_id: Option<i64>,
pub target_created_at: Option<DateTime<Utc>>,
pub target_deleted: bool,
pub publication_paused: bool,
pub total: i64,
pub matched: i64,
pub published: i64,
}
#[derive(Debug, Clone, Serialize)]
pub struct AttemptView {
pub id: i64,
pub kind: String,
pub status: String,
pub started_at: DateTime<Utc>,
pub finished_at: Option<DateTime<Utc>>,
pub statistics: Value,
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ItemView {
pub id: i64,
pub playlist_id: i64,
pub position: i32,
pub metadata: Value,
pub resolution_status: String,
pub resolution_note: Option<String>,
pub match_origin: Option<String>,
pub match_method: Option<String>,
pub match_score: Option<f32>,
pub matched_content_id: Option<String>,
pub matched_track_id: Option<i64>,
pub candidates: Option<Value>,
pub publication_status: String,
pub attempt_count: i32,
pub last_attempt_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ItemsPage {
pub items: Vec<ItemView>,
/// Cursor for the next page: `<playlist ordinal>.<source position>`.
pub next: Option<String>,
}
/// Position of an item in the import order, used as a pagination cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ItemCursor {
pub ordinal: i32,
pub position: i32,
}
impl ItemCursor {
pub fn encode(self) -> String {
format!("{}.{}", self.ordinal, self.position)
}
pub fn parse(value: &str) -> Option<Self> {
let (ordinal, position) = value.split_once('.')?;
let ordinal = ordinal.parse().ok()?;
let position = position.parse().ok()?;
(ordinal >= 0 && position >= 0).then_some(Self { ordinal, position })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn statuses_round_trip_through_text() {
for status in ImportStatus::ALL {
assert_eq!(status.as_str().parse::<ImportStatus>(), Ok(*status));
}
for status in PublicationStatus::ALL {
assert_eq!(status.as_str().parse::<PublicationStatus>(), Ok(*status));
}
assert_eq!(
serde_json::to_value(ResolutionStatus::Unsupported).unwrap(),
"unsupported"
);
assert!("publishing".parse::<PublicationStatus>().is_err());
}
#[test]
fn phases_resume_from_the_stored_phase() {
assert_eq!(
Phase::remaining(SourceType::File, None),
&[
Phase::ResolveLocal,
Phase::ResolveFederation,
Phase::Publish
]
);
assert_eq!(
Phase::remaining(SourceType::Api, Some(Phase::Publish)),
&[Phase::Publish]
);
// A file import never fetches; an unexpected stored phase restarts the sequence.
assert_eq!(
Phase::remaining(SourceType::File, Some(Phase::Fetching)),
Phase::sequence(SourceType::File)
);
}
#[test]
fn entries_without_usable_metadata_are_kept_as_unsupported() {
let track = ImportedTrack {
title: "Song".into(),
..ImportedTrack::default()
};
assert_eq!(
track.initial_resolution(),
(ResolutionStatus::Pending, None)
);
let untitled = ImportedTrack {
title: " ".into(),
..track.clone()
};
assert_eq!(
untitled.initial_resolution().0,
ResolutionStatus::Unsupported
);
let episode = ImportedTrack {
kind: TrackKind::Episode,
..track.clone()
};
assert_eq!(
episode.initial_resolution(),
(ResolutionStatus::Unsupported, Some("episode"))
);
let metadata = serde_json::to_value(track.metadata()).unwrap();
assert_eq!(metadata["kind"], "track");
assert!(metadata.get("source_id").is_none());
}
fn before(source_key: &str, kind: PlaylistKind, title: &str, import_id: i64) -> ImportedBefore {
ImportedBefore {
source_key: source_key.into(),
kind,
title: title.into(),
import_id,
target_playlist_id: Some(import_id * 10),
}
}
#[test]
fn history_separates_repeats_from_similar_playlists() {
let history = [
before("a", PlaylistKind::Playlist, "Road Trip", 3),
before("a", PlaylistKind::Playlist, "Road Trip", 5),
before("b", PlaylistKind::Playlist, "road-trip!", 7),
before("c", PlaylistKind::Favorites, "Liked Songs", 8),
];
let repeat = history_match("a", PlaylistKind::Playlist, "Renamed", &history);
assert_eq!(repeat.already_imported_in, Some(3));
assert_eq!(repeat.similar_to, None);
let similar = history_match("z", PlaylistKind::Playlist, " ROAD trip ", &history);
assert_eq!(similar.already_imported_in, None);
assert_eq!(
similar.similar_to,
Some(SimilarTo {
import_id: 7,
target_playlist_id: Some(70)
})
);
// The kind must match: a playlist called "Liked Songs" is not the favorites.
assert_eq!(
history_match("y", PlaylistKind::Playlist, "Liked Songs", &history),
HistoryMatch::default()
);
assert!(
history_match("y", PlaylistKind::Favorites, "Liked songs", &history)
.similar_to
.is_some()
);
// Titles without letters still compare.
assert_eq!(title_key(" 🔥🔥 "), "🔥🔥");
}
#[test]
fn artist_key_skips_empty_names() {
let track = ImportedTrack {
artists: vec![" ".into(), "Björk".into()],
..ImportedTrack::default()
};
assert_eq!(artist_key(&track).as_deref(), Some("björk"));
assert_eq!(artist_key(&ImportedTrack::default()), None);
}
#[test]
fn statistics_split_matches_by_origin() {
let mut stats = ImportStatistics::default();
stats.add(
Some(ResolutionStatus::Matched),
Some("federation"),
Some(PublicationStatus::Published),
3,
);
stats.add(
Some(ResolutionStatus::Matched),
Some("local"),
Some(PublicationStatus::Duplicate),
2,
);
stats.add(
Some(ResolutionStatus::Unmatched),
None,
Some(PublicationStatus::NotReady),
5,
);
assert_eq!(stats.total, 10);
assert_eq!(stats.matched(), 5);
assert_eq!(stats.published, 3);
assert_eq!(stats.duplicate, 2);
assert_eq!(stats.unmatched, 5);
}
#[test]
fn item_cursor_rejects_malformed_values() {
let cursor = ItemCursor {
ordinal: 2,
position: 41,
};
assert_eq!(ItemCursor::parse(&cursor.encode()), Some(cursor));
for value in ["", "1", "a.b", "-1.0", "1.-2", "1.2.3"] {
assert_eq!(ItemCursor::parse(value), None, "{value}");
}
}
}
+281
View File
@@ -0,0 +1,281 @@
//! Network integrations of providers: OAuth, API clients and the in-memory
//! token vault. File exports do not need anything here.
pub mod spotify_api;
use std::collections::HashMap;
use std::fmt;
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};
use super::model::{ImportedTrack, PlaylistKind};
/// Longest time an access token is kept. Tokens live only in this process:
/// not in the database, not in the session and never on devices.
pub const TOKEN_TTL: Duration = Duration::from_secs(30 * 60);
/// A provider access token. `Debug` never shows the value.
#[derive(Clone, PartialEq, Eq)]
pub struct AccessToken(String);
impl AccessToken {
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
pub fn secret(&self) -> &str {
&self.0
}
}
impl fmt::Debug for AccessToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AccessToken(<redacted>)")
}
}
/// A signed-in provider account, before or after an import was created.
#[derive(Debug, Clone)]
pub struct Connection {
pub provider: String,
pub account_ref: String,
pub token: AccessToken,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum VaultKey {
/// A random handle kept in the user's session until an import is created.
Handle(String),
/// The token an import fetches its playlists with.
Import(i64),
}
#[derive(Debug)]
struct VaultEntry {
user_id: i64,
connection: Connection,
expires_at: Instant,
}
/// Process-wide store of provider access tokens with a short lifetime.
#[derive(Debug, Default)]
pub struct TokenVault {
entries: Mutex<HashMap<VaultKey, VaultEntry>>,
}
impl TokenVault {
pub fn shared() -> &'static Self {
static VAULT: LazyLock<TokenVault> = LazyLock::new(TokenVault::default);
&VAULT
}
fn with_entries<T>(&self, action: impl FnOnce(&mut HashMap<VaultKey, VaultEntry>) -> T) -> T {
let mut entries = self
.entries
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let now = Instant::now();
entries.retain(|_, entry| entry.expires_at > now);
action(&mut entries)
}
fn entry(user_id: i64, connection: Connection, lifetime: Duration) -> VaultEntry {
VaultEntry {
user_id,
connection,
expires_at: Instant::now() + lifetime.min(TOKEN_TTL),
}
}
/// Keeps a fresh sign-in under a new random handle for the user's session.
pub fn connect(&self, user_id: i64, connection: Connection, lifetime: Duration) -> String {
let handle = random_secret();
self.with_entries(|entries| {
entries.insert(
VaultKey::Handle(handle.clone()),
Self::entry(user_id, connection, lifetime),
)
});
handle
}
/// The sign-in behind a session handle, only for the user who made it.
pub fn connection(&self, user_id: i64, handle: &str) -> Option<Connection> {
self.with_entries(|entries| {
entries
.get(&VaultKey::Handle(handle.to_owned()))
.filter(|entry| entry.user_id == user_id)
.map(|entry| entry.connection.clone())
})
}
/// Moves a session sign-in to the import created with it.
pub fn attach(&self, user_id: i64, handle: &str, import_id: i64) -> bool {
self.with_entries(|entries| {
let key = VaultKey::Handle(handle.to_owned());
if entries
.get(&key)
.is_none_or(|entry| entry.user_id != user_id)
{
return false;
}
let entry = entries.remove(&key).expect("checked above");
entries.insert(VaultKey::Import(import_id), entry);
true
})
}
/// Stores the token of a repeated sign-in for an import that waits for it.
pub fn store_for_import(
&self,
user_id: i64,
import_id: i64,
connection: Connection,
lifetime: Duration,
) {
self.with_entries(|entries| {
entries.insert(
VaultKey::Import(import_id),
Self::entry(user_id, connection, lifetime),
)
});
}
pub fn import_token(&self, import_id: i64) -> Option<AccessToken> {
self.with_entries(|entries| {
entries
.get(&VaultKey::Import(import_id))
.map(|entry| entry.connection.token.clone())
})
}
pub fn forget_import(&self, import_id: i64) {
self.with_entries(|entries| entries.remove(&VaultKey::Import(import_id)));
}
pub fn forget_handle(&self, handle: &str) {
self.with_entries(|entries| entries.remove(&VaultKey::Handle(handle.to_owned())));
}
}
/// A random URL-safe secret for OAuth state and session handles.
pub fn random_secret() -> String {
openidconnect::CsrfToken::new_random().secret().clone()
}
/// A stored source playlist whose entries an API import still has to fetch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchTarget {
pub kind: PlaylistKind,
pub source_playlist_id: Option<String>,
}
/// Why a provider request did not return data. Never carries response bodies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchError {
/// The token expired or was revoked: the user signs in again.
Unauthorized,
/// The provider refuses this playlist (Spotify Development Mode).
Forbidden,
NotFound,
/// Rate limits did not clear in time.
RateLimited,
Failed(String),
}
impl fmt::Display for FetchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unauthorized => f.write_str("provider authorization expired"),
Self::Forbidden => f.write_str("provider refused access"),
Self::NotFound => f.write_str("provider resource not found"),
Self::RateLimited => f.write_str("provider rate limit"),
Self::Failed(reason) => write!(f, "provider request failed: {reason}"),
}
}
}
impl std::error::Error for FetchError {}
/// Reads the entries of one stored playlist from its provider.
#[async_trait::async_trait]
pub trait LibraryFetcher: Send + Sync {
async fn fetch_playlist(
&self,
provider: &str,
token: &AccessToken,
target: &FetchTarget,
) -> Result<Vec<ImportedTrack>, FetchError>;
}
/// The fetcher used by the background job.
pub struct ProviderFetchers;
#[async_trait::async_trait]
impl LibraryFetcher for ProviderFetchers {
async fn fetch_playlist(
&self,
provider: &str,
token: &AccessToken,
target: &FetchTarget,
) -> Result<Vec<ImportedTrack>, FetchError> {
match provider {
spotify_api::PROVIDER => {
spotify_api::SpotifyClient::new()?
.tracks(token, target)
.await
}
_ => Err(FetchError::Failed(
"provider has no API integration".to_owned(),
)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn connection(token: &str) -> Connection {
Connection {
provider: "spotify".into(),
account_ref: "account".into(),
token: AccessToken::new(token),
}
}
#[test]
fn tokens_are_redacted_in_debug_output() {
let text = format!("{:?}", connection("BQD-secret"));
assert!(!text.contains("BQD-secret"), "{text}");
}
#[test]
fn handles_belong_to_their_user_and_move_to_the_import() {
let vault = TokenVault::default();
let handle = vault.connect(1, connection("t1"), TOKEN_TTL);
assert!(vault.connection(2, &handle).is_none());
assert!(!vault.attach(2, &handle, 10));
assert_eq!(
vault.connection(1, &handle).unwrap().token,
AccessToken::new("t1")
);
assert!(vault.attach(1, &handle, 10));
assert!(vault.connection(1, &handle).is_none());
assert_eq!(vault.import_token(10), Some(AccessToken::new("t1")));
vault.forget_import(10);
assert_eq!(vault.import_token(10), None);
}
#[test]
fn expired_tokens_are_dropped() {
let vault = TokenVault::default();
vault.store_for_import(1, 5, connection("t"), Duration::ZERO);
assert_eq!(vault.import_token(5), None);
let handle = vault.connect(1, connection("t"), Duration::from_secs(24 * 3600));
// Lifetimes are capped by the vault TTL.
let expires_at =
vault.with_entries(|entries| entries[&VaultKey::Handle(handle.clone())].expires_at);
assert!(expires_at <= Instant::now() + TOKEN_TTL);
}
}
+704
View File
@@ -0,0 +1,704 @@
//! Optional Spotify Web API integration (plan §4.3).
//!
//! The administrator sets `spotify_client_id` (and, behind a proxy,
//! `spotify_redirect_uri`). Sign-in is Authorization Code with PKCE, so no
//! client secret exists. The OAuth state, the PKCE verifier and the import a
//! repeated sign-in belongs to are one record in the session; the access
//! token lives only in [`TokenVault`](super::TokenVault).
//!
//! Development Mode applications read items only of the user's own and
//! collaborative playlists; other playlists are offered through the data
//! export. Requests run one at a time, honor `Retry-After` and back off on
//! server errors. Tokens, codes, states and verifiers are never logged.
use std::sync::LazyLock;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{AccessToken, FetchError, FetchTarget, random_secret};
use crate::config::AppConfig;
use crate::library_import::adapters::spotify_export::FAVORITES_TITLE;
use crate::library_import::adapters::version_hint;
use crate::library_import::model::{ImportedTrack, PlaylistKind, PreviewPlaylist, TrackKind};
pub const PROVIDER: &str = "spotify";
pub const CALLBACK_PATH: &str = "/api/imports/providers/spotify/callback";
pub const SCOPES: &str = "playlist-read-private playlist-read-collaborative user-library-read";
/// Session record of a sign-in in progress.
pub const SESSION_AUTH: &str = "library_import_spotify_auth";
/// Session handle of the signed-in account in the vault.
pub const SESSION_HANDLE: &str = "library_import_spotify_handle";
const AUTHORIZE_URL: &str = "https://accounts.spotify.com/authorize";
const TOKEN_URL: &str = "https://accounts.spotify.com/api/token";
const API_BASE: &str = "https://api.spotify.com/v1";
/// How long the user may stay on the Spotify consent page.
const STATE_TTL_SECONDS: i64 = 10 * 60;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
const MAX_RATE_LIMIT_RETRIES: u32 = 6;
const MAX_SERVER_ERROR_RETRIES: u32 = 5;
/// Longer waits (daily quotas) fail the request instead of holding the worker.
const MAX_RETRY_AFTER: Duration = Duration::from_secs(300);
const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(5);
const PAGE_LIMIT: usize = 50;
/// Upper bound of followed `next` links: 100 000 entries per list.
const MAX_PAGES: usize = 2000;
/// Whether the administrator enabled the API path.
pub fn is_configured(config: &AppConfig) -> bool {
!config.spotify_client_id.trim().is_empty()
}
/// The configured redirect URI, or the callback on the request origin.
pub fn redirect_uri(config: &AppConfig, origin: &str) -> String {
let configured = config.spotify_redirect_uri.trim();
if configured.is_empty() {
format!("{}{CALLBACK_PATH}", origin.trim_end_matches('/'))
} else {
configured.to_owned()
}
}
/// Spotify accepts HTTPS redirect URIs and plain HTTP only for loopback IPs.
pub fn validate_redirect_uri(uri: &str) -> Result<(), &'static str> {
if uri.is_empty() {
return Ok(());
}
let parsed =
reqwest::Url::parse(uri).map_err(|_| "Spotify redirect URI must be an absolute URL")?;
let loopback = matches!(parsed.host_str(), Some("127.0.0.1" | "[::1]"));
match parsed.scheme() {
"https" if parsed.host_str().is_some_and(|host| host != "localhost") => {}
"http" if loopback => {}
_ => {
return Err(
"Spotify redirect URI must use HTTPS (HTTP only for 127.0.0.1 or [::1]), not localhost",
);
}
}
if parsed.fragment().is_some() {
return Err("Spotify redirect URI must not contain a fragment");
}
Ok(())
}
/// A sign-in in progress, stored in the session. The import id binds a
/// repeated sign-in to the import that waits for it; the callback takes it
/// from here, never from the URL.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthState {
state: String,
verifier: String,
redirect_uri: String,
created_at: i64,
import_id: Option<i64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthStateError {
Mismatch,
Expired,
}
impl AuthState {
/// Starts a sign-in and returns the record with the authorization URL.
pub fn begin(
client_id: &str,
redirect_uri: String,
import_id: Option<i64>,
now: i64,
) -> (Self, String) {
let (challenge, verifier) = openidconnect::PkceCodeChallenge::new_random_sha256();
let state = random_secret();
let mut url = reqwest::Url::parse(AUTHORIZE_URL).expect("valid authorize URL");
url.query_pairs_mut()
.append_pair("client_id", client_id)
.append_pair("response_type", "code")
.append_pair("redirect_uri", &redirect_uri)
.append_pair("code_challenge_method", "S256")
.append_pair("code_challenge", challenge.as_str())
.append_pair("state", &state)
.append_pair("scope", SCOPES);
(
Self {
state,
verifier: verifier.secret().clone(),
redirect_uri,
created_at: now,
import_id,
},
url.into(),
)
}
/// Checks the returned state; the record is single-use and removed by the caller.
pub fn verify(&self, state: &str, now: i64) -> Result<(), AuthStateError> {
if state.is_empty() || state != self.state {
return Err(AuthStateError::Mismatch);
}
if now - self.created_at > STATE_TTL_SECONDS || now < self.created_at {
return Err(AuthStateError::Expired);
}
Ok(())
}
pub fn import_id(&self) -> Option<i64> {
self.import_id
}
pub fn redirect_uri(&self) -> &str {
&self.redirect_uri
}
pub fn verifier(&self) -> &str {
&self.verifier
}
}
/// What to do after a failed response.
fn retry_delay(status: u16, retry_after: Option<&str>, attempt: u32) -> Option<Duration> {
match status {
429 if attempt < MAX_RATE_LIMIT_RETRIES => {
let delay = retry_after
.and_then(|value| value.trim().parse::<u64>().ok())
.map_or(DEFAULT_RETRY_AFTER, Duration::from_secs);
(delay <= MAX_RETRY_AFTER).then_some(delay.max(Duration::from_secs(1)))
}
500..=599 if attempt < MAX_SERVER_ERROR_RETRIES => {
Some(Duration::from_secs(1u64 << attempt))
}
_ => None,
}
}
fn status_error(status: u16) -> FetchError {
match status {
401 => FetchError::Unauthorized,
403 => FetchError::Forbidden,
404 => FetchError::NotFound,
429 => FetchError::RateLimited,
_ => FetchError::Failed(format!("HTTP {status}")),
}
}
/// A granted access token and its lifetime.
pub struct GrantedToken {
pub token: AccessToken,
pub expires_in: Duration,
}
pub struct SpotifyClient {
http: reqwest::Client,
}
impl SpotifyClient {
pub fn new() -> Result<Self, FetchError> {
static HTTP: LazyLock<Option<reqwest::Client>> = LazyLock::new(|| {
reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.redirect(reqwest::redirect::Policy::none())
.user_agent(concat!("furumi/", env!("CARGO_PKG_VERSION")))
.build()
.ok()
});
HTTP.clone()
.map(|http| Self { http })
.ok_or_else(|| FetchError::Failed("HTTP client unavailable".to_owned()))
}
/// Exchanges the authorization code with the PKCE verifier.
pub async fn exchange_code(
&self,
client_id: &str,
code: &str,
auth: &AuthState,
) -> Result<GrantedToken, FetchError> {
#[derive(Deserialize)]
struct TokenResponse {
access_token: String,
#[serde(default)]
expires_in: Option<u64>,
}
let response = self
.http
.post(TOKEN_URL)
.form(&[
("grant_type", "authorization_code"),
("code", code),
("redirect_uri", auth.redirect_uri()),
("client_id", client_id),
("code_verifier", auth.verifier()),
])
.send()
.await
.map_err(|error| FetchError::Failed(request_failure(&error)))?;
let status = response.status().as_u16();
if !response.status().is_success() {
tracing::warn!(status, "Spotify token exchange failed");
// An invalid or reused code is answered with 400.
return Err(if status == 400 {
FetchError::Unauthorized
} else {
status_error(status)
});
}
let body: TokenResponse = response
.json()
.await
.map_err(|_| FetchError::Failed("invalid token response".to_owned()))?;
Ok(GrantedToken {
token: AccessToken::new(body.access_token),
expires_in: Duration::from_secs(body.expires_in.unwrap_or(3600)),
})
}
/// The Spotify user id of the token's account.
pub async fn account_id(&self, token: &AccessToken) -> Result<String, FetchError> {
let me = self.get(token, &format!("{API_BASE}/me")).await?;
me.get("id")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.map(str::to_owned)
.ok_or_else(|| FetchError::Failed("profile without an id".to_owned()))
}
/// The account's playlists for the wizard, favorites first.
pub async fn playlists(
&self,
token: &AccessToken,
account_id: &str,
) -> Result<Vec<PreviewPlaylist>, FetchError> {
let saved = self
.get(token, &format!("{API_BASE}/me/tracks?limit=1"))
.await?;
let mut playlists = vec![favorites_preview(account_id, total(&saved))];
let url = format!("{API_BASE}/me/playlists?limit={PAGE_LIMIT}");
for item in self.pages(token, url).await? {
if let Some(playlist) = playlist_preview(&item, account_id) {
playlists.push(playlist);
}
}
Ok(playlists)
}
/// All entries of a playlist or of the saved tracks, in source order.
pub async fn tracks(
&self,
token: &AccessToken,
target: &FetchTarget,
) -> Result<Vec<ImportedTrack>, FetchError> {
let url = match target.kind {
PlaylistKind::Favorites => format!("{API_BASE}/me/tracks?limit={PAGE_LIMIT}"),
PlaylistKind::Playlist => {
let id = target
.source_playlist_id
.as_deref()
.and_then(|uri| uri.strip_prefix("spotify:playlist:"))
.filter(|id| id.chars().all(|c| c.is_ascii_alphanumeric()) && !id.is_empty())
.ok_or(FetchError::NotFound)?;
format!(
"{API_BASE}/playlists/{id}/items?limit={PAGE_LIMIT}&additional_types=track,episode"
)
}
};
Ok(self
.pages(token, url)
.await?
.iter()
.enumerate()
.map(|(position, item)| api_track(position, item))
.collect())
}
/// Follows `next` links on the API host and returns every `items` entry.
async fn pages(&self, token: &AccessToken, first: String) -> Result<Vec<Value>, FetchError> {
let mut items = Vec::new();
let mut next = Some(first);
let mut pages = 0;
while let Some(url) = next.take() {
pages += 1;
if pages > MAX_PAGES {
return Err(FetchError::Failed("too many pages".to_owned()));
}
let mut page = self.get(token, &url).await?;
if let Some(Value::Array(page_items)) = page.get_mut("items").map(Value::take) {
items.extend(page_items);
}
next = page
.get("next")
.and_then(Value::as_str)
.filter(|url| url.starts_with(&format!("{API_BASE}/")))
.map(str::to_owned);
}
Ok(items)
}
/// GET with the token, honoring `Retry-After` and retrying server errors.
async fn get(&self, token: &AccessToken, url: &str) -> Result<Value, FetchError> {
let mut attempt = 0;
loop {
let (status, retry_after) =
match self.http.get(url).bearer_auth(token.secret()).send().await {
Ok(response) if response.status().is_success() => {
return response
.json()
.await
.map_err(|_| FetchError::Failed("invalid API response".to_owned()));
}
Ok(response) => (
response.status().as_u16(),
response
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|value| value.to_str().ok())
.map(str::to_owned),
),
// Timeouts and connection errors are retried like server errors.
Err(error) => {
tracing::debug!(reason = request_failure(&error), "Spotify request failed");
(503, None)
}
};
match retry_delay(status, retry_after.as_deref(), attempt) {
Some(delay) => {
tracing::info!(
status,
delay_seconds = delay.as_secs(),
"Spotify request postponed"
);
tokio::time::sleep(delay).await;
attempt += 1;
}
None => {
tracing::warn!(status, "Spotify request failed");
return Err(status_error(status));
}
}
}
}
}
/// Error kind without the URL, which may carry ids.
fn request_failure(error: &reqwest::Error) -> String {
if error.is_timeout() {
"timeout".to_owned()
} else if error.is_connect() {
"connection failed".to_owned()
} else {
"request failed".to_owned()
}
}
fn total(page: &Value) -> usize {
page.get("total")
.and_then(Value::as_u64)
.and_then(|total| usize::try_from(total).ok())
.unwrap_or(0)
}
fn text(value: Option<&Value>) -> Option<String> {
value
.and_then(Value::as_str)
.map(str::trim)
.filter(|text| !text.is_empty())
.map(str::to_owned)
}
/// `source_key` of the saved tracks: Spotify's own URI of the collection.
pub fn favorites_key(account_id: &str) -> String {
format!("spotify:user:{account_id}:collection")
}
fn favorites_preview(account_id: &str, count: usize) -> PreviewPlaylist {
PreviewPlaylist {
source_key: favorites_key(account_id),
kind: PlaylistKind::Favorites,
title: FAVORITES_TITLE.to_owned(),
description: None,
track_count: count,
unsupported_count: None,
available: true,
already_imported_in: None,
similar_to: None,
}
}
/// A playlist from `GET /me/playlists`. Items are readable in Development
/// Mode only for the user's own and collaborative playlists.
fn playlist_preview(item: &Value, account_id: &str) -> Option<PreviewPlaylist> {
let id = text(item.get("id"))?;
let owner = item
.get("owner")
.and_then(|owner| owner.get("id"))
.and_then(Value::as_str);
let collaborative = item
.get("collaborative")
.and_then(Value::as_bool)
.unwrap_or(false);
// The list object was called `tracks` before the 2026 API migration.
let count = item
.get("items")
.or_else(|| item.get("tracks"))
.map_or(0, total);
Some(PreviewPlaylist {
source_key: format!("spotify:playlist:{id}"),
kind: PlaylistKind::Playlist,
title: text(item.get("name")).unwrap_or_default(),
description: text(item.get("description")),
track_count: count,
unsupported_count: None,
available: owner == Some(account_id) || collaborative,
already_imported_in: None,
similar_to: None,
})
}
/// An entry of a playlist (`item`, formerly `track`) or of the saved tracks (`track`).
fn api_track(position: usize, entry: &Value) -> ImportedTrack {
let mut track = ImportedTrack {
kind: TrackKind::Unknown,
position: u32::try_from(position).unwrap_or(u32::MAX),
..ImportedTrack::default()
};
let Some(object) = ["item", "track"]
.iter()
.filter_map(|key| entry.get(*key))
.find(|value| value.is_object())
else {
return track;
};
let uri = text(object.get("uri"));
let is_local = object
.get("is_local")
.and_then(Value::as_bool)
.unwrap_or(false)
|| uri
.as_deref()
.is_some_and(|uri| uri.starts_with("spotify:local:"));
track.title = text(object.get("name")).unwrap_or_default();
track.duration_ms = object.get("duration_ms").and_then(Value::as_u64);
track.album = text(object.get("album").and_then(|album| album.get("name")));
match object.get("type").and_then(Value::as_str) {
_ if is_local => {
track.kind = TrackKind::LocalFile;
track.artists = artist_names(object);
}
Some("episode") => {
track.kind = TrackKind::Episode;
track.artists = text(object.get("show").and_then(|show| show.get("name")))
.into_iter()
.collect();
track.album = None;
track.source_id = uri;
}
Some("track") | None => {
track.kind = TrackKind::Track;
track.artists = artist_names(object);
track.isrc = text(object.get("external_ids").and_then(|ids| ids.get("isrc")));
track.version_hint = version_hint(&track.title);
track.source_id = uri;
}
Some(_) => {}
}
track
}
fn artist_names(object: &Value) -> Vec<String> {
object
.get("artists")
.and_then(Value::as_array)
.map(|artists| {
artists
.iter()
.filter_map(|artist| text(artist.get("name")))
.collect()
})
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::library_import::model::ResolutionStatus;
use serde_json::json;
#[test]
fn redirect_uris_follow_spotify_rules() {
for ok in [
"",
"https://music.example.org/api/imports/providers/spotify/callback",
"http://127.0.0.1:8080/api/imports/providers/spotify/callback",
"http://[::1]:8080/cb",
] {
assert!(validate_redirect_uri(ok).is_ok(), "{ok}");
}
for bad in [
"music.example.org/callback",
"http://music.example.org/callback",
"http://localhost:8080/callback",
"https://localhost/callback",
"https://example.org/cb#x",
"ftp://example.org/cb",
] {
assert!(validate_redirect_uri(bad).is_err(), "{bad}");
}
let mut config = AppConfig::default();
assert_eq!(
redirect_uri(&config, "https://music.example.org/"),
"https://music.example.org/api/imports/providers/spotify/callback"
);
config.spotify_redirect_uri = " https://proxy.example.org/cb ".into();
assert_eq!(
redirect_uri(&config, "http://internal:3000"),
"https://proxy.example.org/cb"
);
}
#[test]
fn sign_in_state_is_single_purpose_and_expires() {
let (auth, url) =
AuthState::begin("client123", "https://a.example/cb".into(), Some(42), 1000);
let url = reqwest::Url::parse(&url).unwrap();
let query: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect();
assert_eq!(url.host_str(), Some("accounts.spotify.com"));
assert_eq!(query["client_id"], "client123");
assert_eq!(query["code_challenge_method"], "S256");
assert_eq!(query["redirect_uri"], "https://a.example/cb");
assert_eq!(query["scope"], SCOPES);
assert_eq!(query["state"], auth.state);
// The verifier stays on the server; only its challenge is sent.
assert!(!url.as_str().contains(&auth.verifier));
assert!(!query.contains_key("import_id"));
assert_eq!(auth.verify(&auth.state.clone(), 1000 + 600), Ok(()));
assert_eq!(auth.import_id(), Some(42));
assert_eq!(auth.verify("forged", 1001), Err(AuthStateError::Mismatch));
assert_eq!(auth.verify("", 1001), Err(AuthStateError::Mismatch));
assert_eq!(
auth.verify(&auth.state.clone(), 1000 + 601),
Err(AuthStateError::Expired)
);
let (other, _) = AuthState::begin("client123", "https://a.example/cb".into(), None, 1000);
assert_ne!(other.state, auth.state);
assert_ne!(other.verifier, auth.verifier);
// The record round-trips through the session store.
let stored: AuthState =
serde_json::from_value(serde_json::to_value(&auth).unwrap()).unwrap();
assert_eq!(stored, auth);
}
#[test]
fn retries_follow_retry_after_and_back_off() {
assert_eq!(retry_delay(429, Some("7"), 0), Some(Duration::from_secs(7)));
assert_eq!(retry_delay(429, Some("0"), 0), Some(Duration::from_secs(1)));
assert_eq!(retry_delay(429, None, 2), Some(DEFAULT_RETRY_AFTER));
assert_eq!(retry_delay(429, Some("soon"), 0), Some(DEFAULT_RETRY_AFTER));
// A daily quota is not waited out by the worker.
assert_eq!(retry_delay(429, Some("86400"), 0), None);
assert_eq!(retry_delay(429, Some("1"), MAX_RATE_LIMIT_RETRIES), None);
assert_eq!(retry_delay(502, None, 0), Some(Duration::from_secs(1)));
assert_eq!(retry_delay(503, None, 3), Some(Duration::from_secs(8)));
assert_eq!(retry_delay(500, None, MAX_SERVER_ERROR_RETRIES), None);
for status in [400, 401, 403, 404] {
assert_eq!(retry_delay(status, Some("1"), 0), None);
}
assert_eq!(status_error(401), FetchError::Unauthorized);
assert_eq!(status_error(403), FetchError::Forbidden);
assert_eq!(status_error(429), FetchError::RateLimited);
assert_eq!(status_error(418), FetchError::Failed("HTTP 418".into()));
}
#[test]
fn api_entries_become_imported_tracks() {
let track = api_track(
3,
&json!({
"added_at": "2026-01-01T00:00:00Z",
"item": {
"type": "track",
"name": "Paranoid Android - Remastered",
"uri": "spotify:track:6LgJvl0Xdtc73RJ1mmpotq",
"duration_ms": 383_000,
"is_local": false,
"artists": [{"name": "Radiohead"}, {"name": " "}, {"id": "x"}],
"album": {"name": "OK Computer"},
"external_ids": {"isrc": "GBAYE9700131"}
}
}),
);
assert_eq!(track.kind, TrackKind::Track);
assert_eq!(track.position, 3);
assert_eq!(track.artists, ["Radiohead"]);
assert_eq!(track.album.as_deref(), Some("OK Computer"));
assert_eq!(track.duration_ms, Some(383_000));
assert_eq!(track.isrc.as_deref(), Some("GBAYE9700131"));
assert_eq!(track.version_hint.as_deref(), Some("Remastered"));
assert_eq!(
track.source_id.as_deref(),
Some("spotify:track:6LgJvl0Xdtc73RJ1mmpotq")
);
// Saved tracks and pre-migration playlist items use `track`.
let saved = api_track(
0,
&json!({"track": {"name": "Teardrop", "artists": [{"name": "Massive Attack"}]}}),
);
assert_eq!(saved.kind, TrackKind::Track);
assert_eq!(saved.title, "Teardrop");
let episode = api_track(
1,
&json!({"item": {"type": "episode", "name": "Ep 1", "show": {"name": "Show"}, "uri": "spotify:episode:1"}}),
);
assert_eq!(episode.kind, TrackKind::Episode);
assert_eq!(episode.artists, ["Show"]);
assert_eq!(
episode.initial_resolution().0,
ResolutionStatus::Unsupported
);
let local = api_track(
2,
&json!({"track": {"type": "track", "is_local": true, "name": "Demo", "uri": "spotify:local:a:b:Demo:10"}}),
);
assert_eq!(local.kind, TrackKind::LocalFile);
assert_eq!(local.source_id, None);
// Removed tracks come back as null and are kept as unsupported entries.
let removed = api_track(4, &json!({"item": null, "track": null}));
assert_eq!(removed.kind, TrackKind::Unknown);
assert_eq!(removed.position, 4);
assert_eq!(api_track(5, &json!("garbage")).kind, TrackKind::Unknown);
}
#[test]
fn playlist_list_marks_unreadable_playlists() {
let own = playlist_preview(
&json!({"id": "abc", "name": "Mine", "owner": {"id": "me"}, "collaborative": false, "items": {"total": 12}}),
"me",
)
.unwrap();
assert_eq!(own.source_key, "spotify:playlist:abc");
assert_eq!(own.track_count, 12);
assert!(own.available);
let shared = playlist_preview(
&json!({"id": "def", "name": "Shared", "owner": {"id": "other"}, "collaborative": true, "tracks": {"total": 3}}),
"me",
)
.unwrap();
assert!(shared.available);
assert_eq!(shared.track_count, 3);
let followed = playlist_preview(
&json!({"id": "ghi", "name": "Editorial", "owner": {"id": "spotify"}}),
"me",
)
.unwrap();
assert!(!followed.available);
assert!(playlist_preview(&json!({"name": "no id"}), "me").is_none());
let favorites = favorites_preview("me", 40);
assert_eq!(favorites.source_key, "spotify:user:me:collection");
assert_eq!(favorites.kind, PlaylistKind::Favorites);
}
}
File diff suppressed because it is too large. Load diff
+912
View File
@@ -0,0 +1,912 @@
//! Resolver (plan §6). Stages 1–2 match against the local library and the
//! federated tracks this server already knows; neither touches the network.
//! Stage 3 ([`federated`]) searches artist catalogues of peers and reaches the
//! network only through [`FederationAccess`], so an import without consent
//! provably makes no network calls.
//!
//! Library SQL lives here; the import tables are written by `store.rs`.
use std::collections::{BTreeSet, HashMap, HashSet};
use std::time::Duration;
use anyhow::Result;
use music_dht::device_sync::SyncedFedTrack;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::{PgPool, Row};
use super::matcher::{
self, Candidate, Decision, KnownArtists, NameKey, Origin, PreparedCandidate, PreparedSource,
Ranked, Source,
};
use super::model::{ItemMetadata, PublicationStatus, ResolutionStatus};
use super::store::{AMBIGUOUS_LOCAL, PendingEntry, Resolution};
use crate::federation::client::CatalogStream;
mod federated;
pub use federated::{FEDERATION_BUDGET, FEDERATION_UNAVAILABLE, GroupOutcome, NetworkSearch};
/// The network side of the resolver.
#[async_trait::async_trait]
pub trait FederationAccess: Send + Sync {
/// Whether the federation node runs and can search the network.
async fn is_running(&self) -> bool;
/// Catalogues of the peers offering `name`, at most `max_parallel`
/// requests at a time. `None` when the node is not running.
async fn artist_catalogs(&self, name: &str, max_parallel: usize) -> Option<CatalogStream>;
/// Limits of the network stage.
fn limits(&self) -> NetworkLimits {
NetworkLimits::default()
}
}
/// The process-wide federation node.
pub struct NodeFederation;
#[async_trait::async_trait]
impl FederationAccess for NodeFederation {
async fn is_running(&self) -> bool {
crate::federation::handle().is_running().await
}
async fn artist_catalogs(&self, name: &str, max_parallel: usize) -> Option<CatalogStream> {
crate::federation::handle()
.artist_catalogs_bounded(name, max_parallel)
.await
.ok()
}
}
/// Limits of resolver stage 3 (plan §6). Together with the process-wide
/// limit of two artist groups, imports run at most two searches and eight
/// catalogue requests at a time.
#[derive(Debug, Clone)]
pub struct NetworkLimits {
/// Catalogue requests of one lookup running at once.
pub catalog_requests: usize,
/// Time for all lookups of one artist group, retries included.
pub group_timeout: Duration,
/// Waits before repeating a failed search; the group is skipped after the last.
pub backoff: Vec<Duration>,
/// Artist groups searched per pass.
pub max_groups: usize,
/// Time for the network stage of one pass.
pub max_duration: Duration,
/// How often a running group checks for cancellation and lease loss.
pub poll: Duration,
}
impl Default for NetworkLimits {
fn default() -> Self {
Self {
catalog_requests: 4,
group_timeout: Duration::from_secs(60),
backoff: vec![
Duration::from_secs(2),
Duration::from_secs(4),
Duration::from_secs(8),
],
max_groups: 500,
max_duration: Duration::from_secs(30 * 60),
poll: Duration::from_secs(1),
}
}
}
/// Up to this many artist names are looked up by name patterns.
const ARTIST_PATTERNS: usize = 300;
/// Library tracks found by title for an entry whose artist is not in the library.
const TITLE_CANDIDATES: i64 = 20;
/// Entries resolved and written together.
const MAX_GROUP: usize = 500;
/// Drops combining diacritical marks in SQL, like [`matcher::folded`].
const FOLD_SQL: &str = "'[\\u0300-\\u036f]'";
/// A pending entry with its prepared source.
pub struct Entry {
pub id: i64,
raw: Source,
source: PreparedSource,
/// Why stages 1–2 found nothing, for an entry waiting for the network,
/// or [`AMBIGUOUS_LOCAL`].
note: Option<String>,
/// The candidates of stages 1–2 of an entry waiting as ambiguous.
candidates: Option<Value>,
}
/// Entries of one resolver pass, grouped by their main artist.
pub struct Prepared {
pub resolver: Resolver,
pub groups: Vec<Vec<Entry>>,
/// Entries whose stored metadata cannot be read.
pub invalid: Vec<Resolution>,
}
#[derive(Debug, Clone)]
struct LocalTrack {
track_id: i64,
media_file_id: i64,
content_id: Option<String>,
candidate: Candidate,
}
struct KnownTrack {
fed: SyncedFedTrack,
candidate: Candidate,
prepared: PreparedCandidate,
}
/// Lookups shared by all groups of one pass.
pub struct Resolver {
known: KnownArtists,
/// Library artist ids by name key and folded key.
artist_ids: HashMap<String, Vec<i64>>,
federated: Vec<KnownTrack>,
/// Indexes into `federated` by artist key and folded key.
federated_by_artist: HashMap<String, Vec<usize>>,
storage_dir: String,
}
fn keys_of(name: &str) -> impl Iterator<Item = String> {
let name = NameKey::new(name);
let folded = (name.folded != name.key).then_some(name.folded);
std::iter::once(name.key).chain(folded)
}
impl Resolver {
/// Reads the pending entries and loads the library artists and the known
/// federated tracks of their artists.
pub async fn prepare(
pool: &PgPool,
user_id: i64,
entries: Vec<PendingEntry>,
storage_dir: String,
) -> Result<Prepared> {
let mut parsed = Vec::with_capacity(entries.len());
let mut invalid = Vec::new();
for entry in entries {
match serde_json::from_value::<ItemMetadata>(entry.metadata) {
Ok(metadata) if !metadata.title.trim().is_empty() => {
parsed.push((
entry.id,
entry.artist_key,
(entry.note, entry.candidates),
metadata,
));
}
_ => invalid.push(Resolution::failed(entry.id, "invalid_metadata")),
}
}
let mut names = BTreeSet::new();
for (_, _, _, metadata) in &parsed {
let featured = matcher::parse_title(&metadata.title).featured;
for raw in metadata.artists.iter().chain(&featured) {
names.extend(matcher::artist_name_variants(raw));
}
}
let wanted: HashSet<String> = names
.iter()
.flat_map(|name| keys_of(name))
.filter(|key| !key.is_empty())
.collect();
let names: Vec<String> = names.into_iter().collect();
let mut known = KnownArtists::default();
let mut artist_ids: HashMap<String, Vec<i64>> = HashMap::new();
for (id, name) in load_artists(pool, &names, &wanted).await? {
known.insert(&name);
for key in keys_of(&name) {
artist_ids.entry(key).or_default().push(id);
}
}
let tracks = load_known_federated(pool, user_id, &wanted).await?;
for (fed, _) in &tracks {
for name in fed.artist_names.iter().chain(&fed.featured_artist_names) {
known.insert(name);
}
}
let mut federated = Vec::with_capacity(tracks.len());
let mut federated_by_artist: HashMap<String, Vec<usize>> = HashMap::new();
for (fed, owners) in tracks {
let candidate = Candidate {
origin: Origin::Federation,
title: fed.title.clone(),
artists: fed.artist_names.clone(),
featured_artists: fed.featured_artist_names.clone(),
album: fed.release_title.clone(),
duration_seconds: fed.duration_seconds.map(|seconds| seconds as f64),
content_id: Some(fed.content_id.clone()),
owners,
};
let prepared = PreparedCandidate::new(&candidate, &known);
let index = federated.len();
for name in fed.artist_names.iter().chain(&fed.featured_artist_names) {
for name in matcher::split_artists(name, &known) {
for key in keys_of(&name) {
let indexes = federated_by_artist.entry(key).or_default();
if indexes.last() != Some(&index) {
indexes.push(index);
}
}
}
}
federated.push(KnownTrack {
fed,
candidate,
prepared,
});
}
let mut groups: Vec<Vec<Entry>> = Vec::new();
let mut current_key: Option<Option<String>> = None;
for (id, artist_key, (note, candidates), metadata) in parsed {
let raw = Source {
title: metadata.title,
artists: metadata.artists,
album: metadata.album,
duration_ms: metadata.duration_ms,
};
let source = PreparedSource::new(&raw, &known);
let same_group = current_key.as_ref() == Some(&artist_key)
&& groups.last().is_some_and(|group| group.len() < MAX_GROUP);
if !same_group {
groups.push(Vec::new());
current_key = Some(artist_key);
}
groups
.last_mut()
.expect("a group was just pushed")
.push(Entry {
id,
raw,
source,
note,
candidates,
});
}
Ok(Prepared {
resolver: Self {
known,
artist_ids,
federated,
federated_by_artist,
storage_dir,
},
groups,
invalid,
})
}
fn library_artists(&self, entry: &Entry) -> Vec<i64> {
entry
.source
.artist_names()
.iter()
.flat_map(|name| keys_of(name))
.filter_map(|key| self.artist_ids.get(&key))
.flatten()
.copied()
.collect()
}
fn federated_candidates(&self, entry: &Entry, exclude: &HashSet<&str>) -> Vec<&KnownTrack> {
let mut indexes: Vec<usize> = entry
.source
.artist_names()
.iter()
.flat_map(|name| keys_of(name))
.filter_map(|key| self.federated_by_artist.get(&key))
.flatten()
.copied()
.collect();
indexes.sort_unstable();
indexes.dedup();
indexes
.into_iter()
.map(|index| &self.federated[index])
.filter(|track| track.prepared.title_key().matches(entry.source.title_key()))
.filter(|track| !exclude.contains(track.fed.content_id.as_str()))
.collect()
}
/// Decides every entry of a group: the local library first (stage 1),
/// then together with the known federated tracks (stage 2). With
/// `defer_unmatched` an entry without a match stays pending with its
/// reason for the network stage, and an ambiguous one with its candidates
/// (REQ §11: Retry searches the federation for both).
pub async fn resolve_group(
&self,
pool: &PgPool,
group: &[Entry],
defer_unmatched: bool,
) -> Result<Vec<Resolution>> {
let mut artist_ids = BTreeSet::new();
let mut by_title = Vec::new();
for entry in group {
let found = self.library_artists(entry);
if found.is_empty() && !entry.source.search_title().trim().is_empty() {
by_title.push(entry.source.search_title().to_owned());
}
artist_ids.extend(found);
}
let mut track_ids: BTreeSet<i64> = BTreeSet::new();
if !artist_ids.is_empty() {
let ids: Vec<i64> = artist_ids.into_iter().collect();
track_ids.extend(artist_track_ids(pool, &ids).await?);
}
if !by_title.is_empty() {
track_ids.extend(title_track_ids(pool, &by_title).await?);
}
let ids: Vec<i64> = track_ids.into_iter().collect();
let tracks = if ids.is_empty() {
Vec::new()
} else {
local_tracks(pool, &ids).await?
};
let prepared: Vec<PreparedCandidate> = tracks
.iter()
.map(|track| PreparedCandidate::new(&track.candidate, &self.known))
.collect();
let mut by_key: HashMap<&str, Vec<usize>> = HashMap::new();
for (index, candidate) in prepared.iter().enumerate() {
let title = candidate.title_key();
by_key.entry(title.key.as_str()).or_default().push(index);
if title.folded != title.key {
by_key.entry(title.folded.as_str()).or_default().push(index);
}
}
let mut resolutions = Vec::with_capacity(group.len());
for entry in group {
let title = entry.source.title_key();
let mut local: Vec<usize> = [title.key.as_str(), title.folded.as_str()]
.iter()
.filter_map(|key| by_key.get(key))
.flatten()
.copied()
.collect();
local.sort_unstable();
local.dedup();
let local_prepared: Vec<&PreparedCandidate> =
local.iter().map(|index| &prepared[*index]).collect();
let mut decision = matcher::decide(&entry.source, &local_prepared);
let mut federated = Vec::new();
if !matches!(decision, Decision::Matched(_)) {
let exclude: HashSet<&str> = local
.iter()
.filter_map(|index| tracks[*index].content_id.as_deref())
.collect();
federated = self.federated_candidates(entry, &exclude);
if !federated.is_empty() {
let combined: Vec<&PreparedCandidate> = local_prepared
.iter()
.copied()
.chain(federated.iter().map(|track| &track.prepared))
.collect();
decision = matcher::decide(&entry.source, &combined);
}
}
let chosen = |index: usize| Chosen::pick(&local, &tracks, &federated, index);
resolutions.push(match decision {
Decision::Matched(ranked) => {
self.matched(pool, entry.id, ranked, chosen(ranked.index))
.await
}
Decision::Ambiguous(ranked) => Resolution {
score: ranked.first().map(|best| best.score),
candidates: Some(Value::Array(
ranked
.iter()
.map(|ranked| candidate_json(ranked, chosen(ranked.index)))
.collect(),
)),
note: defer_unmatched.then(|| AMBIGUOUS_LOCAL.to_owned()),
..Resolution::new(
entry.id,
if defer_unmatched {
ResolutionStatus::Pending
} else {
ResolutionStatus::Ambiguous
},
)
},
Decision::Unmatched { reason } => Resolution {
note: Some(reason.to_owned()),
..Resolution::new(
entry.id,
if defer_unmatched {
ResolutionStatus::Pending
} else {
ResolutionStatus::Unmatched
},
)
},
});
}
Ok(resolutions)
}
async fn matched(
&self,
pool: &PgPool,
item_id: i64,
ranked: Ranked,
chosen: Chosen<'_>,
) -> Resolution {
let base = Resolution {
score: Some(ranked.score),
publication: PublicationStatus::Pending,
..Resolution::new(item_id, ResolutionStatus::Matched)
};
match chosen {
Chosen::Local(track) => {
let content_id = match &track.content_id {
Some(content_id) => Some(content_id.clone()),
// Only the chosen track is hashed, one file at a time.
None => match crate::federation::ensure_local_content_id(
pool,
&self.storage_dir,
track.media_file_id,
)
.await
{
Ok(content_id) => content_id,
Err(error) => {
tracing::warn!(
item_id,
media_file_id = track.media_file_id,
%error,
"library import could not compute a content id"
);
return Resolution::failed(item_id, "content_id_failed");
}
},
};
Resolution {
origin: Some(Origin::Local.as_str()),
track_id: Some(track.track_id),
publication: if content_id.is_some() {
PublicationStatus::Pending
} else {
PublicationStatus::NoContentId
},
content_id,
..base
}
}
Chosen::Federated(track) => federated_match(base, track),
}
}
}
/// A match with a federated track: published by its content id and `SyncedFedTrack`.
fn federated_match(base: Resolution, track: &KnownTrack) -> Resolution {
Resolution {
origin: Some(Origin::Federation.as_str()),
content_id: Some(track.fed.content_id.clone()),
fed: serde_json::to_value(&track.fed).ok(),
..base
}
}
/// The track behind a candidate index: local candidates come first.
enum Chosen<'a> {
Local(&'a LocalTrack),
Federated(&'a KnownTrack),
}
impl<'a> Chosen<'a> {
fn pick(
local: &[usize],
tracks: &'a [LocalTrack],
federated: &[&'a KnownTrack],
index: usize,
) -> Self {
match local.get(index) {
Some(local_index) => Self::Local(&tracks[*local_index]),
None => Self::Federated(federated[index - local.len()]),
}
}
}
/// A candidate offered for manual selection.
fn candidate_json(ranked: &Ranked, chosen: Chosen<'_>) -> Value {
let (candidate, track_id, fed) = match chosen {
Chosen::Local(track) => (&track.candidate, Some(track.track_id), None),
Chosen::Federated(track) => (
&track.candidate,
None,
serde_json::to_value(&track.fed).ok(),
),
};
json!({
"origin": candidate.origin,
"level": ranked.level,
"score": ranked.score,
"title": candidate.title,
"artists": candidate.artists,
"featured_artists": candidate.featured_artists,
"album": candidate.album,
"duration_seconds": candidate.duration_seconds,
"content_id": candidate.content_id,
"track_id": track_id,
"fed": fed,
})
}
/// A candidate the user chose, read back from the stored `candidates`
/// (written by [`candidate_json`]). Stored data is checked again, so only a
/// verifiable content id and a servable federated source are accepted.
#[derive(Debug, Clone, PartialEq)]
pub struct ManualMatch {
pub origin: Origin,
pub score: Option<f32>,
pub content_id: Option<String>,
pub track_id: Option<i64>,
pub fed: Option<Value>,
}
impl ManualMatch {
pub fn from_candidate(candidate: &Value) -> Option<Self> {
let content_id = match candidate.get("content_id") {
None | Some(Value::Null) => None,
Some(value) => Some(music_dht::normalize_content_id(value.as_str()?)?),
};
let score = candidate
.get("score")
.and_then(Value::as_f64)
.map(|score| score as f32);
match candidate.get("origin")?.as_str()? {
"local" => Some(Self {
origin: Origin::Local,
score,
content_id,
track_id: Some(candidate.get("track_id")?.as_i64()?),
fed: None,
}),
"federation" => {
let content_id = content_id?;
let fed: SyncedFedTrack =
serde_json::from_value(candidate.get("fed")?.clone()).ok()?;
let valid = music_dht::normalize_content_id(&fed.content_id).as_deref()
== Some(content_id.as_str())
&& !fed.title.trim().is_empty()
&& usable_source(&fed.owner, &fed.item_id);
valid.then(|| Self {
origin: Origin::Federation,
score,
fed: serde_json::to_value(&fed).ok(),
content_id: Some(content_id),
track_id: None,
})
}
_ => None,
}
}
/// A local track without a content id waits for the publisher to hash it.
pub fn publication(&self) -> PublicationStatus {
if self.content_id.is_some() {
PublicationStatus::Pending
} else {
PublicationStatus::NoContentId
}
}
}
fn longest_token(key: &str) -> Option<&str> {
key.split(' ')
.filter(|token| !token.is_empty())
.max_by_key(|token| token.chars().count())
}
/// Library artists named like any of `names` (stage 1a). As in the
/// federation's local catalogue, a literal token narrows the rows and the
/// Unicode comparison happens in Rust. A large import compares every visible
/// artist instead: one scan is cheaper than hundreds of patterns per row.
async fn load_artists(
pool: &PgPool,
names: &[String],
wanted: &HashSet<String>,
) -> sqlx::Result<Vec<(i64, String)>> {
let rows = if names.len() > ARTIST_PATTERNS {
sqlx::query("SELECT id, name::text FROM furumusic__artist WHERE NOT is_hidden")
.fetch_all(pool)
.await?
} else {
let mut patterns = BTreeSet::new();
let mut folded_patterns = BTreeSet::new();
for name in names {
if let Some(token) = longest_token(&music_dht::normalize_name(name)) {
patterns.insert(format!("%{token}%"));
}
if let Some(token) = longest_token(&matcher::folded(name)) {
folded_patterns.insert(format!("%{token}%"));
}
}
if patterns.is_empty() && folded_patterns.is_empty() {
return Ok(Vec::new());
}
sqlx::query(&format!(
"SELECT id, name::text FROM furumusic__artist
WHERE NOT is_hidden
AND (name_sort LIKE ANY($1) OR name IS NOT NFKC NORMALIZED
OR regexp_replace(normalize(name_sort::text, NFD), {FOLD_SQL}, '', 'g')
LIKE ANY($2))"
))
.bind(patterns.into_iter().collect::<Vec<_>>())
.bind(folded_patterns.into_iter().collect::<Vec<_>>())
.fetch_all(pool)
.await?
};
Ok(rows
.into_iter()
.filter_map(|row| {
let name: String = row.get(1);
let key = NameKey::new(&name);
(wanted.contains(&key.key) || wanted.contains(&key.folded)).then(|| (row.get(0), name))
})
.collect())
}
/// Tracks credited to the artists, as main or featured, and tracks of their
/// releases (stage 1b).
async fn artist_track_ids(pool: &PgPool, artist_ids: &[i64]) -> sqlx::Result<Vec<i64>> {
sqlx::query_scalar(
"SELECT track_id FROM furumusic__track_artist
WHERE artist_id = ANY($1) AND role IN ('main', 'featuring')
UNION
SELECT t.id FROM furumusic__track t
JOIN furumusic__release_artist ra ON ra.release_id = t.release_id
WHERE ra.artist_id = ANY($1)",
)
.bind(artist_ids)
.fetch_all(pool)
.await
}
/// Tracks with a similar title for entries whose artist is not in the
/// library (stage 1c), up to [`TITLE_CANDIDATES`] per title.
async fn title_track_ids(pool: &PgPool, titles: &[String]) -> sqlx::Result<Vec<i64>> {
sqlx::query_scalar(
"SELECT DISTINCT hit.id
FROM unnest($1::text[]) AS query(title)
CROSS JOIN LATERAL (
SELECT t.id FROM furumusic__track t
WHERE NOT t.is_hidden AND query.title <% t.title_sort::text
ORDER BY word_similarity(query.title, t.title_sort::text) DESC, t.id
LIMIT $2) hit",
)
.bind(titles)
.bind(TITLE_CANDIDATES)
.fetch_all(pool)
.await
}
async fn local_tracks(pool: &PgPool, ids: &[i64]) -> sqlx::Result<Vec<LocalTrack>> {
let rows = sqlx::query(
"SELECT t.id, m.id, c.content_id, t.title::text, r.title::text, t.duration_seconds,
ARRAY(SELECT a.name::text FROM furumusic__track_artist ta
JOIN furumusic__artist a ON a.id = ta.artist_id
WHERE ta.track_id = t.id AND ta.role = 'main' AND NOT a.is_hidden
ORDER BY ta.position, a.id),
ARRAY(SELECT a.name::text FROM furumusic__track_artist ta
JOIN furumusic__artist a ON a.id = ta.artist_id
WHERE ta.track_id = t.id AND ta.role = 'featuring' AND NOT a.is_hidden
ORDER BY ta.position, a.id),
ARRAY(SELECT a.name::text FROM furumusic__release_artist ra
JOIN furumusic__artist a ON a.id = ra.artist_id
WHERE ra.release_id = r.id AND NOT a.is_hidden
ORDER BY ra.position, a.id)
FROM furumusic__track t
JOIN furumusic__release r ON r.id = t.release_id AND NOT r.is_hidden
JOIN furumusic__media_file m ON m.id = t.audio_file_id
LEFT JOIN furumusic__federation_content_id_cache c
ON c.media_file_id = m.id AND c.sha256_hash = m.sha256_hash
WHERE t.id = ANY($1) AND NOT t.is_hidden
ORDER BY t.id",
)
.bind(ids)
.fetch_all(pool)
.await?;
Ok(rows
.into_iter()
.map(|row| {
let content_id: Option<String> = row.get(2);
let content_id = content_id
.as_deref()
.and_then(music_dht::normalize_content_id);
let main: Vec<String> = row.get(6);
let release_artists: Vec<String> = row.get(8);
let duration: f64 = row.get(5);
LocalTrack {
track_id: row.get(0),
media_file_id: row.get(1),
candidate: Candidate {
origin: Origin::Local,
title: row.get(3),
// Tracks without credits belong to their release artists.
artists: if main.is_empty() {
release_artists
} else {
main
},
featured_artists: row.get(7),
album: row.get(4),
duration_seconds: (duration > 0.0).then_some(duration),
content_id: content_id.clone(),
owners: 0,
},
content_id,
}
})
.collect())
}
#[derive(Deserialize)]
struct RefArtist {
#[serde(default)]
name: String,
}
#[derive(Deserialize)]
struct RefRelease {
#[serde(default)]
title: Option<String>,
}
/// `furumusic__track_ref.metadata_json` as written by the federation search.
#[derive(Deserialize)]
struct RefMetadata {
#[serde(default)]
title: String,
#[serde(default)]
artists: Vec<RefArtist>,
#[serde(default)]
featured_artists: Vec<RefArtist>,
#[serde(default)]
release: Option<RefRelease>,
#[serde(default)]
year: Option<i32>,
#[serde(default)]
duration_seconds: Option<f64>,
#[serde(default)]
track_number: Option<i32>,
#[serde(default)]
disc_number: Option<i32>,
}
/// A federated source the web player can show and the network can serve:
/// not the web player's own metadata of a local track.
fn usable_source(owner: &str, item_id: &str) -> bool {
!owner.trim().is_empty()
&& !item_id.trim().is_empty()
&& owner != "WEB"
&& !item_id.starts_with("web:")
}
fn jsonb_array(path: &str) -> String {
format!("CASE WHEN jsonb_typeof({path}) = 'array' THEN {path} ELSE '[]'::jsonb END")
}
/// Federated tracks this server already knows, by the artists' keys (stage 2):
/// search results in `track_ref` with their freshest source, and the import
/// owner's own likes and playlist entries from Device Sync.
async fn load_known_federated(
pool: &PgPool,
user_id: i64,
wanted: &HashSet<String>,
) -> sqlx::Result<Vec<(SyncedFedTrack, u32)>> {
if wanted.is_empty() {
return Ok(Vec::new());
}
let keys: Vec<&str> = wanted.iter().map(String::as_str).collect();
let artists = format!(
"{} || {}",
jsonb_array("r.metadata_json->'artists'"),
jsonb_array("r.metadata_json->'featured_artists'")
);
let rows = sqlx::query(&format!(
"SELECT r.content_id, r.metadata_json, src.owner_peer_id, src.item_id, src.owners
FROM furumusic__track_ref r
CROSS JOIN LATERAL (
SELECT s.owner_peer_id, s.item_id, count(*) OVER () AS owners
FROM furumusic__federation_track_source s
WHERE s.track_ref_id = r.id AND s.owner_peer_id <> 'WEB'
AND s.item_id NOT LIKE 'web:%'
ORDER BY s.last_seen_ms DESC, s.owner_peer_id, s.item_id
LIMIT 1) src
WHERE r.id IN (
SELECT r.id FROM furumusic__track_ref r
CROSS JOIN LATERAL jsonb_array_elements({artists}) artist
CROSS JOIN LATERAL (VALUES
(replace(artist->'key'->>'normalized_name', 'ё', 'е')),
(regexp_replace(normalize(artist->'key'->>'normalized_name', NFD),
{FOLD_SQL}, '', 'g'))) name(key)
WHERE name.key IN (SELECT unnest($1::text[])))"
))
.bind(&keys)
.fetch_all(pool)
.await?;
let mut seen = HashSet::new();
let mut tracks = Vec::new();
for row in rows {
let content_id: String = row.get(0);
let Some(content_id) = music_dht::normalize_content_id(&content_id) else {
continue;
};
let Ok(metadata) = serde_json::from_value::<RefMetadata>(row.get(1)) else {
continue;
};
let owner: String = row.get(2);
let item_id: String = row.get(3);
let owners: i64 = row.get(4);
if metadata.title.trim().is_empty() || !usable_source(&owner, &item_id) {
continue;
}
let names = |artists: Vec<RefArtist>| -> Vec<String> {
artists
.into_iter()
.map(|artist| artist.name)
.filter(|name| !name.trim().is_empty())
.collect()
};
if seen.insert(content_id.clone()) {
tracks.push((
SyncedFedTrack {
item_id,
owner,
title: metadata.title,
artist_names: names(metadata.artists),
featured_artist_names: names(metadata.featured_artists),
year: metadata.year,
duration_seconds: metadata
.duration_seconds
.filter(|seconds| seconds.is_finite() && *seconds > 0.0)
.map(|seconds| seconds.round() as i64),
content_id,
release_title: metadata.release.and_then(|release| release.title),
track_number: metadata.track_number,
disc_number: metadata.disc_number,
},
u32::try_from(owners).unwrap_or(u32::MAX),
));
}
}
let own: Vec<Value> = sqlx::query_scalar(
"SELECT fed_json FROM furumusic__fed_state_like
WHERE user_id = $1 AND fed_json IS NOT NULL
UNION ALL
SELECT fed_json FROM furumusic__fed_state_playlist_item
WHERE user_id = $1 AND fed_json IS NOT NULL",
)
.bind(user_id)
.fetch_all(pool)
.await?;
for value in own {
let Ok(mut fed) = serde_json::from_value::<SyncedFedTrack>(value) else {
continue;
};
let Some(content_id) = music_dht::normalize_content_id(&fed.content_id) else {
continue;
};
let by_wanted_artist = fed
.artist_names
.iter()
.chain(&fed.featured_artist_names)
.flat_map(|name| keys_of(name))
.any(|key| wanted.contains(&key));
if fed.title.trim().is_empty()
|| !usable_source(&fed.owner, &fed.item_id)
|| !by_wanted_artist
|| !seen.insert(content_id.clone())
{
continue;
}
fed.content_id = content_id;
tracks.push((fed, 1));
}
Ok(tracks)
}
+878
View File
@@ -0,0 +1,878 @@
//! Resolver stage 3 (plan §6): artist catalogues of federation peers.
//!
//! Only artist names leave the server. Each artist group is looked up by its
//! original name, then by its folded spelling, then by its collaboration
//! parts; whatever peers return becomes federated candidates for the group.
//! Groups run under a process-wide limit, a time limit per group and a budget
//! per pass. Dropping a running group cancels its search and all catalogue
//! requests.
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use music_dht::catalog::{CatalogArtist, CatalogTrack};
use music_dht::device_sync::SyncedFedTrack;
use serde_json::Value;
use tokio::sync::Semaphore;
use tokio::time::Instant;
use super::{
Chosen, Entry, FederationAccess, KnownTrack, NetworkLimits, Resolver, candidate_json,
federated_match, usable_source,
};
use crate::federation::client::CatalogError;
use crate::library_import::matcher::{
self, Candidate, Decision, MAX_CANDIDATES, NameKey, Origin, PreparedCandidate, PreparedSource,
};
use crate::library_import::model::{PublicationStatus, ResolutionStatus};
use crate::library_import::store::{AMBIGUOUS_LOCAL, Resolution};
/// Artist groups searched at once by all imports of this process.
static GROUPS: Semaphore = Semaphore::const_new(2);
/// Lookups remembered during one pass. Each artist group is looked up once;
/// the cache serves folded spellings and the parts of collaborations.
const CACHE_NAMES: usize = 8;
/// Federated tracks (unique content ids) kept from one lookup. Peers are not
/// trusted: the 4 MiB limit per catalogue alone lets one lookup bring
/// hundreds of thousands of made-up tracks.
const MAX_FOUND_TRACKS: usize = 5_000;
/// `resolution_note` when the federation node is off or stopped.
pub const FEDERATION_UNAVAILABLE: &str = "federation_unavailable";
/// `resolution_note` of entries left over by the budget of a pass.
pub const FEDERATION_BUDGET: &str = "federation_budget";
/// `resolution_note` of a group whose search kept failing; Resync retries it.
pub const FEDERATION_ERROR: &str = "federation_error";
/// The result of one artist group.
#[derive(Debug)]
pub enum GroupOutcome {
/// A decision for every entry of the group.
Resolved {
resolutions: Vec<Resolution>,
/// Catalogues received.
catalogs: u64,
/// Catalogues lost: unreachable, refused, too large or late.
catalog_errors: u64,
},
/// The federation node is not running; the stage stops.
Unavailable,
}
/// Federated tracks found for one name, unique by content id.
#[derive(Debug, Default)]
struct Found {
tracks: Vec<(SyncedFedTrack, Vec<String>)>,
by_content: HashMap<String, usize>,
names: Vec<String>,
}
impl Found {
fn is_empty(&self) -> bool {
self.tracks.is_empty()
}
/// Takes the tracks of a catalogue with a verifiable content id and a
/// source the network can serve, up to [`MAX_FOUND_TRACKS`]. `false` when
/// some new tracks did not fit: the catalogue counts as too large.
fn add_catalog(&mut self, owner: &str, artist: &CatalogArtist) -> bool {
self.names.push(artist.name.clone());
let mut complete = true;
for release in &artist.releases {
for track in &release.tracks {
complete &=
self.add_track(owner, &artist.name, track, &release.title, release.year);
}
}
for appearance in &artist.appears_on {
complete &= self.add_track(
owner,
&artist.name,
&appearance.track,
&appearance.release_title,
appearance.year,
);
}
complete
}
fn add_track(
&mut self,
owner: &str,
artist: &str,
track: &CatalogTrack,
release: &str,
year: Option<i32>,
) -> bool {
let Some(content_id) = track
.content_id
.as_deref()
.and_then(music_dht::normalize_content_id)
else {
return true;
};
if track.title.trim().is_empty() || !usable_source(owner, &track.item_id) {
return true;
}
if self.tracks.len() >= MAX_FOUND_TRACKS && !self.by_content.contains_key(&content_id) {
return false;
}
let artists = if track.artists.is_empty() {
vec![artist.to_owned()]
} else {
track.artists.clone()
};
self.add(
SyncedFedTrack {
item_id: track.item_id.clone(),
owner: owner.to_owned(),
title: track.title.clone(),
artist_names: artists,
featured_artist_names: track.featured_artists.clone(),
year,
duration_seconds: track
.duration_seconds
.filter(|seconds| seconds.is_finite() && *seconds > 0.0)
.map(|seconds| seconds.round() as i64),
content_id,
release_title: Some(release.trim())
.filter(|title| !title.is_empty())
.map(str::to_owned),
track_number: track.track_number,
disc_number: track.disc_number,
},
std::slice::from_ref(&owner.to_owned()),
);
true
}
/// Adds a track; another owner of a known content id counts, and the
/// first owner by id is kept as the source whatever order peers answer in.
fn add(&mut self, track: SyncedFedTrack, owners: &[String]) {
match self.by_content.get(&track.content_id) {
Some(&index) => {
let (source, known) = &mut self.tracks[index];
for owner in owners {
if !known.contains(owner) {
known.push(owner.clone());
}
}
known.sort();
if track.owner < source.owner {
*source = track;
}
}
None => {
self.by_content
.insert(track.content_id.clone(), self.tracks.len());
self.tracks.push((track, owners.to_vec()));
}
}
}
fn merge(&mut self, other: &Found) {
self.names.extend(other.names.iter().cloned());
for (track, owners) in &other.tracks {
self.add(track.clone(), owners);
}
}
}
enum Lookup {
Found(Arc<Found>),
/// The group ran out of time; what arrived until then.
TimedOut(Found),
/// The search failed after every retry.
Failed,
Unavailable,
}
#[derive(Default)]
struct Counts {
catalogs: u64,
catalog_errors: u64,
}
/// Stage 3 of one resolver pass.
pub struct NetworkSearch<'a> {
resolver: &'a mut Resolver,
federation: &'a dyn FederationAccess,
limits: NetworkLimits,
cache: HashMap<String, Arc<Found>>,
cache_order: VecDeque<String>,
groups: usize,
started: Instant,
}
impl<'a> NetworkSearch<'a> {
pub fn new(resolver: &'a mut Resolver, federation: &'a dyn FederationAccess) -> Self {
Self {
resolver,
limits: federation.limits(),
federation,
cache: HashMap::new(),
cache_order: VecDeque::new(),
groups: 0,
started: Instant::now(),
}
}
pub fn limits(&self) -> &NetworkLimits {
&self.limits
}
/// Artist groups that asked the network.
pub fn groups(&self) -> usize {
self.groups
}
/// Whether the pass used up its groups or its time.
pub fn exhausted(&self) -> bool {
self.groups >= self.limits.max_groups || self.started.elapsed() >= self.limits.max_duration
}
/// Searches the catalogues of a group's artist and decides its entries.
/// Cancel-safe: dropping the future stops the search and its requests.
pub async fn resolve_group(&mut self, group: &[Entry]) -> GroupOutcome {
let Some(name) = group_artist(group) else {
return GroupOutcome::Resolved {
resolutions: self.decide(group, &Found::default()),
catalogs: 0,
catalog_errors: 0,
};
};
let _permit = GROUPS
.acquire()
.await
.expect("the semaphore is never closed");
self.groups += 1;
let deadline = Instant::now() + self.limits.group_timeout;
let mut counts = Counts::default();
let mut found = Found::default();
let (mut failed, mut timed_out) = (false, false);
let mut queue = VecDeque::from([name.clone()]);
let mut step = 0;
'search: loop {
while let Some(query) = queue.pop_front() {
match self.lookup(&query, deadline, &mut counts).await {
Lookup::Found(result) => found.merge(&result),
Lookup::TimedOut(result) => {
found.merge(&result);
timed_out = true;
break 'search;
}
Lookup::Failed => failed = true,
Lookup::Unavailable => return GroupOutcome::Unavailable,
}
}
if !found.is_empty() {
break;
}
step += 1;
match step {
1 => queue.extend(latin_folded(&name)),
2 => {
let parts = matcher::split_artists(&name, &self.resolver.known);
if parts.len() > 1 {
queue.extend(parts);
}
}
_ => break,
}
}
let resolutions = if found.is_empty() && (failed || timed_out) {
group
.iter()
.map(|entry| {
if is_ambiguous(entry) {
still_ambiguous(entry, Vec::new())
} else {
Resolution::failed(entry.id, FEDERATION_ERROR)
}
})
.collect()
} else {
self.decide(group, &found)
};
GroupOutcome::Resolved {
resolutions,
catalogs: counts.catalogs,
catalog_errors: counts.catalog_errors,
}
}
/// One name: from the cache, or from the network with retries after a
/// failed search. Lost catalogues are counted, not retried.
async fn lookup(&mut self, name: &str, deadline: Instant, counts: &mut Counts) -> Lookup {
let key = NameKey::new(name).key;
if let Some(found) = self.cache.get(&key) {
return Lookup::Found(Arc::clone(found));
}
let mut attempt = 0;
loop {
let Some(mut stream) = self
.federation
.artist_catalogs(name, self.limits.catalog_requests)
.await
else {
return Lookup::Unavailable;
};
let mut found = Found::default();
let mut search_failed = false;
loop {
match tokio::time::timeout_at(deadline, stream.next()).await {
// Dropping the stream cancels the requests still running.
Err(_) => {
counts.catalog_errors += 1;
return Lookup::TimedOut(found);
}
Ok(None) => break,
Ok(Some(Ok((owner, artist)))) => {
counts.catalogs += 1;
if !found.add_catalog(&owner, &artist) {
counts.catalog_errors += 1;
}
}
// Errors describe the transport or the peer, never the artist name.
Ok(Some(Err(CatalogError::Catalog(error)))) => {
tracing::debug!(%error, "library import lost a peer catalogue");
counts.catalog_errors += 1;
}
Ok(Some(Err(CatalogError::Search(error)))) => {
tracing::debug!(%error, "library import network search failed");
search_failed = true;
}
}
}
if !search_failed {
let found = Arc::new(found);
self.remember(key, Arc::clone(&found));
return Lookup::Found(found);
}
let Some(wait) = self.limits.backoff.get(attempt).copied() else {
return Lookup::Failed;
};
attempt += 1;
if Instant::now() + wait >= deadline {
tokio::time::sleep_until(deadline).await;
return Lookup::Failed;
}
tokio::time::sleep(wait).await;
}
}
fn remember(&mut self, key: String, found: Arc<Found>) {
if self.cache.len() >= CACHE_NAMES
&& let Some(oldest) = self.cache_order.pop_front()
{
self.cache.remove(&oldest);
}
self.cache_order.push_back(key.clone());
self.cache.insert(key, found);
}
/// Decides the group's entries from the federated candidates found.
fn decide(&mut self, group: &[Entry], found: &Found) -> Vec<Resolution> {
let known = &mut self.resolver.known;
for name in &found.names {
known.insert(name);
}
for (track, _) in &found.tracks {
for name in track
.artist_names
.iter()
.chain(&track.featured_artist_names)
{
known.insert(name);
}
}
let known = &*known;
let tracks: Vec<KnownTrack> = found
.tracks
.iter()
.map(|(fed, owners)| {
let candidate = Candidate {
origin: Origin::Federation,
title: fed.title.clone(),
artists: fed.artist_names.clone(),
featured_artists: fed.featured_artist_names.clone(),
album: fed.release_title.clone(),
duration_seconds: fed.duration_seconds.map(|seconds| seconds as f64),
content_id: Some(fed.content_id.clone()),
owners: u32::try_from(owners.len()).unwrap_or(u32::MAX),
};
let prepared = PreparedCandidate::new(&candidate, known);
KnownTrack {
fed: fed.clone(),
candidate,
prepared,
}
})
.collect();
let mut by_title: HashMap<&str, Vec<usize>> = HashMap::new();
for (index, track) in tracks.iter().enumerate() {
let title = track.prepared.title_key();
by_title.entry(title.key.as_str()).or_default().push(index);
if title.folded != title.key {
by_title
.entry(title.folded.as_str())
.or_default()
.push(index);
}
}
group
.iter()
.map(|entry| {
// Catalogue names may split collaborations stages 1–2 kept whole.
let source = PreparedSource::new(&entry.raw, known);
let title = source.title_key();
let mut indexes: Vec<usize> = [title.key.as_str(), title.folded.as_str()]
.iter()
.filter_map(|key| by_title.get(key))
.flatten()
.copied()
.collect();
indexes.sort_unstable();
indexes.dedup();
let candidates: Vec<&KnownTrack> =
indexes.iter().map(|index| &tracks[*index]).collect();
let prepared: Vec<&PreparedCandidate> =
candidates.iter().map(|track| &track.prepared).collect();
let decision = matcher::decide(&source, &prepared);
if is_ambiguous(entry) {
return decide_ambiguous(entry, decision, &candidates);
}
match decision {
Decision::Matched(ranked) => federated_match(
Resolution {
score: Some(ranked.score),
publication: PublicationStatus::Pending,
..Resolution::new(entry.id, ResolutionStatus::Matched)
},
candidates[ranked.index],
),
Decision::Ambiguous(ranked) => Resolution {
score: ranked.first().map(|best| best.score),
candidates: Some(Value::Array(
ranked
.iter()
.map(|ranked| {
candidate_json(
ranked,
Chosen::Federated(candidates[ranked.index]),
)
})
.collect(),
)),
..Resolution::new(entry.id, ResolutionStatus::Ambiguous)
},
Decision::Unmatched { reason } => Resolution {
note: Some(stronger_note(entry.note.as_deref(), reason).to_owned()),
..Resolution::new(entry.id, ResolutionStatus::Unmatched)
},
}
})
.collect()
}
}
fn is_ambiguous(entry: &Entry) -> bool {
entry.note.as_deref() == Some(AMBIGUOUS_LOCAL)
}
/// An entry stages 1–2 found ambiguous, decided as if its stored candidates
/// and the catalogue tracks were decided together: only Strong and Exact
/// candidates make a match, so the network decides it only when none of the
/// stored candidates is Strong or Exact. Otherwise it stays ambiguous with
/// the catalogue candidates added.
fn decide_ambiguous(entry: &Entry, decision: Decision, found: &[&KnownTrack]) -> Resolution {
let stored_decides = stored_candidates(entry)
.iter()
.any(|candidate| level_rank(candidate) >= STRONG);
let added = match decision {
Decision::Matched(ranked) if !stored_decides => {
return federated_match(
Resolution {
score: Some(ranked.score),
publication: PublicationStatus::Pending,
..Resolution::new(entry.id, ResolutionStatus::Matched)
},
found[ranked.index],
);
}
Decision::Matched(ranked) => vec![ranked],
Decision::Ambiguous(ranked) => ranked,
Decision::Unmatched { .. } => Vec::new(),
};
still_ambiguous(
entry,
added
.iter()
.map(|ranked| candidate_json(ranked, Chosen::Federated(found[ranked.index])))
.collect(),
)
}
fn stored_candidates(entry: &Entry) -> Vec<Value> {
entry
.candidates
.as_ref()
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
}
/// Stored candidates and new ones not offered yet, best first.
fn still_ambiguous(entry: &Entry, added: Vec<Value>) -> Resolution {
let mut candidates = stored_candidates(entry);
for candidate in added {
let content_id = candidate.get("content_id").and_then(Value::as_str);
let offered = content_id.is_some_and(|content_id| {
candidates
.iter()
.any(|known| known.get("content_id").and_then(Value::as_str) == Some(content_id))
});
if !offered {
candidates.push(candidate);
}
}
if candidates.is_empty() {
return Resolution {
note: Some(matcher::NOT_FOUND.to_owned()),
..Resolution::new(entry.id, ResolutionStatus::Unmatched)
};
}
let score = |candidate: &Value| candidate.get("score").and_then(Value::as_f64);
candidates.sort_by(|a, b| {
level_rank(b)
.cmp(&level_rank(a))
.then_with(|| score(b).unwrap_or(0.0).total_cmp(&score(a).unwrap_or(0.0)))
});
candidates.truncate(MAX_CANDIDATES);
Resolution {
score: candidates.first().and_then(score).map(|score| score as f32),
candidates: Some(Value::Array(candidates)),
..Resolution::new(entry.id, ResolutionStatus::Ambiguous)
}
}
/// [`level_rank`] of a Strong candidate.
const STRONG: u8 = 2;
/// The match level a stored candidate was given.
fn level_rank(candidate: &Value) -> u8 {
match candidate.get("level").and_then(Value::as_str) {
Some("exact") => 3,
Some("strong") => STRONG,
Some("weak") => 1,
_ => 0,
}
}
/// The artist name a group is looked up by: the first credited artist as the
/// source spells it.
fn group_artist(group: &[Entry]) -> Option<String> {
group
.iter()
.filter_map(|entry| entry.raw.artists.first())
.map(|name| name.trim())
.find(|name| !NameKey::new(name).is_empty())
.map(str::to_owned)
}
/// The name without the diacritics of Latin letters (Beyoncé → beyonce), if
/// it differs. Other scripts keep their marks: й is a letter of its own, and
/// peers spell it so.
fn latin_folded(name: &str) -> Option<String> {
use unicode_normalization::UnicodeNormalization;
let key = NameKey::new(name).key;
let mut folded = String::with_capacity(key.len());
let mut latin_base = false;
for c in key.nfd() {
if ('\u{300}'..='\u{36f}').contains(&c) {
if latin_base {
continue;
}
} else {
latin_base = c.is_ascii_alphabetic();
}
folded.push(c);
}
let folded: String = folded.nfc().collect();
(!folded.trim().is_empty() && folded != key).then_some(folded)
}
/// The more specific of two reasons for an entry without a match.
fn stronger_note<'a>(local: Option<&'a str>, network: &'a str) -> &'a str {
fn rank(note: &str) -> u8 {
match note {
"duration_mismatch" => 2,
"version_mismatch" => 1,
_ => 0,
}
}
match local {
Some(local) if rank(local) > rank(network) => local,
_ => network,
}
}
#[cfg(test)]
mod tests {
use music_dht::catalog::{CatalogAppearance, CatalogRelease};
use serde_json::json;
use super::*;
fn b3(digit: char) -> String {
format!("b3:{}", digit.to_string().repeat(64))
}
fn track(title: &str, content_id: Option<String>, item_id: &str) -> CatalogTrack {
CatalogTrack {
title: title.into(),
duration_seconds: Some(200.4),
content_id,
item_id: item_id.into(),
..Default::default()
}
}
#[test]
fn catalogue_tracks_become_portable_federated_tracks() {
let artist = CatalogArtist {
name: "Кино".into(),
releases: vec![CatalogRelease {
title: "Группа крови".into(),
year: Some(1988),
tracks: vec![
track("Группа крови", Some(b3('a')), "item-1"),
track("Без content id", None, "item-2"),
track("Свой трек веба", Some(b3('b')), "web:7"),
track(" ", Some(b3('c')), "item-3"),
],
..Default::default()
}],
appears_on: vec![CatalogAppearance {
release_title: "Сборник".into(),
year: Some(2000),
track: CatalogTrack {
artists: vec!["Другой".into()],
..track("Группа крови", Some(b3('a')), "item-9")
},
..Default::default()
}],
};
let mut found = Found::default();
assert!(found.add_catalog("peer-1", &artist));
assert!(found.add_catalog("peer-2", &artist));
assert_eq!(found.tracks.len(), 1);
let (fed, owners) = &found.tracks[0];
assert_eq!(owners, &["peer-1", "peer-2"]);
assert_eq!(fed.owner, "peer-1");
assert_eq!(fed.item_id, "item-1");
assert_eq!(fed.artist_names, ["Кино"]);
assert_eq!(fed.release_title.as_deref(), Some("Группа крови"));
assert_eq!(fed.year, Some(1988));
assert_eq!(fed.duration_seconds, Some(200));
assert_eq!(fed.content_id, b3('a'));
assert_eq!(found.names, ["Кино", "Кино"]);
}
#[test]
fn ambiguous_entries_take_a_network_match_only_over_weak_candidates() {
let fed = SyncedFedTrack {
item_id: "item-1".into(),
owner: "peer-1".into(),
title: "Группа крови".into(),
artist_names: vec!["Кино".into()],
featured_artist_names: Vec::new(),
year: None,
duration_seconds: Some(285),
content_id: b3('a'),
release_title: Some("Группа крови".into()),
track_number: None,
disc_number: None,
};
let candidate = Candidate {
origin: Origin::Federation,
title: fed.title.clone(),
artists: fed.artist_names.clone(),
featured_artists: Vec::new(),
album: fed.release_title.clone(),
duration_seconds: Some(285.0),
content_id: Some(fed.content_id.clone()),
owners: 1,
};
let prepared = PreparedCandidate::new(&candidate, &Default::default());
let track = KnownTrack {
fed,
candidate,
prepared,
};
let raw = matcher::Source {
title: "Группа крови".into(),
artists: vec!["Кино".into()],
album: Some("Группа крови".into()),
duration_ms: Some(285_000),
};
let entry = |stored: Value| Entry {
id: 7,
source: PreparedSource::new(&raw, &Default::default()),
raw: raw.clone(),
note: Some(AMBIGUOUS_LOCAL.into()),
candidates: Some(stored),
};
let decision = || matcher::decide(&entry(json!([])).source, &[&track.prepared]);
assert!(matches!(decision(), Decision::Matched(_)));
let local = |level: &str, digit: char| json!({"origin": "local", "level": level, "score": 0.6, "content_id": b3(digit), "track_id": 1});
// Weak local candidates give way to a network match.
let matched = decide_ambiguous(&entry(json!([local("weak", 'b')])), decision(), &[&track]);
assert_eq!(matched.status, ResolutionStatus::Matched);
assert_eq!(matched.content_id, Some(b3('a')));
// A strong local candidate of another recording keeps the choice open.
let open = decide_ambiguous(
&entry(json!([local("weak", 'c'), local("strong", 'b')])),
decision(),
&[&track],
);
assert_eq!(open.status, ResolutionStatus::Ambiguous);
let candidates = open.candidates.unwrap();
let ids: Vec<&str> = candidates
.as_array()
.unwrap()
.iter()
.map(|candidate| candidate["content_id"].as_str().unwrap())
.collect();
assert_eq!(ids.len(), 3);
assert_eq!(ids[2], b3('c'), "best level first");
assert!(ids.contains(&b3('a').as_str()));
// A candidate already offered is not added twice; nothing found keeps the rest.
let same = decide_ambiguous(&entry(json!([local("strong", 'a')])), decision(), &[&track]);
assert_eq!(same.candidates.unwrap().as_array().unwrap().len(), 1);
let nothing = decide_ambiguous(
&entry(json!([local("weak", 'b')])),
Decision::Unmatched {
reason: "not_found",
},
&[],
);
assert_eq!(nothing.status, ResolutionStatus::Ambiguous);
assert_eq!(nothing.candidates.unwrap().as_array().unwrap().len(), 1);
}
#[test]
fn one_lookup_keeps_a_bounded_number_of_tracks() {
let content_id = |n: usize| format!("b3:{n:064x}");
let release = |tracks: std::ops::Range<usize>| CatalogRelease {
title: "Album".into(),
tracks: tracks
.map(|n| track("Song", Some(content_id(n)), &format!("item-{n}")))
.collect(),
..Default::default()
};
let artist = |tracks| CatalogArtist {
name: "Artist".into(),
releases: vec![release(tracks)],
..Default::default()
};
let mut found = Found::default();
assert!(found.add_catalog("peer-1", &artist(0..MAX_FOUND_TRACKS)));
// Known tracks still gain owners; new ones beyond the limit are dropped.
assert!(found.add_catalog("peer-2", &artist(0..10)));
assert!(!found.add_catalog("peer-3", &artist(5..MAX_FOUND_TRACKS + 5)));
assert_eq!(found.tracks.len(), MAX_FOUND_TRACKS);
assert_eq!(found.tracks[0].1, ["peer-1", "peer-2"]);
assert_eq!(found.tracks[MAX_FOUND_TRACKS - 1].1, ["peer-1", "peer-3"]);
assert!(!found.by_content.contains_key(&content_id(MAX_FOUND_TRACKS)));
}
#[test]
fn only_latin_diacritics_are_folded_for_the_network() {
assert_eq!(latin_folded("Beyoncé").as_deref(), Some("beyonce"));
assert_eq!(latin_folded("Sigur Rós").as_deref(), Some("sigur ros"));
assert_eq!(latin_folded("Мумий Тролль"), None);
assert_eq!(latin_folded("Queen"), None);
}
#[test]
fn stored_candidates_are_checked_before_a_manual_match() {
use super::super::ManualMatch;
let fed = SyncedFedTrack {
item_id: "item-1".into(),
owner: "peer-1".into(),
title: "Группа крови".into(),
artist_names: vec!["Кино".into()],
featured_artist_names: Vec::new(),
year: None,
duration_seconds: Some(285),
content_id: b3('a'),
release_title: None,
track_number: None,
disc_number: None,
};
let candidate = Candidate {
origin: Origin::Federation,
title: fed.title.clone(),
artists: fed.artist_names.clone(),
featured_artists: Vec::new(),
album: None,
duration_seconds: Some(285.0),
content_id: Some(fed.content_id.clone()),
owners: 1,
};
let prepared = PreparedCandidate::new(&candidate, &Default::default());
let track = KnownTrack {
fed,
candidate,
prepared,
};
// Without a duration on the source side the candidate is only weak.
let source = PreparedSource::new(
&matcher::Source {
title: "Группа крови".into(),
artists: vec!["Кино".into()],
album: None,
duration_ms: None,
},
&Default::default(),
);
let Decision::Ambiguous(ranked) = matcher::decide(&source, &[&track.prepared]) else {
panic!("a weak candidate is left to the user");
};
let ranked = ranked[0];
let stored = candidate_json(&ranked, Chosen::Federated(&track));
let chosen = ManualMatch::from_candidate(&stored).unwrap();
assert_eq!(chosen.origin, Origin::Federation);
assert_eq!(chosen.content_id, Some(b3('a')));
assert_eq!(chosen.publication(), PublicationStatus::Pending);
let mut web = stored.clone();
web["fed"]["item_id"] = "web:7".into();
let mut other = stored.clone();
other["content_id"] = b3('b').into();
let mut origin = stored.clone();
origin["origin"] = "elsewhere".into();
for invalid in [web, other, origin] {
assert_eq!(ManualMatch::from_candidate(&invalid), None);
}
let local = serde_json::json!({"origin": "local", "track_id": 3, "content_id": null});
let chosen = ManualMatch::from_candidate(&local).unwrap();
assert_eq!(chosen.publication(), PublicationStatus::NoContentId);
}
#[test]
fn the_more_specific_reason_is_kept() {
assert_eq!(
stronger_note(Some("version_mismatch"), "not_found"),
"version_mismatch"
);
assert_eq!(
stronger_note(Some("not_found"), "duration_mismatch"),
"duration_mismatch"
);
assert_eq!(stronger_note(None, "not_found"), "not_found");
}
}
+108
View File
@@ -0,0 +1,108 @@
-- Library import keeps the full source list, matching decisions and publication receipts.
-- None of these tables take part in Device Sync.
CREATE TABLE IF NOT EXISTS furumusic__library_import (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES furumusic__user(id) ON DELETE CASCADE,
provider TEXT NOT NULL,
source_type TEXT NOT NULL,
source_account_ref TEXT,
federated_search BOOLEAN NOT NULL DEFAULT false,
status TEXT NOT NULL,
phase TEXT,
cancel_requested BOOLEAN NOT NULL DEFAULT false,
rerun_requested BOOLEAN NOT NULL DEFAULT false,
lease_owner BIGINT,
lease_until TIMESTAMPTZ,
statistics JSONB NOT NULL DEFAULT '{}',
error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_resync_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_library_import_user
ON furumusic__library_import(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_library_import_active
ON furumusic__library_import(status) WHERE status IN ('queued', 'running');
CREATE TABLE IF NOT EXISTS furumusic__library_import_playlist (
id BIGSERIAL PRIMARY KEY,
import_id BIGINT NOT NULL REFERENCES furumusic__library_import(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
ordinal INTEGER NOT NULL,
source_playlist_id TEXT,
source_key TEXT NOT NULL,
source_title TEXT NOT NULL,
source_description TEXT,
target_playlist_id BIGINT REFERENCES furumusic__playlist(id) ON DELETE SET NULL,
-- A NULL target with a creation time means the user deleted the target playlist.
target_created_at TIMESTAMPTZ,
publication_paused BOOLEAN NOT NULL DEFAULT false,
fetched_at TIMESTAMPTZ,
UNIQUE (import_id, source_key)
);
CREATE INDEX IF NOT EXISTS idx_library_import_playlist_key
ON furumusic__library_import_playlist(source_key);
-- Deleting any playlist sets its import targets to NULL.
CREATE INDEX IF NOT EXISTS idx_library_import_playlist_target
ON furumusic__library_import_playlist(target_playlist_id) WHERE target_playlist_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS furumusic__library_import_item (
id BIGSERIAL PRIMARY KEY,
import_playlist_id BIGINT NOT NULL
REFERENCES furumusic__library_import_playlist(id) ON DELETE CASCADE,
source_track_id TEXT,
source_position INTEGER NOT NULL,
metadata JSONB NOT NULL,
artist_key TEXT,
resolution_status TEXT NOT NULL DEFAULT 'pending',
resolution_note TEXT,
match_origin TEXT,
match_method TEXT,
match_score REAL,
matched_content_id TEXT,
matched_track_id BIGINT,
matched_fed JSONB,
candidates JSONB,
publication_status TEXT NOT NULL DEFAULT 'not_ready',
last_attempt_at TIMESTAMPTZ,
attempt_count INTEGER NOT NULL DEFAULT 0,
UNIQUE (import_playlist_id, source_position)
);
CREATE INDEX IF NOT EXISTS idx_library_import_item_resolution
ON furumusic__library_import_item(import_playlist_id, resolution_status);
CREATE INDEX IF NOT EXISTS idx_library_import_item_publication
ON furumusic__library_import_item(import_playlist_id, publication_status, source_position);
CREATE INDEX IF NOT EXISTS idx_library_import_item_artist
ON furumusic__library_import_item(import_playlist_id, artist_key);
-- A receipt survives track and playlist deletion, so removed tracks are never added again.
CREATE TABLE IF NOT EXISTS furumusic__library_import_publication (
target_playlist_id BIGINT NOT NULL,
content_id TEXT NOT NULL,
import_playlist_id BIGINT NOT NULL
REFERENCES furumusic__library_import_playlist(id) ON DELETE CASCADE,
item_id BIGINT NOT NULL REFERENCES furumusic__library_import_item(id) ON DELETE CASCADE,
state TEXT NOT NULL,
position BIGINT NOT NULL,
op_id TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (target_playlist_id, content_id)
);
-- Deleting an import cascades through these keys once per row.
CREATE INDEX IF NOT EXISTS idx_library_import_publication_item
ON furumusic__library_import_publication(item_id);
CREATE INDEX IF NOT EXISTS idx_library_import_publication_playlist
ON furumusic__library_import_publication(import_playlist_id);
CREATE TABLE IF NOT EXISTS furumusic__library_import_attempt (
id BIGSERIAL PRIMARY KEY,
import_id BIGINT NOT NULL REFERENCES furumusic__library_import(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
status TEXT NOT NULL,
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
finished_at TIMESTAMPTZ,
statistics JSONB NOT NULL DEFAULT '{}',
error TEXT
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_library_import_attempt_active
ON furumusic__library_import_attempt(import_id) WHERE finished_at IS NULL
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+76
View File
@@ -0,0 +1,76 @@
//! Rendering of the import page, menu entry and wizard in the player. Set
//! `FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1` to write the rendered player for
//! `tests/browser-library-import.cjs`.
use cot::Template;
use crate::i18n::{Lang, Translations};
use crate::player::PlayerPageTemplate;
fn render(lang: Lang, guest: bool) -> String {
PlayerPageTemplate {
t: Translations::for_lang(lang),
guest,
account_id: if guest { 0 } else { 1 },
share_token: if guest { "share".into() } else { String::new() },
downloads_enabled: true,
torrent_downloads_enabled: true,
youtube_downloads_enabled: true,
}
.render()
.unwrap()
}
#[test]
fn library_import_page_menu_and_wizard_render_in_the_player() {
let html = render(Lang::En, false);
// The menu entry sits between Followed and Settings in both account menus.
let menus: Vec<&str> = html
.split("<div class=\"account-action-list\"")
.skip(1)
.collect();
assert_eq!(menus.len(), 2);
for menu in menus {
let followed = menu.find("href=\"#followed\"").unwrap();
let imports = menu.find("href=\"#imports\"").unwrap();
let settings = menu.find("$store.user.openSettings()").unwrap();
assert!(followed < imports && imports < settings);
assert!(menu[imports..settings].contains("Import library"));
}
assert!(html.contains("x-if=\"$store.library.view === 'imports'\""));
assert!(html.contains("x-if=\"$store.library.view === 'import_detail'\""));
assert!(html.contains("id=\"import-wizard\" class=\"player-dialog import-wizard\""));
assert!(
html.find("Alpine.store('imports',").unwrap()
< html.find("Alpine.store('library',").unwrap(),
"the import store must exist before library.init restores the hash"
);
// The archive reader is loaded on demand, not embedded in the page.
assert!(html.contains("/vendor/fflate-0.8.2.js"));
assert!(!html.contains("_e.unzipSync="));
// Every label of the store is rendered from the phrase table.
assert!(!html.contains("{{ t."));
let russian = render(Lang::Ru, false);
assert!(russian.contains("Импорт библиотеки"));
assert!(russian.contains("Участникам сети будут отправлены только имена исполнителей."));
let shared = render(Lang::En, true);
assert!(!shared.contains("Alpine.store('imports',"));
assert!(!shared.contains("import-wizard"));
if std::env::var_os("FURU_LIBRARY_IMPORT_RENDER_FIXTURE").is_some() {
std::fs::create_dir_all("target").unwrap();
std::fs::write("target/library-import-player-fixture.html", &html).unwrap();
std::fs::write("target/library-import-player-fixture-ru.html", &russian).unwrap();
}
}
#[test]
fn library_import_vendored_zip_reader_is_fflate_0_8_2() {
let source = include_str!("../../player/vendor/fflate-0.8.2.min.js");
assert!(source.starts_with("!function(f){typeof module!='undefined'"));
assert!(source.contains("_e.unzip=") && source.contains("_e.unzipSync="));
let license = include_str!("../../player/vendor/fflate-LICENSE");
assert!(license.starts_with("MIT License") && license.contains("Arjun Barrett"));
}
+43 -63
View File
@@ -210,7 +210,7 @@ pub async fn list(
user_id: i64,
inbox_dir: &str,
) -> anyhow::Result<Vec<LocalUploadDto>> {
sync_statuses(pool, user_id, inbox_dir).await?;
sync_statuses(pool, user_id, inbox_dir, None).await?;
crate::import_playlists::reconcile(pool, Some(user_id)).await?;
let rows: Vec<LocalUploadRow> = sqlx::query_as(
r#"SELECT id, user_id, filename, size_bytes, status, inbox_path, error,
@@ -239,7 +239,12 @@ pub async fn remove(pool: &PgPool, user_id: i64, id: &str) -> anyhow::Result<()>
Ok(())
}
async fn sync_statuses(pool: &PgPool, user_id: i64, inbox_dir: &str) -> anyhow::Result<()> {
pub(crate) async fn sync_statuses(
pool: &PgPool,
user_id: i64,
inbox_dir: &str,
batches: Option<&[String]>,
) -> anyhow::Result<()> {
let inbox_dir = inbox_dir.trim();
if inbox_dir.is_empty() {
bail!("agent_inbox_dir is not configured");
@@ -253,9 +258,11 @@ async fn sync_statuses(pool: &PgPool, user_id: i64, inbox_dir: &str) -> anyhow::
r#"SELECT id, user_id, filename, size_bytes, status, inbox_path, error,
created_at, updated_at, completed_at, target_playlist_id
FROM furumusic__local_upload
WHERE user_id = $1 AND status <> 'complete'"#,
WHERE user_id = $1 AND status <> 'complete'
AND ($2::text[] IS NULL OR batch_id = ANY($2))"#,
)
.bind(user_id)
.bind(batches)
.fetch_all(pool)
.await?;
if rows.is_empty() {
@@ -263,69 +270,46 @@ async fn sync_statuses(pool: &PgPool, user_id: i64, inbox_dir: &str) -> anyhow::
}
let inbox_paths: Vec<String> = rows.iter().map(|row| row.inbox_path.clone()).collect();
let state_rows: Vec<(String, String, i64)> = sqlx::query_as(
r#"SELECT input_path, status::text, COUNT(*)
FROM furumusic__pending_review
WHERE input_path = ANY($1)
GROUP BY input_path, status"#,
let states: Vec<(String, String, Option<String>)> = sqlx::query_as(
"SELECT input_path, status, error_message FROM furumusic__upload_review_state \
WHERE input_path = ANY($1)",
)
.bind(&inbox_paths)
.fetch_all(pool)
.await?;
let mut states_by_path: HashMap<String, HashMap<String, i64>> = HashMap::new();
for (input_path, status, total) in state_rows {
states_by_path
.entry(input_path)
.or_default()
.insert(status, total);
}
let error_rows: Vec<(String, String)> = sqlx::query_as(
r#"SELECT DISTINCT ON (input_path) input_path, error_message
FROM furumusic__pending_review
WHERE input_path = ANY($1) AND status = 'failed'
AND error_message IS NOT NULL
ORDER BY input_path, id DESC"#,
)
.bind(&inbox_paths)
.fetch_all(pool)
.await?;
let errors_by_path: HashMap<String, String> = error_rows.into_iter().collect();
let states_by_path: HashMap<_, _> = states
.into_iter()
.map(|(path, status, error)| (path, (status, error)))
.collect();
for row in rows {
let counts = states_by_path
.get(&row.inbox_path)
.cloned()
.unwrap_or_default();
let total: i64 = counts.values().sum();
let mut terminal_error = None;
let next = if total == 0 {
if matches!(row.status.as_str(), "uploading" | "failed" | "needs_review") {
continue;
let (next, error) = match states_by_path.get(&row.inbox_path) {
Some((status, error)) => match status.as_str() {
"processing" => ("ai_processing", None),
"failed" => ("failed", error.as_deref()),
"pending" | "rejected" => ("needs_review", None),
"cancelled" => ("cancelled", None),
"approved" | "auto_approved" => ("complete", None),
_ => ("queued", None),
},
None => {
if matches!(
row.status.as_str(),
"uploading" | "failed" | "needs_review" | "cancelled"
) {
continue;
}
let full_path =
crate::media_paths::resolve_path_from_root(inbox_dir, &row.inbox_path);
if tokio::fs::try_exists(full_path).await? {
("queued", None)
} else {
("complete", None)
}
}
let full_path = crate::media_paths::resolve_path_from_root(inbox_dir, &row.inbox_path);
if tokio::fs::try_exists(full_path).await.unwrap_or(false) {
"queued"
} else {
"complete"
}
} else if count(&counts, "processing") > 0 {
"ai_processing"
} else if count(&counts, "queued") > 0 {
"queued"
} else if count(&counts, "failed") > 0 {
terminal_error = errors_by_path.get(&row.inbox_path).cloned();
"failed"
} else if count(&counts, "pending") > 0 || count(&counts, "rejected") > 0 {
"needs_review"
} else if count(&counts, "approved") > 0 || count(&counts, "auto_approved") > 0 {
"complete"
} else {
"queued"
};
if row.status != next || row.error != terminal_error {
update_status(pool, &row.id, row.user_id, next, terminal_error.as_deref()).await?;
if row.status != next || row.error.as_deref() != error {
update_status(pool, &row.id, row.user_id, next, error).await?;
}
}
Ok(())
@@ -340,7 +324,7 @@ async fn update_status(
) -> anyhow::Result<()> {
let now = now_string();
let completed_at =
matches!(status, "complete" | "failed" | "needs_review").then(|| now.clone());
matches!(status, "complete" | "failed" | "needs_review" | "cancelled").then(|| now.clone());
sqlx::query(
r#"UPDATE furumusic__local_upload
SET status = $3, error = $4, updated_at = $5, completed_at = $6
@@ -370,10 +354,6 @@ async fn load(pool: &PgPool, user_id: i64, id: &str) -> anyhow::Result<LocalUplo
.context("file upload history entry not found")
}
fn count(counts: &HashMap<String, i64>, status: &str) -> i64 {
counts.get(status).copied().unwrap_or(0)
}
fn trim_error(value: &str) -> String {
value.chars().take(4_000).collect()
}
+23
View File
@@ -0,0 +1,23 @@
intfloat/multilingual-e5-small
https://huggingface.co/intfloat/multilingual-e5-small/tree/614241f622f53c4eeff9890bdc4f31cfecc418b3
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+100 -17
View File
@@ -3,6 +3,7 @@ use anyhow::Result;
use music_dht::lyrics::{LyricsVersion, MAX_LYRICS_VERSIONS};
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, Row};
mod model_files;
pub mod search;
#[derive(Debug, Serialize)]
@@ -61,16 +62,95 @@ pub async fn for_track(
let Some(hash) = track_hash(pool, track_id, visible_only).await? else {
return Ok(None);
};
let content_id = sqlx::query_scalar("SELECT c.content_id FROM furumusic__track t
JOIN furumusic__media_file m ON m.id=t.audio_file_id
JOIN furumusic__federation_content_id_cache c ON c.media_file_id=m.id AND c.sha256_hash=m.sha256_hash
WHERE t.id=$1").bind(track_id).fetch_optional(pool).await?;
let content_id = track_content_id(pool, track_id, visible_only).await?;
Ok(Some(TrackLyrics {
content_id,
versions: versions(pool, &hash).await?,
}))
}
pub(crate) async fn track_content_id(
pool: &PgPool,
track_id: i64,
visible_only: bool,
) -> Result<Option<String>> {
Ok(sqlx::query_scalar("SELECT c.content_id FROM furumusic__track t
JOIN furumusic__release r ON r.id=t.release_id
JOIN furumusic__media_file m ON m.id=t.audio_file_id
JOIN furumusic__federation_content_id_cache c ON c.media_file_id=m.id AND c.sha256_hash=m.sha256_hash
WHERE t.id=$1 AND (NOT $2 OR (NOT t.is_hidden AND NOT r.is_hidden))")
.bind(track_id).bind(visible_only).fetch_optional(pool).await?)
}
pub(crate) async fn visible_content_hash(
pool: &PgPool,
content_id: &str,
) -> Result<Option<String>> {
Ok(sqlx::query_scalar("SELECT m.sha256_hash::text FROM furumusic__track t
JOIN furumusic__release r ON r.id=t.release_id
JOIN furumusic__media_file m ON m.id=t.audio_file_id
JOIN furumusic__federation_content_id_cache c ON c.media_file_id=m.id AND c.sha256_hash=m.sha256_hash
WHERE c.content_id=$1 AND NOT t.is_hidden AND NOT r.is_hidden
ORDER BY t.id LIMIT 1")
.bind(content_id).fetch_optional(pool).await?)
}
pub(crate) fn same_text(a: &LyricsVersion, b: &LyricsVersion) -> bool {
a.plain_text == b.plain_text && a.synced_lrc == b.synced_lrc && a.instrumental == b.instrumental
}
pub(crate) fn peer_version_id(version: &LyricsVersion) -> String {
let mut hash = blake3::Hasher::new();
for text in [&version.plain_text, &version.synced_lrc] {
hash.update(&[u8::from(text.is_some())]);
if let Some(text) = text {
hash.update(&(text.len() as u64).to_le_bytes());
hash.update(text.as_bytes());
}
}
format!("peer:{}", hash.finalize().to_hex())
}
pub(crate) async fn save_peer_versions(
pool: &PgPool,
content_id: &str,
incoming: &[LyricsVersion],
) -> Result<()> {
let Some(hash) = visible_content_hash(pool, content_id).await? else {
return Ok(());
};
let mut tx = pool.begin().await?;
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))")
.bind(&hash)
.execute(&mut *tx)
.await?;
let mut count: i64 =
sqlx::query_scalar("SELECT count(*) FROM furumusic__lyrics WHERE audio_sha256=$1")
.bind(&hash)
.fetch_one(&mut *tx)
.await?;
for version in incoming {
if count >= MAX_LYRICS_VERSIONS as i64 {
break;
}
if version.validate().is_err() || !postgres_safe(version) {
continue;
}
let result = sqlx::query("INSERT INTO furumusic__lyrics
(audio_sha256,id,label,source,source_id,language,plain_text,synced_lrc,instrumental)
SELECT $1,$2,$3,'federation',$4,$5,$6,$7,$8 WHERE NOT EXISTS (
SELECT 1 FROM furumusic__lyrics WHERE audio_sha256=$1 AND
plain_text IS NOT DISTINCT FROM $6 AND synced_lrc IS NOT DISTINCT FROM $7 AND instrumental=$8
) ON CONFLICT DO NOTHING")
.bind(&hash).bind(peer_version_id(version)).bind(&version.label).bind(&version.source_id)
.bind(&version.language).bind(&version.plain_text).bind(&version.synced_lrc).bind(version.instrumental)
.execute(&mut *tx).await?;
count += result.rows_affected() as i64;
}
tx.commit().await?;
Ok(())
}
pub async fn available_track_ids(
pool: &PgPool,
ids: &[i64],
@@ -87,6 +167,21 @@ pub struct LyricsEdit {
pub retry_lookup: bool,
}
fn postgres_safe(version: &LyricsVersion) -> bool {
[
Some(version.id.as_str()),
Some(version.label.as_str()),
Some(version.source.as_str()),
version.source_id.as_deref(),
version.language.as_deref(),
version.plain_text.as_deref(),
version.synced_lrc.as_deref(),
]
.into_iter()
.flatten()
.all(|text| !text.contains('\0'))
}
pub fn validate_edit(body: &LyricsEdit) -> Result<()> {
anyhow::ensure!(
body.versions.len() <= MAX_LYRICS_VERSIONS,
@@ -95,20 +190,8 @@ pub fn validate_edit(body: &LyricsEdit) -> Result<()> {
let mut ids = std::collections::HashSet::new();
for version in &body.versions {
version.validate()?;
let fields = [
Some(version.id.as_str()),
Some(version.label.as_str()),
Some(version.source.as_str()),
version.source_id.as_deref(),
version.language.as_deref(),
version.plain_text.as_deref(),
version.synced_lrc.as_deref(),
];
anyhow::ensure!(
fields
.into_iter()
.flatten()
.all(|text| !text.contains('\0')),
postgres_safe(version),
"lyrics cannot contain the NUL character (U+0000)"
);
anyhow::ensure!(ids.insert(&version.id), "duplicate version id");
+207
View File
@@ -0,0 +1,207 @@
//! Pinned files for the E5 embedding profile, cached beside the audio similarity models.
use anyhow::{Context, Result, ensure};
use sha2::{Digest, Sha256};
use std::{
io::{ErrorKind, Write},
path::{Path, PathBuf},
time::Duration,
};
use tempfile::NamedTempFile;
use tokio::{fs, io::AsyncWriteExt, sync::Mutex};
const BASE_URL: &str = "https://huggingface.co/intfloat/multilingual-e5-small/resolve/614241f622f53c4eeff9890bdc4f31cfecc418b3/onnx";
const NOTICE: &str = include_str!("e5-notice.txt");
struct Artifact {
name: &'static str,
size: u64,
sha256: &'static str,
}
const FILES: &[Artifact] = &[
Artifact {
name: "model.onnx",
size: 470_268_510,
sha256: "ca456c06b3a9505ddfd9131408916dd79290368331e7d76bb621f1cba6bc8665",
},
Artifact {
name: "tokenizer.json",
size: 17_082_730,
sha256: "0b44a9d7b51c3c62626640cda0e2c2f70fdacdc25bbbd68038369d14ebdf4c39",
},
Artifact {
name: "config.json",
size: 653,
sha256: "bbb7c1333fc4b3e27fbc9cd5d2070aabcc1d4dfb99917c3633e772f97545a6b6",
},
Artifact {
name: "special_tokens_map.json",
size: 167,
sha256: "d05497f1da52c5e09554c0cd874037a083e1dc1b9cfd48034d1c717f1afc07a7",
},
Artifact {
name: "tokenizer_config.json",
size: 443,
sha256: "a1d6bc8734a6f635dc158508bef000f8e2e5a759c7d92f984b2c86e5ff53425b",
},
];
pub(super) fn directory() -> PathBuf {
std::env::var_os("FURU_LYRICS_MODEL_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| {
crate::media_paths::resolve_config_path_buf("similarity-models/multilingual-e5-small")
})
}
pub(super) async fn prepare(download: bool) -> Result<PathBuf> {
static PREPARING: Mutex<()> = Mutex::const_new(());
let _guard = PREPARING.lock().await;
let dir = directory();
prepare_files(&dir, BASE_URL, FILES, download).await?;
Ok(dir)
}
async fn prepare_files(
dir: &Path,
base_url: &str,
files: &[Artifact],
download: bool,
) -> Result<()> {
let mut missing = Vec::new();
for file in files {
let path = dir.join(file.name);
let size = match fs::metadata(&path).await {
Ok(meta) => Some(meta.len()),
Err(error) if error.kind() == ErrorKind::NotFound => None,
Err(error) => return Err(error).with_context(|| format!("reading {}", path.display())),
};
if size == Some(file.size) && crate::agent::mover::sha256_file(&path).await? == file.sha256
{
continue;
}
ensure!(
download,
"missing or invalid cached lyrics model file {}",
path.display()
);
missing.push(file);
}
if missing.is_empty() {
return Ok(());
}
fs::create_dir_all(dir)
.await
.with_context(|| format!("creating {}", dir.display()))?;
let mut notice = NamedTempFile::new_in(dir)?;
notice.write_all(NOTICE.as_bytes())?;
notice.persist(dir.join("NOTICE"))?;
let client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(15))
.read_timeout(Duration::from_secs(120))
.build()?;
for file in missing {
tracing::info!(
"Downloading lyrics model file {} ({} bytes)",
file.name,
file.size
);
download_file(&client, base_url, dir, file)
.await
.with_context(|| format!("downloading lyrics model file {}", file.name))?;
}
Ok(())
}
async fn download_file(
client: &reqwest::Client,
base_url: &str,
dir: &Path,
file: &Artifact,
) -> Result<()> {
let mut response = client
.get(format!("{base_url}/{}", file.name))
.send()
.await?
.error_for_status()?;
// A unique temporary file beside the destination makes publication atomic even
// if two instances share a volume. Cancelling this future discards its partial file.
let (handle, temp_path) = NamedTempFile::new_in(dir)?.into_parts();
let mut output = fs::File::from_std(handle);
let mut hash = Sha256::new();
let mut bytes = 0u64;
while let Some(chunk) = response.chunk().await? {
bytes += chunk.len() as u64;
ensure!(bytes <= file.size, "response exceeds pinned file size");
hash.update(&chunk);
output.write_all(&chunk).await?;
}
ensure!(
bytes == file.size,
"incomplete response ({bytes} of {} bytes)",
file.size
);
ensure!(
format!("{:x}", hash.finalize()) == file.sha256,
"SHA-256 mismatch"
);
output.flush().await?;
drop(output);
temp_path.persist(dir.join(file.name))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::AsyncReadExt;
use tokio::net::TcpListener;
const EXAMPLE: &[Artifact] = &[Artifact {
name: "model.onnx",
size: 5,
sha256: "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
}];
#[tokio::test]
async fn repairs_corrupt_model_and_reuses_verified_files_offline() -> Result<()> {
let root = tempfile::tempdir()?;
let dir = root.path().join("model");
assert!(prepare_files(&dir, "", EXAMPLE, false).await.is_err());
assert!(!dir.exists());
fs::create_dir(&dir).await?;
let model = dir.join("model.onnx");
fs::write(&model, b"prior").await?;
let listener = TcpListener::bind("127.0.0.1:0").await?;
let url = format!("http://{}", listener.local_addr()?);
let server = tokio::spawn(async move {
for body in ["wrong", "hello"] {
let (mut socket, _) = listener.accept().await?;
let mut buffer = [0; 4096];
socket.read(&mut buffer).await?;
let reply = format!(
"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{body}"
);
socket.write_all(reply.as_bytes()).await?;
}
std::io::Result::Ok(())
});
let err = prepare_files(&dir, &url, EXAMPLE, true).await.unwrap_err();
assert!(format!("{err:#}").contains("SHA-256 mismatch"));
assert_eq!(fs::read(&model).await?, b"prior");
assert_eq!(dir.read_dir()?.count(), 2);
prepare_files(&dir, &url, EXAMPLE, true).await?;
server.await??;
assert_eq!(fs::read(&model).await?, b"hello");
assert_eq!(fs::read_to_string(dir.join("NOTICE")).await?, NOTICE);
prepare_files(&dir, "", EXAMPLE, true).await?;
prepare_files(&dir, "", EXAMPLE, false).await
}
#[tokio::test]
#[ignore = "uses the real E5 model cache and downloads missing files"]
async fn prepare_pinned_model() {
prepare(true).await.unwrap();
}
}
+135 -71
View File
@@ -8,13 +8,11 @@ use serde::Serialize;
use sqlx::{PgPool, Row};
use std::{
collections::{HashMap, HashSet, VecDeque},
sync::{
Arc, Mutex, OnceLock, RwLock,
atomic::{AtomicBool, Ordering},
},
path::{Path, PathBuf},
sync::{Arc, Mutex, OnceLock, RwLock},
time::{Duration, Instant},
};
use tokio::sync::{Mutex as AsyncMutex, Semaphore};
use tokio::sync::{Mutex as AsyncMutex, OnceCell, Semaphore, watch};
use unicode_normalization::UnicodeNormalization;
#[cfg(test)]
@@ -81,10 +79,11 @@ struct Corpus {
refreshed: Option<Instant>,
}
pub struct Manager {
enabled: AtomicBool,
enabled: watch::Sender<bool>,
corpus: RwLock<Arc<Corpus>>,
refresh_lock: AsyncMutex<()>,
model: Mutex<Option<TextEmbedding>>,
model_dir: OnceCell<PathBuf>,
model_retry: Mutex<Option<Instant>>,
status: RwLock<Status>,
query_slots: Semaphore,
@@ -92,18 +91,22 @@ pub struct Manager {
}
pub fn handle() -> &'static Arc<Manager> {
static HANDLE: OnceLock<Arc<Manager>> = OnceLock::new();
HANDLE.get_or_init(|| {
Arc::new(Manager {
enabled: AtomicBool::new(true),
HANDLE.get_or_init(|| Arc::new(Manager::default()))
}
impl Default for Manager {
fn default() -> Self {
Self {
enabled: watch::channel(true).0,
corpus: RwLock::new(Arc::new(Corpus::default())),
refresh_lock: AsyncMutex::new(()),
model: Mutex::new(None),
model_dir: OnceCell::new(),
model_retry: Mutex::new(None),
status: RwLock::new(Status::default()),
query_slots: Semaphore::new(2),
pending: Mutex::new(VecDeque::new()),
})
})
}
}
}
impl Manager {
pub fn status(&self) -> Status {
@@ -113,18 +116,29 @@ impl Manager {
.clone()
}
pub fn apply(&self, config: &crate::config::AppConfig) {
self.enabled
.store(config.lyrics_indexing_enabled, Ordering::Release);
self.set_enabled(config.lyrics_indexing_enabled, None);
}
fn set_enabled(&self, enabled: bool, snapshot: Option<&watch::Receiver<bool>>) -> bool {
let mut status = self.status.write().unwrap_or_else(|e| e.into_inner());
status.enabled = config.lyrics_indexing_enabled;
// A DB read started before an admin update must not undo that update.
if snapshot.is_some_and(|s| s.has_changed().unwrap_or(false)) {
return false;
}
self.enabled.send_if_modified(|old| {
let changed = *old != enabled;
*old = enabled;
changed
});
status.enabled = enabled;
if !status.enabled {
status.phase = "paused".into();
status.last_error = None;
} else if status.phase == "paused" {
status.phase = "indexing".into();
}
true
}
pub async fn boot(self: &Arc<Self>, config: &crate::config::AppConfig) {
self.apply(config);
if config.database_url.trim().is_empty() {
return;
}
@@ -141,43 +155,75 @@ impl Manager {
}
}
};
let mut settings = self.enabled.subscribe();
loop {
// Database overrides also apply on restart. Environment always wins.
if let Ok(Some(value)) = sqlx::query_scalar::<_, String>(
"SELECT value FROM furumusic__config_entry WHERE key='lyrics_indexing_enabled'",
)
.fetch_optional(&pool)
.await
{
let mut effective = config.clone();
if let Ok(value) = value.parse() {
effective.lyrics_indexing_enabled = value;
let delay = match self.worker_step(&pool, config, &mut settings).await {
Ok(delay) => delay,
Err(error) => {
self.error(format!("{error:#}"));
Duration::from_secs(30)
}
effective.apply_env_overrides();
self.apply(&effective);
};
tokio::select! {
_ = settings.changed() => (),
_ = tokio::time::sleep(delay) => (),
}
match self.refresh(&pool, false).await {
Ok(()) => {
if self.enabled.load(Ordering::Acquire) {
if let Err(error) = self.index_batch(&pool).await {
self.error(format!("{error:#}"));
tokio::time::sleep(Duration::from_secs(30)).await;
} else if !self
.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_empty()
{
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
}
}
Err(error) => self.error(format!("{error:#}")),
}
tokio::time::sleep(Duration::from_secs(30)).await;
}
}
async fn worker_step(
self: &Arc<Self>,
pool: &PgPool,
config: &crate::config::AppConfig,
settings: &mut watch::Receiver<bool>,
) -> Result<Duration> {
// Read the persisted switch before attempting the first download.
settings.borrow_and_update();
let value = sqlx::query_scalar::<_, String>(
"SELECT value FROM furumusic__config_entry WHERE key='lyrics_indexing_enabled'",
)
.fetch_optional(pool)
.await?;
let mut effective = config.clone();
if let Some(value) = value.and_then(|v| v.parse().ok()) {
effective.lyrics_indexing_enabled = value;
}
effective.apply_env_overrides();
if !self.set_enabled(effective.lyrics_indexing_enabled, Some(settings)) {
return Ok(Duration::ZERO);
}
let enabled = *settings.borrow_and_update();
if enabled && self.model_dir.get().is_none() {
self.status.write().unwrap_or_else(|e| e.into_inner()).phase = "downloading".into();
tokio::select! {
biased;
_ = settings.changed() => return Ok(Duration::ZERO),
result = self.model_dir.get_or_try_init(|| super::model_files::prepare(true)) => { result?; }
}
*self.model_retry.lock().unwrap_or_else(|e| e.into_inner()) = None;
let mut status = self.status.write().unwrap_or_else(|e| e.into_inner());
status.last_error = None;
status.phase = if status.ready_chunks == status.chunks {
"ready"
} else {
"indexing"
}
.into();
}
self.refresh(pool, false).await?;
if *self.enabled.borrow() {
self.index_batch(pool).await?;
if !self
.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_empty()
{
return Ok(Duration::from_millis(100));
}
}
Ok(Duration::from_secs(30))
}
fn error(&self, error: String) {
tracing::warn!(%error,"lyrics search");
let mut status = self.status.write().unwrap_or_else(|e| e.into_inner());
@@ -286,7 +332,10 @@ impl Manager {
.len();
status.ready_chunks = vectors.len();
status.stored_bytes = status.ready_chunks * DIMENSIONS * 4;
status.phase = if !self.enabled.load(Ordering::Acquire) {
if status.enabled && self.model_dir.get().is_none() {
return;
}
status.phase = if !status.enabled {
"paused"
} else if status.ready_chunks == status.chunks {
"ready"
@@ -295,22 +344,43 @@ impl Manager {
}
.into();
}
fn start_model_attempt(&self) -> Result<()> {
let mut retry = self.model_retry.lock().unwrap_or_else(|e| e.into_inner());
anyhow::ensure!(
!retry.is_some_and(|t| t.elapsed() < Duration::from_secs(60)),
"model unavailable; retry in one minute"
);
*retry = Some(Instant::now());
Ok(())
}
async fn embed(self: &Arc<Self>, texts: Vec<String>) -> Result<Vec<Vec<f32>>> {
// Search may use an earlier index while indexing is paused. Only the
// background worker downloads files; queries never wait for the download.
let dir = if let Some(dir) = self.model_dir.get() {
dir
} else if !*self.enabled.borrow() {
self.model_dir
.get_or_try_init(|| async {
self.start_model_attempt()?;
let dir = super::model_files::prepare(false).await?;
*self.model_retry.lock().unwrap_or_else(|e| e.into_inner()) = None;
Ok::<_, anyhow::Error>(dir)
})
.await?
} else {
anyhow::bail!("lyrics model is not ready");
}
.clone();
let manager = self.clone();
tokio::task::spawn_blocking(move || {
let mut model = manager.model.lock().unwrap_or_else(|e| e.into_inner());
if model.is_none() {
let mut retry = manager
manager.start_model_attempt()?;
*model = Some(load_model(&dir)?);
*manager
.model_retry
.lock()
.unwrap_or_else(|e| e.into_inner());
anyhow::ensure!(
!retry.is_some_and(|t| t.elapsed() < Duration::from_secs(60)),
"model unavailable; retry in one minute"
);
*retry = Some(Instant::now());
*model = Some(load_model()?);
*retry = None;
.unwrap_or_else(|e| e.into_inner()) = None;
}
let output = model
.as_mut()
@@ -485,17 +555,10 @@ impl Manager {
}
}
fn load_model() -> Result<TextEmbedding> {
let dir = std::env::var_os("FURU_LYRICS_MODEL_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| "/opt/furumusic/models/multilingual-e5-small".into());
fn load_model(dir: &Path) -> Result<TextEmbedding> {
let read = |file: &str| {
std::fs::read(dir.join(file)).with_context(|| {
format!(
"missing bundled model file {} (set FURU_LYRICS_MODEL_DIR for development)",
dir.join(file).display()
)
})
std::fs::read(dir.join(file))
.with_context(|| format!("reading {}", dir.join(file).display()))
};
let files = TokenizerFiles {
tokenizer_file: read("tokenizer.json")?,
@@ -981,10 +1044,11 @@ mod tests {
assert!(decode_vector(&[0; 4]).is_none());
assert!(decode_vector(&vec![0; DIMENSIONS * 4]).is_none());
}
#[test]
#[ignore = "requires bundled model; FURU_LYRICS_MODEL_DIR"]
fn real_e5_multilingual_retrieval() {
let mut model = load_model().unwrap();
#[tokio::test]
#[ignore = "requires cached E5 model; FURU_LYRICS_MODEL_DIR"]
async fn real_e5_multilingual_retrieval() {
let dir = crate::lyrics::model_files::prepare(false).await.unwrap();
let mut model = load_model(&dir).unwrap();
let v = model
.embed(
vec![
+52 -16
View File
@@ -2,7 +2,7 @@ use super::*;
use sqlx::Connection;
#[test]
#[ignore = "requires bundled E5 and the fixture prepared by tests/lyrics_rank_corpus.py"]
#[ignore = "requires cached E5 and the fixture prepared by tests/lyrics_rank_corpus.py"]
fn lyrics_ranking_quality() {
use std::collections::BTreeMap;
#[derive(serde::Deserialize)]
@@ -43,7 +43,7 @@ fn lyrics_ranking_quality() {
);
}
let mut model = load_model().unwrap();
let mut model = load_model(&crate::lyrics::model_files::directory()).unwrap();
let (hashes, inputs): (Vec<_>, Vec<_>) = passages.into_iter().unzip();
println!(
"{} documents, {} chunks, {} queries",
@@ -86,20 +86,29 @@ fn lyrics_ranking_quality() {
}
fn manager() -> Arc<Manager> {
Arc::new(Manager {
enabled: AtomicBool::new(true),
corpus: RwLock::new(Arc::new(Corpus::default())),
refresh_lock: AsyncMutex::new(()),
model: Mutex::new(None),
model_retry: Mutex::new(None),
status: RwLock::new(Status::default()),
query_slots: Semaphore::new(2),
pending: Mutex::new(VecDeque::new()),
})
Arc::new(Manager::default())
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL and bundled E5 model"]
async fn search_during_model_preparation_falls_back_without_opening_a_model() {
let manager = manager();
let error = manager.embed(vec!["query: snow".into()]).await.unwrap_err();
assert!(error.to_string().contains("not ready"));
assert!(manager.model_dir.get().is_none());
}
#[test]
fn delayed_database_setting_cannot_restart_an_index_disabled_by_the_admin() {
let manager = manager();
let snapshot = manager.enabled.subscribe();
manager.set_enabled(false, None);
assert!(!manager.set_enabled(true, Some(&snapshot)));
assert!(!manager.status().enabled);
assert_eq!(manager.status().phase, "paused");
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL and cached E5 model"]
async fn postgres_index_restart_edits_visibility_and_translations() {
let url = std::env::var("FURU_LYRICS_TEST_DATABASE_URL").unwrap();
let mut admin = sqlx::PgConnection::connect(&url).await.unwrap();
@@ -125,7 +134,9 @@ async fn postgres_index_restart_edits_visibility_and_translations() {
.connect(&url)
.await
.unwrap();
sqlx::raw_sql("CREATE TABLE furumusic__release(id BIGINT PRIMARY KEY,is_hidden BOOLEAN NOT NULL DEFAULT false);
sqlx::raw_sql("CREATE TABLE furumusic__config_entry(key TEXT PRIMARY KEY, value TEXT NOT NULL);
INSERT INTO furumusic__config_entry VALUES ('lyrics_indexing_enabled', 'false');
CREATE TABLE furumusic__release(id BIGINT PRIMARY KEY,is_hidden BOOLEAN NOT NULL DEFAULT false);
CREATE TABLE furumusic__media_file(id BIGINT PRIMARY KEY,sha256_hash TEXT NOT NULL);
CREATE TABLE furumusic__track(id BIGINT PRIMARY KEY,release_id BIGINT,audio_file_id BIGINT,is_hidden BOOLEAN NOT NULL DEFAULT false);
INSERT INTO furumusic__release(id) VALUES(1);
@@ -139,6 +150,31 @@ async fn postgres_index_restart_edits_visibility_and_translations() {
.execute(&pool)
.await
.unwrap();
let first = manager();
let mut settings = first.enabled.subscribe();
let config = crate::config::AppConfig::default();
first
.worker_step(&pool, &config, &mut settings)
.await
.unwrap();
assert!(
first.model_dir.get().is_none(),
"honour a persisted pause at startup"
);
sqlx::query(
"UPDATE furumusic__config_entry SET value='true' WHERE key='lyrics_indexing_enabled'",
)
.execute(&pool)
.await
.unwrap();
first
.worker_step(&pool, &config, &mut settings)
.await
.unwrap();
assert!(
first.model_dir.get().is_some(),
"prepare the model even with no lyrics yet"
);
for (hash, id, plain, lrc) in [
(
"first",
@@ -167,7 +203,7 @@ async fn postgres_index_restart_edits_visibility_and_translations() {
] {
sqlx::query("INSERT INTO furumusic__lyrics(audio_sha256,id,label,source,plain_text,synced_lrc) VALUES($1,$2,$2,'manual',$3,$4)").bind(hash).bind(id).bind(plain).bind(lrc).execute(&pool).await.unwrap();
}
let first = manager();
first.refresh(&pool, true).await.unwrap();
let lexical = first
.search(&pool, "просыпется снег на могилы", 10)
.await
@@ -202,7 +238,7 @@ async fn postgres_index_restart_edits_visibility_and_translations() {
restarted.pending.lock().unwrap().is_empty(),
"restart does not schedule cached fragments"
);
restarted.enabled.store(false, Ordering::Release);
restarted.enabled.send_replace(false);
let semantic = restarted
.search(&pool, "snow covering a cemetery, spring never comes", 10)
.await
+51 -5
View File
@@ -9,11 +9,13 @@ mod import_playlists;
mod jobs;
mod lastfm;
mod library_cleanup;
mod library_import;
mod local_uploads;
mod lyrics;
mod media_paths;
mod metrics;
mod music;
mod offline;
mod oidc;
mod player;
mod podcasts;
@@ -68,6 +70,7 @@ fn build_registry() -> Arc<JobRegistry> {
registry.register(jobs::lastfm_popularity::LastfmPopularityJob);
registry.register(jobs::lastfm_scrobble::LastfmScrobbleJob);
registry.register(podcasts::PodcastRefreshJob);
registry.register(library_import::LibraryImportJob);
Arc::new(registry)
}
@@ -85,18 +88,28 @@ async fn render_player(
i18n: I18n,
share_token: String,
) -> cot::Result<cot::response::Response> {
let guest = auth::get_session_user(&session, &db).await.is_none();
let identity = auth::checked_session_identity(&session, &db).await?;
let user = identity.as_ref().filter(|user| user.is_active());
let guest = user.is_none();
if guest && share_token.is_empty() {
if auth::get_session_identity(&session, &db).await.is_some() {
return Html::new(PendingTemplate { t: i18n.t }.render()?).into_response();
if identity.is_some() {
let mut response = Html::new(PendingTemplate { t: i18n.t }.render()?).into_response()?;
offline::identify(&mut response, 0);
return Ok(response);
}
return Ok(auth::redirect("/login"));
}
let (config, _) = AppConfig::load_with_db(&db).await;
Html::new(
let account_id = user.map_or(0, User::id_val);
if !guest {
metrics::record_active_user(account_id);
}
let is_member_shell = !guest && share_token.is_empty();
let mut response = Html::new(
player::PlayerPageTemplate {
t: i18n.t,
guest,
account_id,
share_token,
downloads_enabled: !guest && config.downloads_enabled,
torrent_downloads_enabled: !guest
@@ -108,7 +121,12 @@ async fn render_player(
}
.render()?,
)
.into_response()
.into_response()?;
response.headers_mut().insert("Cache-Control", "private, no-store".parse().unwrap());
if is_member_shell {
offline::identify(&mut response, account_id);
}
Ok(response)
}
#[derive(Debug, Template)]
@@ -285,6 +303,11 @@ impl App for FuruApp {
get(|| async { Ok::<_, cot::Error>(auth::redirect("/admin/")) }),
"admin_redirect",
),
Route::with_handler_and_name(
"/imports",
get(|| async { Ok::<_, cot::Error>(auth::redirect("/#imports")) }),
"imports_redirect",
),
Route::with_handler_and_name(
"/swagger",
get(|| async { Ok::<_, cot::Error>(auth::redirect("/swagger/")) }),
@@ -299,6 +322,16 @@ impl App for FuruApp {
),
Route::with_handler_and_name("/share/{token}", get(share_handler), "share"),
Route::with_handler_and_name("/auth/status", get(access_status), "access_status"),
Route::with_handler_and_name("/offline-worker.js", get(offline::worker), "offline_worker"),
Route::with_handler_and_name("/offline-catalog.js", get(offline::catalog), "offline_catalog"),
Route::with_handler_and_name("/offline-probe", get(offline::probe), "offline_probe"),
Route::with_handler_and_name("/player.webmanifest", get(offline::manifest), "player_manifest"),
Route::with_handler_and_name("/player-icon.svg", get(offline::icon), "player_icon"),
Route::with_handler_and_name(
"/vendor/fflate-0.8.2.js",
get(offline::fflate),
"vendor_fflate",
),
Route::with_handler_and_name(
"/metrics",
get({
@@ -567,6 +600,12 @@ impl Project for FuruProject {
similarity::handle().boot(&similarity_config).await;
});
// Resume interrupted imports and restart workers whose lease expired.
library_import::job::spawn_boot(
Arc::clone(&self.app_config),
Arc::clone(&self.scheduler_handle),
);
let lyrics_config = Arc::clone(&self.app_config);
tokio::spawn(async move {
lyrics::search::handle().boot(&lyrics_config).await;
@@ -593,6 +632,13 @@ impl Project for FuruProject {
podcasts::PodcastApp::new(Arc::clone(&self.app_config)),
"/api/podcasts",
);
apps.register_with_views(
library_import::ImportApp::new(
Arc::clone(&self.app_config),
Arc::clone(&self.scheduler_handle),
),
"/api/imports",
);
apps.register_with_views(
player::PlayerApp::new(
Arc::clone(&self.app_config),
+160
View File
@@ -2930,7 +2930,167 @@ pub mod db_migrations {
)];
const OPERATIONS: &'static [Operation] = &[Operation::custom(create_lyrics_search).build()];
}
#[cot::db::migrations::migration_op]
async fn create_sidebar_pins(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> {
ctx.db
.raw(include_str!("../player/sidebar_pins.sql"))
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0058CreateSidebarPins;
impl migrations::Migration for M0058CreateSidebarPins {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0058_create_sidebar_pins";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0057_create_lyrics_search",
)];
const OPERATIONS: &'static [Operation] = &[Operation::custom(create_sidebar_pins).build()];
}
#[cot::db::migrations::migration_op]
async fn add_sidebar_pin_order(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> {
ctx.db
.raw(include_str!("../player/sidebar_pin_order.sql"))
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0059AddSidebarPinOrder;
impl migrations::Migration for M0059AddSidebarPinOrder {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0059_add_sidebar_pin_order";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0058_create_sidebar_pins",
)];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(add_sidebar_pin_order).build()];
}
#[cot::db::migrations::migration_op]
async fn repair_legacy_web_listen_durations(
ctx: migrations::MigrationContext<'_>,
) -> cot::db::Result<()> {
ctx.db
.raw(include_str!(
"../player/repair_legacy_web_listen_durations.sql"
))
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0060RepairLegacyWebListenDurations;
impl migrations::Migration for M0060RepairLegacyWebListenDurations {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0060_repair_legacy_web_listen_durations";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0059_add_sidebar_pin_order",
)];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(repair_legacy_web_listen_durations).build()];
}
#[cot::db::migrations::migration_op]
async fn add_playlist_artwork(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> {
ctx.db
.raw(include_str!("../player/playlist_artwork_schema.sql"))
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0061AddPlaylistArtwork;
impl migrations::Migration for M0061AddPlaylistArtwork {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0061_add_playlist_artwork";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0060_repair_legacy_web_listen_durations",
)];
const OPERATIONS: &'static [Operation] = &[Operation::custom(add_playlist_artwork).build()];
}
#[cot::db::migrations::migration_op]
async fn repair_like_aliases(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> {
ctx.db.raw(
"CREATE INDEX idx_fed_like_content_user ON furumusic__fed_state_like(content_id,user_id)"
).await?;
ctx.db
.raw(include_str!(
"../federation/devices/track_content_alias.sql"
))
.await?;
ctx.db
.raw(include_str!(
"../federation/devices/repair_like_aliases.sql"
))
.await?;
ctx.db
.raw(
"UPDATE furumusic__fed_state_like f SET local_track_id=l.track_id
FROM furumusic__user_liked_track l
JOIN furumusic__track_content_alias a ON a.track_id=l.track_id
WHERE f.user_id=l.user_id AND f.content_id=a.content_id AND f.liked
AND NOT a.hidden AND f.local_track_id IS DISTINCT FROM l.track_id",
)
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0062RepairLikeAliases;
impl migrations::Migration for M0062RepairLikeAliases {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0062_repair_like_aliases";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0061_add_playlist_artwork",
)];
const OPERATIONS: &'static [Operation] = &[Operation::custom(repair_like_aliases).build()];
}
#[cot::db::migrations::migration_op]
async fn add_download_history(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> {
for statement in include_str!("../player/download_history_schema.sql").split(';') {
if !statement.trim().is_empty() {
ctx.db.raw(statement).await?;
}
}
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0063DownloadHistory;
impl migrations::Migration for M0063DownloadHistory {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0063_download_history";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0062_repair_like_aliases",
)];
const OPERATIONS: &'static [Operation] = &[Operation::custom(add_download_history).build()];
}
pub const MIGRATIONS: &[&SyncDynMigration] = &[
&M0063DownloadHistory,
&M0062RepairLikeAliases,
&M0061AddPlaylistArtwork,
&M0060RepairLegacyWebListenDurations,
&M0059AddSidebarPinOrder,
&M0058CreateSidebarPins,
&M0057CreateLyricsSearch,
&M0056CreateLyrics,
&M0006CreateMediaFile,
+69
View File
@@ -0,0 +1,69 @@
use cot::Body;
use cot::db::Database;
use cot::http::{HeaderValue, Response, StatusCode};
use cot::session::Session;
pub(crate) const CATALOG: &str = include_str!("player/offline-catalog.js");
fn asset(content_type: &'static str, body: &'static str) -> cot::Result<Response<Body>> {
Ok(Response::builder()
.header("Content-Type", content_type)
.header("Cache-Control", "no-cache")
.header("X-Content-Type-Options", "nosniff")
.body(Body::fixed(body))
.expect("valid offline asset"))
}
pub(crate) fn identify(response: &mut Response<Body>, account_id: i64) {
response.headers_mut().insert(
"X-Furumusic-Player-Account",
HeaderValue::from_str(&account_id.to_string()).expect("numeric account id"),
);
}
pub(crate) async fn worker() -> cot::Result<Response<Body>> {
asset(
"text/javascript; charset=utf-8",
include_str!("player/offline-worker.js"),
)
}
pub(crate) async fn catalog() -> cot::Result<Response<Body>> {
asset("text/javascript; charset=utf-8", CATALOG)
}
pub(crate) async fn manifest() -> cot::Result<Response<Body>> {
asset(
"application/manifest+json",
include_str!("player/player.webmanifest"),
)
}
pub(crate) async fn icon() -> cot::Result<Response<Body>> {
asset("image/svg+xml", include_str!("player/player-icon.svg"))
}
/// The ZIP reader of the library import wizard, loaded only when a user picks
/// an export archive. The version is part of the path.
pub(crate) async fn fflate() -> cot::Result<Response<Body>> {
asset(
"text/javascript; charset=utf-8",
include_str!("player/vendor/fflate-0.8.2.min.js"),
)
}
pub(crate) async fn probe(session: Session, db: Database) -> cot::Result<Response<Body>> {
let identity = crate::auth::checked_session_identity(&session, &db).await?;
let user = identity.filter(|user| user.is_active());
let mut response = Response::builder()
.header("Cache-Control", "private, no-store")
.status(if user.is_some() {
StatusCode::NO_CONTENT
} else {
StatusCode::UNAUTHORIZED
})
.body(Body::empty())
.expect("valid reachability response");
identify(&mut response, user.map_or(0, |u| u.id_val()));
Ok(response)
}
+109
View File
@@ -0,0 +1,109 @@
use super::{SearchArtistRow, helpers, load_artist_detail};
use sqlx::postgres::PgPoolOptions;
#[tokio::test]
#[ignore = "requires FURU_ARTIST_TEST_DATABASE_URL pointing to PostgreSQL"]
async fn artist_credits_include_visible_features_and_count_each_track_once() -> anyhow::Result<()> {
let pool = PgPoolOptions::new()
.max_connections(1)
.connect(&std::env::var("FURU_ARTIST_TEST_DATABASE_URL")?)
.await?;
let schema = format!("artist_{}", uuid::Uuid::new_v4().simple());
sqlx::raw_sql(&format!(
"BEGIN; CREATE SCHEMA {schema}; SET LOCAL search_path TO {schema}, public;
CREATE COLLATION furumusic_unicode (provider=icu, locale='und', deterministic=true);"
))
.execute(&pool)
.await?;
sqlx::raw_sql(
r#"
CREATE TEMP TABLE furumusic__artist (
id bigint, name text, image_file_id bigint, is_hidden bool DEFAULT false);
CREATE TEMP TABLE furumusic__release (
id bigint, title text, title_sort text, release_type text DEFAULT 'album', year int,
cover_file_id bigint, is_hidden bool DEFAULT false);
CREATE TEMP TABLE furumusic__track (
id bigint, title text, release_id bigint, audio_file_id bigint, track_number int,
disc_number int, duration_seconds float8 DEFAULT 120, cover_file_id bigint,
lastfm_listeners bigint, lastfm_playcount bigint, lastfm_rating float8,
lastfm_updated_at text, is_hidden bool DEFAULT false);
CREATE TEMP TABLE furumusic__media_file (
id bigint, sha256_hash text, uploader_name text, audio_format text, audio_bitrate int,
audio_sample_rate int, audio_bit_depth int, file_size_bytes bigint);
CREATE TEMP TABLE furumusic__release_artist (artist_id bigint, release_id bigint);
CREATE TEMP TABLE furumusic__track_artist (artist_id bigint, track_id bigint, position int, role text);
CREATE TEMP TABLE furumusic__play_history (track_id bigint);
CREATE TEMP TABLE furumusic__lyrics (audio_sha256 text);
CREATE TEMP TABLE furumusic__federation_content_id_cache (media_file_id bigint, sha256_hash text, content_id text);
INSERT INTO furumusic__artist (id,name) VALUES (1,'Кизиль'),(2,'Трагедия Всей Жизни');
INSERT INTO furumusic__release (id,title,cover_file_id,is_hidden)
VALUES (10,'13/87',123,false),(11,'Hidden release',NULL,true),(12,'Compilation',NULL,false);
INSERT INTO furumusic__release_artist VALUES (2,10);
INSERT INTO furumusic__track (id,title,release_id,audio_file_id,is_hidden) VALUES
(20,'Диагноз',10,30,false),(21,'Hidden track',10,NULL,true),(22,'Hidden release track',11,NULL,false),
(23,'Only release credit',10,31,false),(24,'Only track credit',12,NULL,false);
INSERT INTO furumusic__track_artist VALUES
(2,20,0,'main'),(1,20,1,'featuring'),(1,21,1,'featuring'),(1,22,1,'featuring'),(2,24,0,'main');
INSERT INTO furumusic__media_file (id,sha256_hash,uploader_name) VALUES (30,'abc','test'),(31,'new','test');
INSERT INTO furumusic__federation_content_id_cache VALUES (30,'abc','valid-id'),(31,'old','stale-id');
INSERT INTO furumusic__play_history VALUES (20),(20),(21),(22),(23),(24);
"#,
)
.execute(&pool)
.await?;
let guest = load_artist_detail(&pool, 1).await?.unwrap();
assert!(guest.releases.is_empty());
assert!(guest.top_tracks.is_empty());
assert_eq!(guest.total_track_count, 1);
assert_eq!(guest.total_play_count, 2);
assert_eq!(guest.track_content_ids, ["valid-id"]);
assert_eq!(guest.featured_tracks.len(), 1);
let track = &guest.featured_tracks[0];
assert_eq!(track.id, 20);
assert_eq!(track.content_id.as_deref(), Some("valid-id"));
assert_eq!(track.stream_url, "/api/player/stream/20");
assert_eq!(
track.cover_url.as_deref(),
Some("/api/player/cover/123/medium")
);
assert_eq!(track.uploader_name, "test");
assert_eq!(track.artists[0].id, 2);
assert_eq!(track.featured_artists[0].id, 1);
let main = load_artist_detail(&pool, 2).await?.unwrap();
assert_eq!(main.releases.len(), 1);
assert_eq!(main.total_track_count, 3);
assert_eq!(main.total_play_count, 4);
assert_eq!(main.track_content_ids, ["valid-id"]);
let top_ids: Vec<_> = main.top_tracks.iter().map(|track| track.id).collect();
assert_eq!(top_ids, [20, 23, 24]);
let rows = [&guest, &main].map(|artist| SearchArtistRow {
id: artist.id,
name: artist.name.clone(),
image_file_id: None,
release_count: artist.releases.len() as i64,
});
let cards = helpers::artist_cards(&pool, rows.into(), "medium").await?;
assert_eq!((cards[0].release_count, cards[0].track_count), (0, 1));
assert_eq!((cards[1].release_count, cards[1].track_count), (1, 3));
// Rank titles by their best recording, retaining every version even below the 50-title cutoff.
sqlx::raw_sql(
r#"UPDATE furumusic__track SET title = 'За дверью' WHERE id = 20;
INSERT INTO furumusic__track (id,title,release_id,lastfm_rating,lastfm_playcount) VALUES
(100,'ЗА ДВЕРЬЮ',10,90,100), (101,' за Дверью ',10,90,120);
INSERT INTO furumusic__track (id,title,release_id,lastfm_rating)
SELECT id, 'Song ' || id, 10, 10 FROM generate_series(1000,1049) id;"#,
)
.execute(&pool)
.await?;
let popular = load_artist_detail(&pool, 2).await?.unwrap().top_tracks;
let ids: Vec<_> = popular.iter().map(|track| track.id).collect();
let expected: Vec<_> = [101, 100, 20].into_iter().chain(1000..1049).collect();
assert_eq!(ids, expected);
sqlx::query("ROLLBACK").execute(&pool).await?;
Ok(())
}
+394
View File
@@ -0,0 +1,394 @@
use super::*;
use sqlx::{FromRow, PgPool};
use tokio::sync::OnceCell;
#[cfg(test)]
#[path = "download_history_tests.rs"]
mod tests;
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Source {
Files,
Torrents,
Youtube,
}
impl Source {
fn name(&self) -> &'static str {
match self {
Self::Files => "files",
Self::Torrents => "torrents",
Self::Youtube => "youtube",
}
}
}
#[derive(Deserialize)]
struct Key {
source: Source,
id: String,
}
#[derive(Deserialize)]
struct Hide {
items: Vec<Key>,
}
#[derive(Deserialize)]
struct Query {
limit: Option<i64>,
offset: Option<i64>,
source: Option<Source>,
id: Option<String>,
}
#[derive(Serialize, FromRow)]
struct Entry {
source: String,
id: String,
title: Option<String>,
status: String,
created_at: String,
updated_at: String,
item_count: i64,
progress_percent: Option<f64>,
error: Option<String>,
#[serde(skip)]
processed: bool,
}
#[derive(Serialize, FromRow)]
struct Stats {
tracks: i64,
releases: i64,
}
#[derive(Serialize)]
struct Page {
items: Vec<Entry>,
stats: Stats,
has_more: bool,
}
async fn keys(
pool: &PgPool,
user: i64,
offset: i64,
limit: i64,
entry: Option<(&Source, &str)>,
) -> sqlx::Result<Vec<(String, String)>> {
sqlx::query_as(
"SELECT source,id FROM (
SELECT 'files' AS source, batch_id AS id, min(created_at) AS added
FROM furumusic__local_upload WHERE user_id=$1 GROUP BY batch_id
UNION ALL SELECT 'torrents',id,created_at FROM furumusic__torrent_session WHERE user_id=$1
UNION ALL SELECT 'youtube',id,created_at FROM furumusic__youtube_download WHERE user_id=$1
) jobs WHERE ($4::text IS NULL OR (source=$4 AND id=$5))
AND NOT EXISTS (
SELECT 1 FROM furumusic__hidden_download h
WHERE h.user_id=$1 AND h.source=jobs.source AND h.download_id=jobs.id
) ORDER BY added DESC,source,id LIMIT $2 OFFSET $3"
)
.bind(user)
.bind(limit)
.bind(offset)
.bind(entry.map(|(source,_)| source.name()))
.bind(entry.map(|(_,id)| id))
.fetch_all(pool)
.await
}
async fn stats(pool: &PgPool, user: i64) -> sqlx::Result<Stats> {
sqlx::query_as(
"SELECT count(*) AS tracks,count(DISTINCT t.release_id) AS releases
FROM furumusic__track t JOIN furumusic__media_file f ON f.id=t.audio_file_id
WHERE f.uploaded_by_user_id=$1",
)
.bind(user)
.fetch_one(pool)
.await
}
async fn summaries(
pool: &PgPool,
user: i64,
sources: &[String],
ids: &[String],
) -> sqlx::Result<Vec<Entry>> {
sqlx::query_as(include_str!("download_history_summary.sql"))
.bind(user)
.bind(sources)
.bind(ids)
.fetch_all(pool)
.await
}
async fn hide(pool: &PgPool, user: i64, items: &[Key]) -> sqlx::Result<()> {
let sources: Vec<_> = items.iter().map(|item| item.source.name()).collect();
let ids: Vec<_> = items.iter().map(|item| item.id.as_str()).collect();
sqlx::query(
"INSERT INTO furumusic__hidden_download(user_id, source, download_id)
SELECT DISTINCT $1,source,id FROM unnest($2::text[],$3::text[]) wanted(source,id)
WHERE CASE source
WHEN 'files' THEN EXISTS (SELECT 1 FROM furumusic__local_upload f WHERE f.user_id=$1 AND f.batch_id=wanted.id)
WHEN 'torrents' THEN EXISTS (SELECT 1 FROM furumusic__torrent_session t WHERE t.user_id=$1 AND t.id=wanted.id)
WHEN 'youtube' THEN EXISTS (SELECT 1 FROM furumusic__youtube_download y WHERE y.user_id=$1 AND y.id=wanted.id)
END ON CONFLICT DO NOTHING"
)
.bind(user)
.bind(sources)
.bind(ids)
.execute(pool)
.await?;
Ok(())
}
// Discovery discards exact duplicates without creating a review record. The
// inbox is authoritative until all audio has been moved or deduplicated.
async fn has_inbox_audio(dir: &std::path::Path) -> std::io::Result<bool> {
let mut pending = vec![dir.to_owned()];
while let Some(dir) = pending.pop() {
let mut entries = match tokio::fs::read_dir(dir).await {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(e),
};
while let Some(entry) = entries.next_entry().await? {
let filename = entry.file_name();
let name = filename.to_string_lossy();
if name.starts_with('.') {
continue;
}
let kind = entry.file_type().await?;
if kind.is_dir() {
pending.push(entry.path());
} else if kind.is_file() && crate::jobs::inbox_discover::is_audio_file(&name) {
return Ok(true);
}
}
}
Ok(false)
}
async fn torrent_status(
pool: &PgPool,
user: i64,
inbox: Option<&std::path::Path>,
service: &TorrentService,
item: &mut Entry,
) -> anyhow::Result<()> {
if matches!(item.status.as_str(), "downloading" | "moving") {
if let Some(progress) = service.live_progress(user, &item.id).await {
item.progress_percent = Some(progress);
} else {
item.status = "paused".into();
}
}
if item.status == "complete" && !item.processed {
let Some(inbox) = inbox else {
item.status = "awaiting_ai".into();
return Ok(());
};
let dir = inbox
.join("user_uploads")
.join(user.to_string())
.join(format!("torrent-{}", item.id));
if has_inbox_audio(&dir).await? {
item.status = "awaiting_ai".into();
} else {
sqlx::query("UPDATE furumusic__torrent_session SET history_processed=true
WHERE user_id=$1 AND id=$2 AND status='complete' AND updated_at=$3 AND NOT history_processed")
.bind(user).bind(&item.id).bind(&item.updated_at).execute(pool).await?;
}
}
Ok(())
}
#[derive(Clone)]
pub(super) struct Services {
pub pool: Arc<OnceCell<PgPool>>,
pub config: Arc<AppConfig>,
pub torrents: Arc<OnceCell<Arc<TorrentService>>>,
pub youtube: Arc<OnceCell<Arc<YouTubeService>>>,
pub scheduler: Arc<OnceCell<Arc<SchedulerHandle>>>,
}
impl Services {
async fn pool(&self) -> cot::Result<&PgPool> {
self.pool
.get_or_try_init(|| {
sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&self.config.database_url)
})
.await
.map_err(|e| cot::Error::internal(e.to_string()))
}
async fn page(
&self,
db: &Database,
user: i64,
config: &AppConfig,
query: Query,
) -> anyhow::Result<Page> {
let pool = self.pool().await?;
let entry = query.source.as_ref().zip(query.id.as_deref());
let limit = if entry.is_some() {
1
} else {
query.limit.unwrap_or(30).clamp(1, 200)
};
let offset = if entry.is_some() {
0
} else {
query.offset.unwrap_or(0).max(0)
};
let (mut page, stats) = tokio::try_join!(
keys(pool, user, offset, limit + 1, entry),
stats(pool, user)
)?;
let has_more = page.len() as i64 > limit;
page.truncate(limit as usize);
let (sources, ids): (Vec<_>, Vec<_>) = page.into_iter().unzip();
let ids_for = |kind: &str| {
sources
.iter()
.zip(&ids)
.filter(|(s, _)| s.as_str() == kind)
.map(|(_, id)| id.clone())
.collect::<Vec<_>>()
};
let local = ids_for("files");
let youtube = ids_for("youtube");
let inbox = config.agent_inbox_dir.trim();
let root = crate::media_paths::resolve_config_path_buf(inbox);
let inbox_available =
!inbox.is_empty() && tokio::fs::metadata(&root).await.is_ok_and(|m| m.is_dir());
if !local.is_empty()
&& inbox_available
&& let Err(error) =
crate::local_uploads::sync_statuses(pool, user, inbox, Some(&local)).await
{
tracing::warn!(user, %error, "could not refresh local upload status");
}
if !youtube.is_empty()
&& let Err(error) = crate::youtube::sync_ai_statuses(pool, user, Some(&youtube)).await
{
tracing::warn!(user, %error, "could not refresh YouTube import status");
}
let torrents = self
.torrents
.get_or_init(|| async { Arc::new(TorrentService::new(self.scheduler.clone())) })
.await;
if config.torrent_downloads_enabled
&& let Ok(proxy) = config.torrent_proxy_url()
&& let Err(error) = torrents.resume_pending(pool, user, proxy).await
{
tracing::warn!(user, %error, "could not resume pending magnets");
}
if config.youtube_downloads_enabled
&& inbox_available
&& let Err(error) = self.resume_youtube(pool, db, config, user).await
{
tracing::warn!(user, %error, "could not resume pending YouTube downloads");
}
let mut items = summaries(pool, user, &sources, &ids).await?;
for item in items.iter_mut().filter(|item| item.source == "torrents") {
if let Err(error) = torrent_status(
pool,
user,
inbox_available.then_some(root.as_path()),
torrents,
item,
)
.await
{
tracing::warn!(user, id=item.id, %error, "could not verify torrent import status");
item.status = "awaiting_ai".into();
}
}
Ok(Page {
items,
stats,
has_more,
})
}
async fn resume_youtube(
&self,
pool: &PgPool,
db: &Database,
config: &AppConfig,
user: i64,
) -> anyhow::Result<()> {
let service = self
.youtube
.get_or_init(|| async { Arc::new(YouTubeService::new(self.scheduler.clone())) })
.await;
let jobs = service.pending_jobs(pool, user).await?;
if !jobs.is_empty() {
let cookies =
crate::youtube::selected_cookie_contents(db, &config.youtube_cookie_id).await?;
service
.resume_jobs(pool, jobs, config, config.youtube_proxy_url()?, cookies)
.await;
}
Ok(())
}
pub(super) fn routes(self) -> [Route; 2] {
let read = self.clone();
let list = get(
move |auth_ctx, session, db, UrlQuery(query): UrlQuery<Query>| {
let read = read.clone();
async move {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let (config, _) = AppConfig::load_with_db(&db).await;
if let Err(error) = require_download_method(&config, DownloadMethod::LocalFile)
{
return Ok(error);
}
if query.source.is_some() != query.id.is_some()
|| query
.id
.as_ref()
.is_some_and(|id| id.trim().is_empty() || id.len() > 36)
{
return Ok(json_error(
StatusCode::BAD_REQUEST,
"expected a download source and ID together",
));
}
let page = read
.page(&db, user.id, &config, query)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
Json(page).into_response()
}
},
);
let remove = post(move |auth_ctx, session, db, Json(body): Json<Hide>| {
let services = self.clone();
async move {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let (config, _) = AppConfig::load_with_db(&db).await;
if let Err(error) = require_download_method(&config, DownloadMethod::LocalFile) {
return Ok(error);
}
hide(services.pool().await?, user.id, &body.items)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
Json(serde_json::json!({"ok":true})).into_response()
}
});
[
Route::with_handler_and_name("/downloads/history", list, "player_download_history"),
Route::with_handler_and_name(
"/downloads/history/hide",
remove,
"player_download_history_hide",
),
]
}
}
+18
View File
@@ -0,0 +1,18 @@
-- Older clients store the true upload batch in its server-assigned inbox directory.
ALTER TABLE furumusic__local_upload ADD COLUMN IF NOT EXISTS batch_id text GENERATED ALWAYS AS (
COALESCE(substring(replace(inbox_path, chr(92), '/') from
'^user_uploads/[0-9]+/local-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/'), id)
) STORED;
CREATE INDEX IF NOT EXISTS idx_local_upload_batch ON furumusic__local_upload(user_id,batch_id,created_at);
ALTER TABLE furumusic__torrent_session ADD COLUMN IF NOT EXISTS history_item_count integer GENERATED ALWAYS AS (
CASE WHEN selected_files_json = '[]' THEN json_array_length(files_json::json)
ELSE json_array_length(selected_files_json::json) END
) STORED;
ALTER TABLE furumusic__torrent_session ADD COLUMN IF NOT EXISTS history_processed boolean NOT NULL DEFAULT false;
CREATE INDEX IF NOT EXISTS idx_pending_review_upload_directory ON furumusic__pending_review
((split_part(input_path,'/',2)), (split_part(input_path,'/',3)))
WHERE split_part(input_path,'/',1)='user_uploads';
CREATE TABLE IF NOT EXISTS furumusic__hidden_download (
user_id bigint NOT NULL, source text NOT NULL, download_id text NOT NULL,
PRIMARY KEY (user_id, source, download_id)
);
+58
View File
@@ -0,0 +1,58 @@
WITH wanted AS (
SELECT * FROM unnest($2::text[],$3::text[]) WITH ORDINALITY w(source,id,position)
WHERE NOT EXISTS (SELECT 1 FROM furumusic__hidden_download h
WHERE h.user_id=$1 AND h.source=w.source AND h.download_id=w.id)
), jobs AS (
SELECT w.position,w.source,w.id,
CASE WHEN count(*)=1 THEN min(regexp_replace(f.filename,'^.*/',''))
WHEN bool_and(strpos(f.filename,'/')>0)
AND min(split_part(f.filename,'/',1))=max(split_part(f.filename,'/',1))
THEN min(split_part(f.filename,'/',1)) END AS title,
CASE WHEN bool_or(f.status='uploading') THEN 'uploading'
WHEN bool_or(f.status='ai_processing') THEN 'ai_processing'
WHEN bool_or(f.status='queued') THEN 'queued'
WHEN bool_or(f.status='needs_review') THEN 'needs_review'
WHEN bool_and(f.status='failed') THEN 'failed'
WHEN bool_and(f.status='cancelled') THEN 'cancelled'
WHEN bool_or(f.status IN ('failed','cancelled')) THEN 'complete_with_errors'
ELSE 'complete' END AS status,
min(f.created_at) AS created_at, max(f.updated_at) AS updated_at, count(*) AS item_count,
CASE WHEN count(*)>1 THEN 100.0::float8 * count(*) FILTER (WHERE f.status='complete') / count(*) END AS progress_percent,
min(f.error) FILTER (WHERE f.status='failed') AS error, false AS processed
FROM wanted w JOIN (
SELECT batch_id,replace(filename,chr(92),'/') AS filename,status,created_at,updated_at,error
FROM furumusic__local_upload WHERE user_id=$1
) f ON w.source='files' AND w.id=f.batch_id
GROUP BY w.position,w.source,w.id
UNION ALL
SELECT w.position,w.source,w.id,t.name,
CASE WHEN review.processing THEN 'ai_processing'
WHEN review.queued THEN 'awaiting_ai'
WHEN review.failed THEN 'ai_failed'
WHEN review.pending THEN 'needs_review'
WHEN review.cancelled THEN 'cancelled'
WHEN review.partly_cancelled THEN 'complete_with_errors'
ELSE t.status END,
t.created_at,t.updated_at,t.history_item_count::bigint,
CASE WHEN t.status='downloading' THEN t.progress_percent END,
coalesce(t.error,review.error), t.history_processed
FROM wanted w JOIN furumusic__torrent_session t ON w.source='torrents' AND w.id=t.id AND t.user_id=$1
LEFT JOIN LATERAL (
SELECT bool_or(r.status='processing') AS processing, bool_or(r.status='queued') AS queued,
bool_or(r.status='failed') AS failed, bool_or(r.status IN ('rejected','pending')) AS pending,
bool_and(r.status='cancelled') AS cancelled, bool_or(r.status='cancelled') AS partly_cancelled,
min(r.error_message) FILTER (WHERE r.status='failed') AS error
FROM furumusic__upload_review_state r WHERE t.status='complete' AND NOT t.history_processed
AND split_part(r.input_path,'/',1)='user_uploads' AND split_part(r.input_path,'/',2)=t.user_id::text
AND split_part(r.input_path,'/',3)='torrent-'||t.id
) review ON true
UNION ALL
SELECT w.position,w.source,w.id,coalesce(nullif(y.title,''),y.source_url),y.status,
y.created_at,y.updated_at,y.total_items::bigint,
CASE WHEN y.status='downloading' THEN
(SELECT avg(i.progress_percent) FROM furumusic__youtube_download_item i WHERE i.job_id=y.id) END,
y.error,false
FROM wanted w JOIN furumusic__youtube_download y ON w.source='youtube' AND w.id=y.id AND y.user_id=$1
)
SELECT source,id,title,status,created_at,updated_at,item_count,progress_percent,error,processed
FROM jobs ORDER BY position
+165
View File
@@ -0,0 +1,165 @@
use super::*;
#[tokio::test]
#[ignore = "requires a disposable PostgreSQL database in FURU_IMPORT_TEST_DATABASE_URL"]
async fn batches_group_before_pagination_and_hiding_preserves_imports() -> anyhow::Result<()> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&std::env::var("FURU_IMPORT_TEST_DATABASE_URL")?)
.await?;
// Isolate the complete migration (which creates permanent relations) in
// this test's own schema on a single connection.
let schema = format!("history_{}", uuid::Uuid::new_v4().simple());
sqlx::raw_sql(&format!(
"CREATE SCHEMA {schema}; SET search_path TO {schema};"
))
.execute(&pool)
.await?;
sqlx::raw_sql(r#"
CREATE TABLE furumusic__local_upload (id text PRIMARY KEY,user_id bigint,filename text,
inbox_path text,status text,error text,created_at text DEFAULT '01',updated_at text DEFAULT '01');
CREATE TABLE furumusic__youtube_download (id text PRIMARY KEY,user_id bigint,title text,source_url text,
total_items integer,status text,error text,created_at text DEFAULT '02',updated_at text DEFAULT '02');
CREATE TABLE furumusic__youtube_download_item(job_id text, progress_percent double precision);
CREATE TABLE furumusic__torrent_session(id text PRIMARY KEY,user_id bigint,name text,selected_files_json text,files_json text,
status text, progress_percent double precision,error text,created_at text DEFAULT '03',updated_at text DEFAULT '03');
CREATE TABLE furumusic__pending_review(input_path text,status text,error_message text,id bigserial PRIMARY KEY);
CREATE TABLE furumusic__media_file(id bigint,uploaded_by_user_id bigint);
CREATE TABLE furumusic__track(audio_file_id bigint,release_id bigint);
INSERT INTO furumusic__media_file VALUES (1,1),(2,1),(3,2);
INSERT INTO furumusic__track VALUES (1,10),(2,10),(3,20);
INSERT INTO furumusic__youtube_download(id,user_id,title,total_items,status) VALUES ('same',1,'Mix',2,'downloading');
INSERT INTO furumusic__youtube_download_item VALUES ('same',100),('same',20);
INSERT INTO furumusic__torrent_session(id,user_id,name,selected_files_json,files_json,status)
VALUES ('same',1,'Album','[1]','[1,2,3]','complete'),('other',2,'Other','[]','[5,6]','complete');
INSERT INTO furumusic__pending_review VALUES ('user_uploads/1/torrent-same/Album/a.flac','processing',null);
INSERT INTO furumusic__local_upload(id,user_id,filename,inbox_path,status)
SELECT i::text,1,'Disc/'||i||'.mp3','user_uploads/1/local-12345678-1234-1234-1234-123456789abc/Disc/'||i||'.mp3',
CASE WHEN i=105 THEN 'failed' ELSE 'complete' END FROM generate_series(1,105) AS i;
INSERT INTO furumusic__local_upload(id,user_id,filename,inbox_path,status)
VALUES ('legacy',1,'Song.mp3','older/location/song.mp3','complete'),
('second-user',2,'Own.mp3','user_uploads/2/local-12345678-1234-1234-1234-123456789abc/Own.mp3','complete');
"#).execute(&pool).await?;
sqlx::raw_sql(include_str!("download_history_schema.sql"))
.execute(&pool)
.await?;
sqlx::raw_sql(include_str!("../scheduler/review_dismissal_schema.sql"))
.execute(&pool)
.await?;
let batch = "12345678-1234-1234-1234-123456789abc";
let key_list = keys(&pool, 1, 0, 100, None).await?;
assert_eq!(key_list.len(), 4);
assert_eq!(keys(&pool, 1, 1, 2, None).await?, key_list[1..3]);
assert_eq!(
keys(&pool, 1, 0, 1, Some((&Source::Youtube, "same"))).await?,
vec![("youtube".into(), "same".into())]
);
let (sources, ids): (Vec<_>, Vec<_>) = key_list.into_iter().unzip();
let rows = summaries(&pool, 1, &sources, &ids).await?;
assert_eq!(
(
rows[0].source.as_str(),
rows[0].status.as_str(),
rows[0].item_count
),
("torrents", "ai_processing", 1)
);
assert_eq!(rows[1].progress_percent, Some(60.0));
let files = rows.iter().find(|r| r.id == batch).unwrap();
assert_eq!(
(
files.item_count,
files.title.as_deref(),
files.status.as_str()
),
(105, Some("Disc"), "complete_with_errors")
);
let selection = vec![
Key {
source: Source::Files,
id: batch.into(),
},
Key {
source: Source::Youtube,
id: "same".into(),
},
Key {
source: Source::Torrents,
id: "other".into(),
},
];
hide(&pool, 1, &selection).await?;
hide(&pool, 1, &selection).await?;
assert_eq!(
keys(&pool, 1, 0, 100, None).await?,
vec![
("torrents".into(), "same".into()),
("files".into(), "legacy".into())
]
);
assert_eq!(keys(&pool, 2, 0, 100, None).await?.len(), 2);
assert!(
keys(&pool, 1, 0, 1, Some((&Source::Youtube, "same")))
.await?
.is_empty()
);
let stats = stats(&pool, 1).await?;
assert_eq!((stats.tracks, stats.releases), (2, 1));
let counts:(i64,i64,i64) = sqlx::query_as("SELECT (SELECT count(*) FROM furumusic__local_upload),
(SELECT count(*) FROM furumusic__youtube_download_item),(SELECT count(*) FROM furumusic__hidden_download)")
.fetch_one(&pool).await?;
assert_eq!(counts, (107, 2, 2));
// A later receipt for a still-running hidden batch must not revive its history.
sqlx::query("INSERT INTO furumusic__local_upload(id,user_id,filename,inbox_path,status)
VALUES ('late',1,'last.flac','user_uploads/1/local-12345678-1234-1234-1234-123456789abc/last.flac','queued')")
.execute(&pool).await?;
assert_eq!(keys(&pool, 1, 0, 100, None).await?.len(), 2);
// Check the boundary between a finished torrent transfer and finished import.
sqlx::query("DELETE FROM furumusic__pending_review")
.execute(&pool)
.await?;
let inbox = tempfile::tempdir()?;
let folder = inbox.path().join("user_uploads/1/torrent-same/Album");
tokio::fs::create_dir_all(&folder).await?;
tokio::fs::write(folder.join("track.flac"), b"audio").await?;
let service = TorrentService::new(Arc::new(OnceCell::new()));
let mut entry = summaries(&pool, 1, &["torrents".into()], &["same".into()])
.await?
.remove(0);
torrent_status(&pool, 1, Some(inbox.path()), &service, &mut entry).await?;
assert_eq!(entry.status, "awaiting_ai");
tokio::fs::remove_file(folder.join("track.flac")).await?;
let mut entry = summaries(&pool, 1, &["torrents".into()], &["same".into()])
.await?
.remove(0);
torrent_status(&pool, 1, Some(inbox.path()), &service, &mut entry).await?;
assert_eq!(entry.status, "complete");
assert!(summaries(&pool, 1, &["torrents".into()], &["same".into()]).await?[0].processed);
// An unimported file dismissed in the inbox must not count as an import.
let other_file = "user_uploads/2/torrent-other/Album/removed.mp3";
sqlx::query("INSERT INTO furumusic__dismissed_review VALUES ($1, repeat('a',64), 70, false)")
.bind(other_file)
.execute(&pool)
.await?;
let torrent_sources = ["torrents".into()];
let other_id = ["other".into()];
assert_eq!(
summaries(&pool, 2, &torrent_sources, &other_id).await?[0].status,
"cancelled"
);
sqlx::query(
"INSERT INTO furumusic__pending_review(input_path,status,id) VALUES ($1,'queued',71)",
)
.bind(other_file)
.execute(&pool)
.await?;
assert_eq!(
summaries(&pool, 2, &torrent_sources, &other_id).await?[0].status,
"awaiting_ai"
);
sqlx::raw_sql(&format!("DROP SCHEMA {schema} CASCADE"))
.execute(&pool)
.await?;
Ok(())
}
+8 -26
View File
@@ -36,10 +36,11 @@ pub(super) struct ArtistDetail {
pub(super) name: String,
pub(super) image_url: Option<String>,
pub(super) total_track_count: i64,
pub(super) track_content_ids: Vec<String>,
pub(super) total_play_count: i64,
pub(super) top_tracks: Vec<TrackItem>,
pub(super) releases: Vec<ReleaseCard>,
pub(super) featured_tracks: Vec<ArtistAppearanceTrack>,
pub(super) featured_tracks: Vec<TrackItem>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
@@ -85,31 +86,6 @@ pub(super) struct PlaylistTrackItem {
pub(super) track: TrackItem,
}
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct ArtistAppearanceTrack {
pub(super) id: i64,
pub(super) title: String,
pub(super) release_id: i64,
pub(super) release_title: String,
pub(super) release_year: Option<i32>,
pub(super) duration_seconds: f64,
pub(super) artists: Vec<ArtistRef>,
pub(super) featured_artists: Vec<ArtistRef>,
pub(super) cover_url: Option<String>,
pub(super) stream_url: String,
pub(super) uploader_name: String,
pub(super) audio_format: Option<String>,
pub(super) audio_bitrate: Option<i32>,
pub(super) audio_sample_rate: Option<i32>,
pub(super) audio_bit_depth: Option<i32>,
pub(super) file_size_bytes: Option<i64>,
pub(super) lastfm_listeners: Option<i64>,
pub(super) lastfm_playcount: Option<i64>,
pub(super) lastfm_rating: Option<f64>,
pub(super) lastfm_updated_at: Option<String>,
pub(super) has_lyrics: bool,
}
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct ReleaseDetail {
pub(super) id: i64,
@@ -131,6 +107,8 @@ pub(super) struct UploaderSummary {
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct PlaylistCard {
pub(super) id: i64,
pub(super) cover_url: Option<String>,
pub(super) cover_urls: Vec<String>,
pub(super) title: String,
pub(super) track_count: i64,
pub(super) is_own: bool,
@@ -309,6 +287,8 @@ pub(super) struct PlayerDevicePollResponse {
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct PlaylistDetail {
pub(super) id: i64,
#[serde(flatten)]
pub(super) artwork: super::playlist_artwork::Artwork,
pub(super) title: String,
pub(super) description: Option<String>,
pub(super) is_own: bool,
@@ -582,6 +562,8 @@ pub(super) struct PlayHistoryPage {
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct LikeStatus {
pub(super) liked: bool,
pub(super) content_id: Option<String>,
pub(super) affected_track_ids: Vec<i64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
+65 -2
View File
@@ -1,5 +1,68 @@
use crate::player::dto::UploaderSummary;
use crate::player::rows::ReleaseUploaderRow;
use crate::player::dto::{ArtistCard, UploaderSummary};
use crate::player::rows::{ReleaseUploaderRow, SearchArtistRow};
// Match by either credit. UNION keeps appearances on the artist's own releases
// and duplicate credit roles from counting as extra tracks.
const VISIBLE_ARTIST_TRACKS: &str = r#"
SELECT credited.artist_id, t.id AS track_id, t.audio_file_id
FROM (
SELECT ta.artist_id, ta.track_id FROM furumusic__track_artist ta
WHERE ta.artist_id = ANY($1)
UNION
SELECT ra.artist_id, t.id FROM furumusic__release_artist ra
JOIN furumusic__track t ON t.release_id = ra.release_id
WHERE ra.artist_id = ANY($1)
) credited
JOIN furumusic__track t ON t.id = credited.track_id AND NOT t.is_hidden
JOIN furumusic__release r ON r.id = t.release_id AND NOT r.is_hidden"#;
pub(super) async fn artist_track_totals(
pool: &sqlx::PgPool,
artist_id: i64,
) -> Result<(i64, i64, Vec<String>), sqlx::Error> {
sqlx::query_as(&format!(
"WITH tracks AS ({VISIBLE_ARTIST_TRACKS})
SELECT COUNT(*),
(SELECT COUNT(*) FROM furumusic__play_history ph JOIN tracks ON tracks.track_id = ph.track_id),
ARRAY(SELECT DISTINCT c.content_id FROM tracks
JOIN furumusic__media_file m ON m.id = tracks.audio_file_id
JOIN furumusic__federation_content_id_cache c ON c.media_file_id = m.id AND c.sha256_hash = m.sha256_hash
ORDER BY c.content_id)
FROM tracks"
))
.bind(&[artist_id][..])
.fetch_one(pool)
.await
}
pub(super) async fn artist_cards(
pool: &sqlx::PgPool,
rows: Vec<SearchArtistRow>,
image_variant: &str,
) -> Result<Vec<ArtistCard>, sqlx::Error> {
if rows.is_empty() {
return Ok(Vec::new());
}
let ids: Vec<_> = rows.iter().map(|r| r.id).collect();
let counts: std::collections::HashMap<_, _> = sqlx::query_as::<_, (i64, i64)>(&format!(
"SELECT artist_id, COUNT(*) FROM ({VISIBLE_ARTIST_TRACKS}) tracks GROUP BY artist_id"
))
.bind(ids)
.fetch_all(pool)
.await?
.into_iter()
.collect();
Ok(rows
.into_iter()
.map(|r| ArtistCard {
id: r.id,
name: r.name,
image_url: cover_variant_url(r.image_file_id, image_variant),
release_count: r.release_count,
track_count: counts.get(&r.id).copied().unwrap_or_default(),
})
.collect())
}
pub(crate) fn cover_variant_url(file_id: Option<i64>, variant: &str) -> Option<String> {
file_id.map(|id| format!("/api/player/cover/{id}/{variant}"))
+12
View File
@@ -0,0 +1,12 @@
WITH stored AS (
SELECT track_id FROM furumusic__user_liked_track WHERE user_id = $1
), recordings AS (
SELECT a.content_id FROM stored s JOIN furumusic__track_content_alias a USING (track_id)
UNION
SELECT content_id FROM furumusic__fed_state_like
WHERE user_id = $1 AND liked AND local_track_id IS NULL
)
SELECT track_id FROM stored
UNION
SELECT a.track_id FROM recordings r JOIN furumusic__track_content_alias a USING (content_id)
WHERE NOT a.hidden
+522
View File
@@ -0,0 +1,522 @@
use chrono::NaiveDate;
use cot::{db::Database, http::StatusCode, json::Json, response::IntoResponse, session::Session};
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use super::json_error;
use crate::auth;
#[derive(Default, Deserialize)]
#[serde(rename_all = "lowercase")]
enum View {
#[default]
Overview,
History,
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Ranking {
#[default]
Artists,
Tracks,
Releases,
}
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub(super) struct Query {
view: View,
kind: Ranking,
from: Option<String>,
to: Option<String>,
tz: Option<String>,
page: Option<u32>,
}
impl Query {
fn valid_dates(&self) -> bool {
let valid = |s: &str| {
s.len() == 10 && s >= "1970-01-01" && NaiveDate::parse_from_str(s, "%Y-%m-%d").is_ok()
};
self.from.as_deref().is_none_or(|s| s == "all" || valid(s))
&& self.to.as_deref().is_none_or(valid)
}
}
pub(super) async fn handler(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: &PgPool,
query: Query,
) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
if !query.valid_dates() {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"Use dates in YYYY-MM-DD format",
));
}
let tz = query.tz.as_deref().unwrap_or("UTC");
if tz.is_empty() || tz.len() > 128 {
return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid time zone"));
}
let bounds = match bounds(pool, &query, tz).await {
Ok((start, end)) if start < end => (start, end),
Ok(_) => return Ok(json_error(StatusCode::BAD_REQUEST, "Reversed date range")),
Err(sqlx::Error::Database(e)) if e.code().as_deref() == Some("22023") => {
return Ok(json_error(StatusCode::BAD_REQUEST, "Unknown time zone"));
}
Err(e) => return Err(cot::Error::internal(e.to_string())),
};
let data = match query.view {
View::Overview => overview(pool, user.id, bounds, tz, &query.kind).await,
View::History => history(pool, user.id, bounds, query.page.unwrap_or(1).max(1)).await,
}
.map_err(|e| cot::Error::internal(e.to_string()))?;
let mut response = Json(data).into_response()?;
response
.headers_mut()
.insert("Cache-Control", "private, no-store".parse().unwrap());
Ok(response)
}
// Calendar midnights are converted independently so DST days work on the
// chart and when drilling into a single day's history.
async fn bounds(pool: &PgPool, query: &Query, tz: &str) -> Result<(i64, i64), sqlx::Error> {
sqlx::query_as(
"WITH bounds AS (SELECT COALESCE($2::text::date, (now() AT TIME ZONE $3)::date) AS last_day)
SELECT CASE WHEN $1::text = 'all' THEN 0 ELSE (EXTRACT(EPOCH FROM
(COALESCE(NULLIF($1, 'all')::date, last_day - 29)::timestamp AT TIME ZONE $3)) * 1000)::bigint END,
(EXTRACT(EPOCH FROM ((last_day + 1)::timestamp AT TIME ZONE $3)) * 1000)::bigint
FROM bounds",
)
.bind(&query.from).bind(&query.to).bind(tz).fetch_one(pool).await
}
// Every projection starts from the authenticated listener's qualified events.
// NOT MATERIALIZED lets PostgreSQL use the per-user time index for a history
// page and count its rows without reading every event's metadata.
const EVENTS: &str = "
WITH events AS NOT MATERIALIZED (
SELECT * FROM furumusic__listen_event
WHERE user_id = $1 AND qualified AND started_at_ms >= $2 AND started_at_ms < $3
)";
const RECORDINGS: &str = "
, recordings AS (
SELECT DISTINCT ON (content_id) content_id, metadata_json, local_track_id,
COUNT(*) OVER (PARTITION BY content_id) AS plays
FROM events ORDER BY content_id, started_at_ms DESC, listen_id DESC
)";
// Materialized tracks keep the same content ID. Resolve against today's audio
// hash, including tracks that arrived after the listen was synced.
const LOCAL_TRACKS: &str = "
, local AS (
SELECT DISTINCT ON (w.content_id) w.content_id, t.id AS track_id, t.title,
r.id AS release_id, r.title AS release_title, r.cover_file_id AS album_art,
COALESCE(t.cover_file_id, r.cover_file_id) AS track_art
FROM wanted w JOIN furumusic__federation_content_id_cache c USING (content_id)
JOIN furumusic__media_file m ON m.id = c.media_file_id AND m.sha256_hash = c.sha256_hash
JOIN furumusic__track t ON t.audio_file_id = m.id AND NOT t.is_hidden
JOIN furumusic__release r ON r.id = t.release_id AND NOT r.is_hidden
ORDER BY w.content_id, (t.id = w.local_track_id) DESC NULLS LAST, t.id
)";
const SUMMARY: &str = "
, daily AS (
SELECT (to_timestamp(started_at_ms / 1000.0) AT TIME ZONE $4)::date AS day,
COUNT(*) AS plays, SUM(listened_ms)::bigint / 1000 AS listened_seconds
FROM events GROUP BY day
)
SELECT jsonb_build_object('plays', COUNT(*), 'tracks', COUNT(DISTINCT content_id),
'listened_seconds', COALESCE(SUM(listened_ms), 0)::bigint / 1000,
'daily', COALESCE((SELECT jsonb_agg(to_jsonb(daily) ORDER BY day) FROM daily), '[]'))
FROM events";
// Fold credits with the same Unicode rules on every database, including C-locale
// installations. Return the key to the column's collation for the name_sort index.
const TOP_ARTISTS: &str = r#"
, top AS (
SELECT key, MIN(name) AS title, COUNT(*) AS plays
FROM events CROSS JOIN LATERAL (
SELECT DISTINCT ON (key)
lower(normalize(trim(n), NFKC) COLLATE furumusic_unicode) COLLATE "default" AS key,
trim(n) AS name
FROM jsonb_array_elements_text(COALESCE(metadata_json->'artist_names', '[]') ||
COALESCE(metadata_json->'featured_artist_names', '[]')) n
WHERE trim(n) <> '' ORDER BY key, name
) credit
GROUP BY key ORDER BY plays DESC, key LIMIT 5
), visible AS NOT MATERIALIZED (
SELECT id, name_sort, image_file_id,
lower(normalize(trim(name), NFKC) COLLATE furumusic_unicode) COLLATE "default" AS display_key
FROM furumusic__artist WHERE NOT is_hidden
)
SELECT COALESCE(jsonb_agg(to_jsonb(item) ORDER BY plays DESC, title), '[]') FROM (
SELECT COALESCE(a.name, top.title) AS title, top.plays, a.id AS artist_id,
CASE WHEN a.image_file_id IS NOT NULL THEN '/api/player/cover/' || a.image_file_id || '/small' END AS cover_url
FROM top LEFT JOIN furumusic__artist a ON a.id = COALESCE(
(SELECT id FROM visible WHERE name_sort = top.key AND display_key = top.key
AND image_file_id IS NOT NULL ORDER BY id LIMIT 1),
-- Older imports can have a different sort key. Prefer the actual
-- display name and choose the visible copy with a photo on ties.
(SELECT id FROM visible WHERE display_key = top.key OR name_sort = top.key
ORDER BY (display_key = top.key) DESC, (image_file_id IS NOT NULL) DESC, id LIMIT 1)
)
) item"#;
const TRACK_ROWS: &str = "
SELECT COALESCE(jsonb_agg(to_jsonb(item) ORDER BY plays DESC, content_id), '[]') FROM (
SELECT w.content_id, w.plays, l.track_id, l.release_id,
COALESCE(l.title, w.metadata_json->>'title', '') AS title,
COALESCE(w.metadata_json->'artist_names', '[]') AS artist_names,
array_to_string(ARRAY(SELECT jsonb_array_elements_text(w.metadata_json->'artist_names')), ', ') AS detail,
CASE WHEN l.track_art IS NOT NULL THEN '/api/player/cover/' || l.track_art || '/small' END AS cover_url
FROM wanted w LEFT JOIN local l USING (content_id)
) item";
const RELEASE_ROWS: &str = "
, editions AS (
SELECT w.plays, l.release_id, l.album_art,
COALESCE(l.release_title, w.metadata_json->>'release_title') AS title,
COALESCE(w.metadata_json->'artist_names', '[]') AS artists,
w.metadata_json->>'year' AS year
FROM wanted w LEFT JOIN local l USING (content_id)
), grouped AS (
SELECT release_id, MIN(title) AS title, MIN(album_art) AS art,
(array_agg(artists ORDER BY artists))[1] AS snapshot_artists,
SUM(plays)::bigint AS plays
FROM editions WHERE NULLIF(trim(title), '') IS NOT NULL
GROUP BY release_id, CASE WHEN release_id IS NULL THEN jsonb_build_array(
lower(title), ARRAY(SELECT DISTINCT lower(trim(name)) FROM jsonb_array_elements_text(artists) name
ORDER BY lower(trim(name))), year) END
ORDER BY plays DESC, title, release_id NULLS LAST, snapshot_artists LIMIT 5
), ranked AS (
SELECT g.*, COALESCE((
SELECT jsonb_agg(a.name ORDER BY ra.position, a.id)
FROM furumusic__release_artist ra JOIN furumusic__artist a ON a.id = ra.artist_id
WHERE ra.release_id = g.release_id AND NOT a.is_hidden
), snapshot_artists) AS artist_names FROM grouped g
)
SELECT COALESCE(jsonb_agg(to_jsonb(item) ORDER BY plays DESC, title, release_id NULLS LAST, artist_names), '[]') FROM (
SELECT release_id, title, artist_names, plays,
array_to_string(ARRAY(SELECT jsonb_array_elements_text(artist_names)), ', ') AS detail,
CASE WHEN art IS NOT NULL THEN '/api/player/cover/' || art || '/small' END AS cover_url
FROM ranked
) item";
async fn overview(
pool: &PgPool,
user: i64,
(start, end): (i64, i64),
tz: &str,
kind: &Ranking,
) -> Result<Value, sqlx::Error> {
let summary_sql = format!("{EVENTS}{SUMMARY}");
let ranking_sql = match kind {
Ranking::Artists => format!("{EVENTS}{TOP_ARTISTS}"),
Ranking::Tracks => format!(
"{EVENTS}{RECORDINGS}, wanted AS (SELECT * FROM recordings ORDER BY plays DESC, content_id LIMIT 5){LOCAL_TRACKS}{TRACK_ROWS}"
),
Ranking::Releases => format!(
"{EVENTS}{RECORDINGS}, wanted AS (SELECT * FROM recordings){LOCAL_TRACKS}{RELEASE_ROWS}"
),
};
let (mut summary, ranking): (Value, Value) = tokio::try_join!(
sqlx::query_scalar(&summary_sql)
.bind(user)
.bind(start)
.bind(end)
.bind(tz)
.fetch_one(pool),
sqlx::query_scalar(&ranking_sql)
.bind(user)
.bind(start)
.bind(end)
.fetch_one(pool),
)?;
summary["ranking"] = ranking;
Ok(summary)
}
async fn history(
pool: &PgPool,
user: i64,
(start, end): (i64, i64),
page: u32,
) -> Result<Value, sqlx::Error> {
const LIMIT: i64 = 25;
let sql = format!("{EVENTS}, wanted AS (
SELECT * FROM events ORDER BY started_at_ms DESC, listen_id DESC LIMIT $4 OFFSET $5
){LOCAL_TRACKS}, items AS (
SELECT w.listen_id AS id, w.content_id, w.started_at_ms, w.listened_ms, l.track_id, l.release_id,
COALESCE(l.title, w.metadata_json->>'title', '') AS title,
COALESCE(l.release_title, w.metadata_json->>'release_title', '') AS release_title,
COALESCE(w.metadata_json->'artist_names', '[]') ||
COALESCE(w.metadata_json->'featured_artist_names', '[]') AS artist_names,
CASE WHEN l.track_art IS NOT NULL THEN '/api/player/cover/' || l.track_art || '/small' END AS cover_url,
COALESCE(NULLIF(d.name, ''), w.origin_device_id) AS device_name,
trim(both '\"' from w.ended_reason) = 'finished' AS completed
FROM wanted w LEFT JOIN local l USING (content_id)
LEFT JOIN furumusic__fed_device d ON d.user_id = w.user_id AND d.device_id = w.origin_device_id
) SELECT jsonb_build_object('total', (SELECT COUNT(*) FROM events), 'items',
COALESCE((SELECT jsonb_agg(to_jsonb(items) ORDER BY started_at_ms DESC, id DESC) FROM items), '[]'))");
let mut data: Value = sqlx::query_scalar(&sql)
.bind(user)
.bind(start)
.bind(end)
.bind(LIMIT)
.bind((i64::from(page) - 1) * LIMIT)
.fetch_one(pool)
.await?;
data["page"] = json!(page);
data["limit"] = json!(LIMIT);
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn personal_query_accepts_calendar_dates_but_no_user_selector() {
assert!(serde_json::from_value::<Query>(json!({"user_id": 3})).is_err());
for (date, valid) in [("all", true), ("2024-02-29", true), ("2026-02-29", false)] {
let query = Query {
from: Some(date.into()),
..Default::default()
};
assert_eq!(query.valid_dates(), valid);
}
}
async fn catalog_fixture() -> anyhow::Result<PgPool> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?)
.await?;
// Collation names do not resolve through pg_temp. Use an isolated schema
// with the deployment's ICU collation, rolled back with the fixture.
let schema = format!("listening_{}", uuid::Uuid::new_v4().simple());
sqlx::raw_sql(&format!(
"BEGIN; CREATE SCHEMA {schema}; SET LOCAL search_path TO {schema}, public;
CREATE COLLATION furumusic_unicode (provider=icu, locale='und', deterministic=true);"
))
.execute(&pool)
.await?;
sqlx::raw_sql(include_str!("../../tests/statistics_fixture.sql"))
.execute(&pool)
.await?;
sqlx::raw_sql("
ALTER TABLE furumusic__track ADD title text, ADD release_id bigint, ADD audio_file_id bigint, ADD is_hidden bool DEFAULT false, ADD cover_file_id bigint;
ALTER TABLE furumusic__release ADD title text, ADD is_hidden bool DEFAULT false, ADD cover_file_id bigint;
ALTER TABLE furumusic__media_file ADD id bigint, ADD sha256_hash text;
ALTER TABLE furumusic__artist ADD name text, ADD name_sort text, ADD image_file_id bigint, ADD is_hidden bool DEFAULT false;
CREATE TEMP TABLE furumusic__federation_content_id_cache(media_file_id bigint, sha256_hash text, content_id text);
CREATE TEMP TABLE furumusic__release_artist(release_id bigint, artist_id bigint, position int);
INSERT INTO furumusic__release (id,title,cover_file_id) VALUES (14,'Shared release',91);
INSERT INTO furumusic__artist (id,name,name_sort,image_file_id) VALUES (15,'Artist A','artist a',92);
INSERT INTO furumusic__release_artist VALUES (14,15,0);
INSERT INTO furumusic__track (id,title,release_id,audio_file_id) VALUES (50,'Local title',14,51),(60,'Imported track',14,61);
INSERT INTO furumusic__media_file (id,sha256_hash) VALUES (51,'sha'),(61,'new-sha');
INSERT INTO furumusic__federation_content_id_cache VALUES (51,'sha','content-one'),(61,'old-sha','content-two');
").execute(&pool).await?;
Ok(pool)
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
async fn personal_artist_ranking_resolves_unicode_portraits() -> anyhow::Result<()> {
let pool = catalog_fixture().await?;
sqlx::raw_sql(r#"
INSERT INTO furumusic__artist (id,name,name_sort,image_file_id,is_hidden) VALUES
(20,'Ногу Свело!','ногу свело!',101,true),
(21,'Ногу Свело!','ногу свело!',NULL,false),
(22,'Ногу Свело!','ногу свело',102,false),
(23,'Олег Лёгкий','олег лёгкий',103,false),
(24,'Саша Скул','саша скул',104,false),
(25,'Hidden','hidden',105,true);
INSERT INTO furumusic__listen_event (user_id,listen_id,started_at_ms,qualified,metadata_json) VALUES
(4,'one',1,true,'{"artist_names":["НОГУ СВЕЛО!","Олег Лёгкий","Саша Скул","Hidden"],"featured_artist_names":[" Ногу Свело! "]}'),
(4,'two',2,true,'{"artist_names":["ногу свело!","Олег Ле\u0308гкии\u0306"],"featured_artist_names":["ОЛЕГ ЛЁГКИЙ"]}');
"#).execute(&pool).await?;
let data = overview(&pool, 4, (0, 3), "UTC", &Ranking::Artists).await?;
let artists = data["ranking"].as_array().unwrap();
assert_eq!(artists.len(), 4);
for (title, id, image, plays) in [
("Ногу Свело!", 22, 102, 2),
("Олег Лёгкий", 23, 103, 2),
("Саша Скул", 24, 104, 1),
] {
let artist = artists.iter().find(|item| item["title"] == title).unwrap();
assert_eq!(artist["artist_id"], id);
assert_eq!(
artist["cover_url"],
format!("/api/player/cover/{image}/small")
);
assert_eq!(artist["plays"], plays);
}
let hidden = artists
.iter()
.find(|item| item["title"] == "Hidden")
.unwrap();
assert!(hidden["artist_id"].is_null() && hidden["cover_url"].is_null());
sqlx::query("ROLLBACK").execute(&pool).await?;
Ok(())
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
async fn legacy_web_repair_corrects_only_overlong_fallback_listens() -> anyhow::Result<()> {
let pool = catalog_fixture().await?;
sqlx::raw_sql(
"INSERT INTO furumusic__listen_event
(user_id, listen_id, content_id, started_at_ms, qualified, listened_ms, track_duration_ms)
SELECT 3, id, 'content-one', 1000, true, listened, duration FROM (VALUES
('legacy-web:3:42:1', 40461000, 267000),
('legacy-web:3:43:1', 20000, 267000),
('legacy-web:3:44:1', 267000, 267000),
('legacy-web:3:45:1', 800000, NULL),
('legacy-web:3:46:1', 800000, 0),
('legacy-web:12', 800000, 267000),
('legacy-web:2:42:1', 800000, 267000),
('legacy-web:3:track:1', 800000, 267000),
('e28cbb99-d9cc-40c5-ad1c-490be56688b6', 800000, 267000)
) v(id, listened, duration)",
)
.execute(&pool)
.await?;
let repair = include_str!("repair_legacy_web_listen_durations.sql");
assert_eq!(sqlx::query(repair).execute(&pool).await?.rows_affected(), 2);
assert_eq!(sqlx::query(repair).execute(&pool).await?.rows_affected(), 0);
let day = (0, 86400000);
let log = history(&pool, 3, day, 1).await?;
assert_eq!(log["total"], 9);
let legacy = log["items"]
.as_array()
.unwrap()
.iter()
.find(|item| item["id"] == "legacy-web:3:42:1")
.unwrap();
assert_eq!(legacy["started_at_ms"], 1000);
assert_eq!(legacy["listened_ms"], 267000);
let summary = overview(&pool, 3, day, "UTC", &Ranking::Tracks).await?;
assert_eq!(
summary["daily"],
json!([{
"day": "1970-01-01", "plays": 9, "listened_seconds": 3 * 267 + 20 + 5 * 800,
}])
);
sqlx::query("ROLLBACK").execute(&pool).await?;
Ok(())
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
async fn busy_calendar_day_history_matches_the_overview() -> anyhow::Result<()> {
let pool = catalog_fixture().await?;
let filter = Query {
from: Some("2026-11-21".into()),
to: Some("2026-11-21".into()),
..Default::default()
};
let tz = "Asia/Nicosia";
let (start, end) = bounds(&pool, &filter, tz).await?;
sqlx::query(
"INSERT INTO furumusic__listen_event
(user_id, listen_id, content_id, started_at_ms, listened_ms, qualified)
SELECT 3, n::text, 'content-one',
CASE n WHEN 0 THEN $1::bigint - 1 WHEN 114 THEN $2::bigint
ELSE $1::bigint + (n-1) * 360000 END, 360000, true
FROM generate_series(0, 114) n",
)
.bind(start)
.bind(end)
.execute(&pool)
.await?;
let summary = overview(&pool, 3, (start, end), tz, &Ranking::Tracks).await?;
assert_eq!(
summary["daily"],
json!([{
"day": "2026-11-21", "plays": 113, "listened_seconds": 113 * 360,
}])
);
let mut ids = Vec::new();
for (page, count) in [(1, 25), (2, 25), (3, 25), (4, 25), (5, 13)] {
let data = history(&pool, 3, (start, end), page).await?;
assert_eq!(data["total"], summary["plays"]);
let items = data["items"].as_array().unwrap();
assert_eq!(items.len(), count);
ids.extend(
items
.iter()
.map(|item| item["id"].as_str().unwrap().to_owned()),
);
}
assert_eq!(
ids,
(1..=113).rev().map(|n| n.to_string()).collect::<Vec<_>>()
);
sqlx::query("ROLLBACK").execute(&pool).await?;
Ok(())
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
async fn personal_listening_filters_events_and_resolves_playable_editions() -> anyhow::Result<()>
{
let pool = catalog_fixture().await?;
let all = (0, i64::MAX);
let data = overview(&pool, 1, all, "UTC", &Ranking::Artists).await?;
assert_eq!(data["plays"], 31);
assert_eq!(data["tracks"], 2);
assert_eq!(data["listened_seconds"], 5520);
assert_eq!(data["ranking"][0]["plays"], 30);
assert_eq!(data["ranking"][0]["artist_id"], 15);
assert_eq!(data["ranking"][1]["title"], "Guest");
let bob = overview(&pool, 2, all, "UTC", &Ranking::Tracks).await?;
assert_eq!(bob["plays"], 1);
assert_eq!(bob["listened_seconds"], 90);
assert_eq!(bob["ranking"][0]["title"], "Local title");
assert_eq!(bob["ranking"][0]["track_id"], 50);
assert_eq!(bob["ranking"][0]["cover_url"], "/api/player/cover/91/small");
let before = history(&pool, 1, all, 1).await?;
assert_eq!(before["total"], 31);
assert_eq!(before["items"].as_array().unwrap().len(), 25);
assert!(before["items"][0]["track_id"].is_null());
assert_eq!(before["items"][0]["title"], "Remote song");
assert_eq!(before["items"][0]["device_name"], "Alice phone");
assert_eq!(before["items"][0]["completed"], false);
let page_two = history(&pool, 1, all, 2).await?;
assert_eq!(page_two["items"].as_array().unwrap().len(), 6);
sqlx::query("UPDATE furumusic__federation_content_id_cache SET sha256_hash = 'new-sha' WHERE content_id = 'content-two'")
.execute(&pool).await?;
let albums = overview(&pool, 1, all, "UTC", &Ranking::Releases).await?;
assert_eq!(albums["ranking"].as_array().unwrap().len(), 1);
assert_eq!(albums["ranking"][0]["plays"], 31);
assert_eq!(albums["ranking"][0]["release_id"], 14);
assert_eq!(albums["ranking"][0]["artist_names"], json!(["Artist A"]));
let dst = Query {
from: Some("2026-11-01".into()),
to: Some("2026-11-01".into()),
..Default::default()
};
let range = bounds(&pool, &dst, "America/New_York").await?;
assert_eq!(range.1 - range.0, 25 * 3_600_000);
assert_eq!(history(&pool, 1, range, 1).await?["total"], 0);
let local_days = overview(&pool, 1, all, "America/New_York", &Ranking::Artists).await?;
assert_eq!(local_days["daily"][0]["day"], "2026-10-31");
let empty = overview(&pool, 3, all, "UTC", &Ranking::Releases).await?;
assert_eq!(empty["plays"], 0);
assert_eq!(empty["ranking"], json!([]));
sqlx::query("ROLLBACK").execute(&pool).await?;
Ok(())
}
}
+405 -454
View File
File diff suppressed because it is too large. Load diff
+740
View File
@@ -0,0 +1,740 @@
/* Shared by the player and its service worker. A track becomes visible only after
* the complete OPFS file is closed and its IndexedDB transaction commits. */
(() => {
'use strict';
const BASE = '/api/player/';
const DEFAULT_LIMIT = 3_000_000_000;
const MAX_LIMIT = 512_000_000_000;
const stores = ['tracks', 'files', 'assets', 'meta', 'plays', 'lyrics', 'pending'];
const requests = request => new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const validId = value => Number.isSafeInteger(value) && value > 0;
const positiveId = value => validId(Number(value)) ? Number(value) : null;
// Server IDs are sequential. Keep browser-only IDs in the upper half of the safe integer range.
const syntheticBase = 2 ** 52;
const normalized = value => String(value || '').normalize('NFKC').trim().toLowerCase();
const contentToken = id => typeof id === 'string' && /^b3:[a-f\d]{64}$/.test(id) ? id.slice(3) : null;
const remoteMedia = id => BASE + 'federation/cache/' + contentToken(id);
function trackId(value) {
const id = value?.id ?? value;
const token = typeof id === 'string' && id.startsWith('fed:') && contentToken(id.slice(4));
return token ? syntheticBase + parseInt(token.slice(0,13),16) : positiveId(id);
}
async function metadataId(type, key) {
const hash = new DataView(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([type,key]))));
return syntheticBase + (hash.getUint32(0) & 0xfffff) * 2 ** 32 + hash.getUint32(4);
}
function preparedRemote(t) {
return !!contentToken(t?.content_id) && t.id === 'fed:' + t.content_id &&
t.federated_cache === true && t.stream_url === remoteMedia(t.content_id);
}
async function remoteDescriptor(t) {
const metadata = t._federationTrack?.metadata || {};
const credit = async a => {
const name = (typeof a === 'string' ? a : a?.name) || 'Unknown artist';
const key = normalized(a?.key?.normalized_name || name);
const id = positiveId(a?.local_id ?? a?.id) || await metadataId('artist',key);
return {id,name};
};
const primary = t.artists?.length ? t.artists : ['Unknown artist'];
const artists = await Promise.all(primary.map(credit));
const featured = await Promise.all((t.featured_artists || []).map(credit));
const key = metadata.release?.key || t.release_key || {};
const releaseTitle = t.release_title || metadata.release?.title || t.title;
const year = t.release_year ?? key.year ?? null;
const names = key.primary_artists?.length ? key.primary_artists : artists.map(a => a.name);
const releaseArtists = await Promise.all(names.map(name => artists.find(a => normalized(a.name) === normalized(name)) || credit(name)));
const releaseId = positiveId(t.release_id || metadata.release?.local_id) || await metadataId('release',[
normalized(key.normalized_title || releaseTitle), names.map(normalized).sort(), year, key.release_type || '',
]);
const id = trackId(t);
return {id, content_id:t.content_id, title:t.title, artists, featured_artists:featured,
release_id:releaseId, release_title:releaseTitle, release_year:year, track_number:t.track_number ?? null,
disc_number:t.disc_number ?? null, duration_seconds:t.duration_seconds || 0, cover_url:coverKey(t.cover_url),
audio_format:t.audio_format ?? metadata.audio_format, audio_bitrate:t.audio_bitrate ?? metadata.audio_bitrate,
audio_sample_rate:t.audio_sample_rate ?? metadata.audio_sample_rate, audio_bit_depth:t.audio_bit_depth ?? metadata.audio_bit_depth,
uploader_name:'Federation', offline_remote:true, has_lyrics:false, stream_url:BASE + 'stream/' + id,
offline_release:{artists:releaseArtists,release_type:key.release_type || ''}};
}
const quotaError = () => new DOMException('Offline cache limit reached', 'QuotaExceededError');
const trackMissing = () => new DOMException('Recording is no longer available', 'NotFoundError');
const json = (data, status = 200) => Response.json(data, {status});
const missing = () => json({error:'Unavailable offline'}, 404);
function coverKey(url) {
if (typeof url !== 'string') return null;
if (url.startsWith(location.origin + '/')) url = url.slice(location.origin.length);
// Serve the saved thumbnail for all resolutions of the same artwork.
const match = url.match(/^\/api\/player\/cover\/(\d+)(?:\/(?:small|medium|large))?$/);
if (match) return BASE + 'cover/' + match[1] + '/medium';
if (/^\/api\/player\/playlists\/\d+\/cover\?v=[a-f\d]+$/i.test(url)) return url;
return /^\/api\/player\/federation\/(?:tracks\/artwork|catalog\/artwork(?:\/discover)?)\?[^#]+$/.test(url) ? url : null;
}
function savedTrack(row) {
return row.track.cover_url || !row.release?.cover_url ? row.track : {...row.track, cover_url:row.release.cover_url};
}
function releaseInfo(release, track) {
return {
id: track.release_id, title: release?.title || track.release_title,
year: release?.year ?? track.release_year, release_type: release?.release_type || '',
artists: (release?.artists || track.artists || []).map(({id,name}) => ({id,name})),
cover_url: release?.cover_url || track.cover_url,
uploaders: (release?.uploaders || []).map(({name,track_count}) => ({name,track_count})),
track_count: release?.tracks?.length ?? release?.track_count,
};
}
function validTrack(track) {
return track && validId(track.id) && validId(track.release_id) && !!track.title &&
Array.isArray(track.artists) && track.stream_url === BASE + 'stream/' + track.id;
}
function contentKey(track) {
return /^b3:[\da-f]{64}$/.test(track.content_id) ? track.content_id : 'track:' + track.id;
}
const audioTypes = new Map(Object.entries({
mp3:'audio/mpeg', flac:'audio/flac', wav:'audio/wav', ogg:'audio/ogg', oga:'audio/ogg',
opus:'audio/ogg', mp4:'audio/mp4', m4a:'audio/mp4', alac:'audio/mp4', aac:'audio/aac', webm:'audio/webm',
}));
function binary(file, request) {
const headers = new Headers({'Content-Type':file.type || 'application/octet-stream', 'Accept-Ranges':'bytes'});
const range = request.headers.get('Range');
let start = 0, end = file.size - 1;
if (range) {
const parts = /^bytes=(\d*)-(\d*)$/i.exec(range);
if (parts && (parts[1] || parts[2])) {
if (parts[1]) {
start = Number(parts[1]);
if (parts[2]) end = Math.min(end, Number(parts[2]));
} else {
start = Math.max(0, file.size - Number(parts[2]));
}
} else {
start = file.size;
}
if (!Number.isSafeInteger(start) || start > end || start >= file.size) {
headers.set('Content-Range', 'bytes */' + file.size);
return new Response(null, {status:416, headers});
}
headers.set('Content-Range', 'bytes ' + start + '-' + end + '/' + file.size);
}
headers.set('Content-Length', String(end - start + 1));
const body = request.method === 'HEAD' ? null : range ? file.slice(start, end + 1) : file;
return new Response(body, {status:range ? 206 : 200, headers});
}
function summarizePlaylist(pl) {
const {id, title, kind, is_own, is_saved, is_public, owner_name, description, cover_url, cover_urls} = pl;
return {id, title, kind, is_own, is_saved, is_public, owner_name, description, cover_url, cover_urls};
}
class OfflineCatalog {
static trackId(value) { return trackId(value); }
static artworkKey(url) { return coverKey(url); }
static canSave(track) {
return !!track && !track.podcast && !track.federation_pending && (positiveId(track.id) !== null || preparedRemote(track));
}
constructor(account) {
if (!/^\d+$/.test(String(account)) || !positiveId(account)) throw new TypeError('Missing offline account');
this.name = 'furumusic-offline-v1-' + Number(account);
this.account = Number(account);
this._database = null;
this._reconciled = false;
}
async db() {
if (!this._database) {
const opening = indexedDB.open(this.name, 1);
opening.onupgradeneeded = () => {
const db = opening.result;
db.createObjectStore('tracks', {keyPath:'id'}).createIndex('file', 'file');
for (const name of ['files','assets','meta','plays','lyrics']) db.createObjectStore(name);
db.createObjectStore('pending', {keyPath:'id'}).createIndex('queued','queued');
};
this._database = requests(opening).then(db => {
db.onversionchange = () => { db.close(); this._database = null; };
return db;
}).catch(error => { this._database = null; throw error; });
}
return this._database;
}
async read(store, key) {
const tx = (await this.db()).transaction(store);
return requests(tx.objectStore(store).get(key));
}
async all(store) {
const tx = (await this.db()).transaction(store);
return requests(tx.objectStore(store).getAll());
}
async write(names, work) {
const tx = (await this.db()).transaction(names, 'readwrite');
const finished = new Promise((resolve,reject) => {
tx.oncomplete = resolve;
tx.onabort = () => reject(tx.error || new DOMException('Database transaction aborted','AbortError'));
});
try {
work(name => tx.objectStore(name));
} catch (error) {
tx.abort();
await finished.catch(() => {});
throw error;
}
await finished;
}
async directory() {
return (await navigator.storage.getDirectory()).getDirectoryHandle(this.name, {create:true});
}
async stats() {
const tx = (await this.db()).transaction(['tracks','meta']);
const [tracks, bytes] = await Promise.all([requests(tx.objectStore('tracks').count()), requests(tx.objectStore('meta').get('bytes'))]);
return {tracks, bytes:bytes || 0};
}
async list() {
const tx = (await this.db()).transaction(['tracks','plays','files']);
const files = tx.objectStore('files');
const [rows, plays, fileKeys, fileInfo] = await Promise.all([
requests(tx.objectStore('tracks').getAll()), requests(tx.objectStore('plays').getAll()),
requests(files.getAllKeys()), requests(files.getAll()),
]);
const mime = new Map(fileKeys.map((key,i) => [key, fileInfo[i].mime]));
const counts = new Map(plays.map(p => [p.id, p]));
return rows.map(r => ({...savedTrack(r), bytes:r.bytes, audio_mime:mime.get(r.file), downloaded_at:r.downloaded_at,
last_played_at:counts.get(r.id)?.last_played_at || null, play_count:counts.get(r.id)?.play_count || 0}));
}
async has(value) {
const id = trackId(value);
return id !== null && Boolean(await this.read('tracks',id));
}
async openAudio(track) {
const id = trackId(track);
const row = id && await this.read('tracks', id);
const source = track?.id ?? track;
const requested = track?.content_id ?? (typeof source === 'string' && source.startsWith('fed:') ? source.slice(4) : null);
const content = contentToken(requested) ? requested : null;
const key = content || row?.file;
let entry = key && await this.read('files', key);
// Older recordings without a content hash are stored under their local track ID.
if (!entry && content && row?.file === 'track:' + id) entry = await this.read('files', row.file);
if (!entry) return null;
try {
const handle = await (await this.directory()).getFileHandle(entry.name);
const file = await handle.getFile();
const format = track?.audio_format || row?.track?.audio_format;
const type = entry.mime && entry.mime !== 'application/octet-stream'
? entry.mime : file.type || audioTypes.get(normalized(format));
// OPFS filenames have no extension. Retype the disk-backed bytes without reading them into memory.
return type && type !== file.type ? file.slice(0, file.size, type) : file;
} catch (error) {
if (error.name === 'NotFoundError') return null;
throw error;
}
}
async enqueue(track) {
if (!OfflineCatalog.canSave(track)) return;
const id = trackId(track);
const entry = preparedRemote(track) ? await remoteDescriptor(track) : {id, content_id:track.content_id || null};
await this.write(['pending','tracks'], get => {
const tracks = get('tracks'), queue = get('pending');
const existing = tracks.get(id);
existing.onsuccess = () => {
if (existing.result && (!track.content_id || existing.result.track.content_id === track.content_id)) return;
const item = queue.get(id);
item.onsuccess = () => queue.put({...entry, queued:item.result?.queued ?? Date.now()});
};
});
}
async pending() {
const tx = (await this.db()).transaction('pending');
return requests(tx.objectStore('pending').index('queued').getAll());
}
async dequeue(value) {
const id = trackId(value);
if (id) await this.write(['pending'], get => get('pending').delete(id));
}
async touch(track) {
const id = trackId(track);
if (!id) return;
await this.write(['plays'], get => {
const store = get('plays'), req = store.get(id);
req.onsuccess = () => store.put({id, last_played_at:Date.now(), play_count:(req.result?.play_count || 0)+1}, id);
});
}
async observe(raw, value) {
const url = new URL(raw, location.origin);
if (url.origin !== location.origin || value == null) return;
const route = url.pathname.slice(BASE.length);
let key = route, data;
if (!url.pathname.startsWith(BASE)) return;
if (route === 'me' && Number(value.id) === this.account) data = value;
else if (['likes','follows','pins','state'].includes(route)) data = value;
else if (route === 'tracks/content/like' && Array.isArray(value)) data = value;
else if (route === 'playlists' && Array.isArray(value)) data = value.map(summarizePlaylist);
else if (/^playlists\/-?\d+$/.test(route) && Array.isArray(value.tracks)) {
data = {...summarizePlaylist(value), members:value.tracks.map(t => ({id:t.id, content_id:t.content_id,
playlist_track_id:t.playlist_track_id, sort_key:t.sort_key}))};
} else if (route === 'artists' && Array.isArray(value.items)) {
// Only the compact image references are needed to hydrate a track saved later.
const mine = url.searchParams.get('mine') === 'true';
return this.write(['meta'], get => {
for (const a of value.items) {
if (a.image_url) get('meta').put(a.image_url, 'artist-image/' + a.id);
if (mine) get('meta').put(true, 'mine/' + a.id);
}
});
} else if (/^artists\/\d+$/.test(route) && value.image_url) {
key = 'artist-image/' + value.id;
data = value.image_url;
} else return;
// In the window, snapshots may come from Alpine reactive proxies.
const plain = JSON.parse(JSON.stringify(data));
await this.write(['meta'], get => get('meta').put(plain, key));
}
async save(track, options = {}) {
if (!OfflineCatalog.canSave(track)) throw new TypeError('This track is not available to save');
const id = trackId(track);
if (preparedRemote(track)) track = await remoteDescriptor(track);
return navigator.locks.request(this.name, {signal:options.signal}, () => this._save(id, track, options));
}
async _save(id, input, options) {
const {signal} = options;
const fetcher = options.fetch || fetch;
const limit = Math.min(MAX_LIMIT, options.limitBytes ?? DEFAULT_LIMIT);
if (!Number.isFinite(limit) || limit <= 0) throw quotaError();
const get = (path, init) => fetcher(path, {...init, signal, cache:'no-store', credentials:'same-origin', redirect:'error'});
const dir = await this.directory();
if (!this._reconciled) {
await this.prune(dir);
this._reconciled = true;
}
if (options.playlist?.tracks) await this.observe(BASE+'playlists/'+options.playlist.id,options.playlist);
const previous = await this.read('tracks', id);
if (previous && (!input.content_id || previous.track.content_id === input.content_id)) return this.dequeue(id);
if (input.offline_remote && (id !== trackId('fed:'+input.content_id) || previous)) throw new Error('Conflicting offline recording ID');
let track = input;
if (!validTrack(track) || !Object.hasOwn(track,'content_id') || typeof track.has_lyrics !== 'boolean') {
const res = await get(BASE + 'tracks-by-ids', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ids:[id]})});
if ([404,410].includes(res.status)) throw trackMissing();
if (!res.ok) throw new Error('Cannot load track metadata ('+res.status+')');
track = (await res.json()).find(t => t.id === id);
if (!track) throw trackMissing();
}
if (!validTrack(track)) throw new Error('Incomplete offline track metadata');
// Strip transient player state, federated URLs and Alpine proxies.
track = JSON.parse(JSON.stringify(track));
const remote = track.offline_remote, remoteRelease = track.offline_release;
delete track.offline_release;
delete track.queued;
const fileKey = contentKey(track);
let file = await this.read('files', fileKey);
const used = (await this.stats()).bytes;
let remaining = limit - used;
let newName;
let addedBytes = 0;
try {
if (!file) {
if (remaining <= 0 || track.file_size_bytes > remaining) throw quotaError();
const res = await get(remote ? remoteMedia(track.content_id) : track.stream_url);
if ([404,410].includes(res.status)) throw trackMissing();
// Media elements often receive 206; only a complete fresh download is suitable here.
const mime = (res.headers.get('Content-Type') || '').split(';')[0].trim();
if (res.status !== 200 || !res.body || res.headers.has('Content-Range') || /text\/|json|xml/i.test(mime)) {
throw new Error('Cannot download a complete audio file ('+res.status+')');
}
const headerLength = res.headers.get('Content-Length');
const expected = Number(headerLength) || Number(track.file_size_bytes) || null;
if (expected > remaining) throw quotaError();
newName = 'audio-' + crypto.randomUUID();
const target = await dir.getFileHandle(newName, {create:true});
const writer = await target.createWritable();
const reader = res.body.getReader();
let bytes = 0;
try {
for (;;) {
signal?.throwIfAborted();
const {value, done} = await reader.read();
if (done) break;
bytes += value.byteLength;
if (bytes > remaining) throw quotaError();
await writer.write(value);
}
if (!bytes || (expected && expected !== bytes)) throw new Error('Incomplete audio file');
await writer.close();
} catch (error) {
await Promise.allSettled([reader.cancel(),writer.abort()]);
throw error;
} finally { reader.releaseLock(); }
file = {name:newName, bytes, mime};
addedBytes += bytes;
remaining -= bytes;
}
const optional = async path => {
try {
const res = await get(path);
return res.ok ? await res.json() : null;
} catch (error) { signal?.throwIfAborted(); return null; }
};
const release = releaseInfo(options.release?.id === track.release_id ? options.release :
await this.read('meta','release/'+track.release_id) || (track.release_id < syntheticBase ? await optional(BASE+'releases/'+track.release_id) : null) || remoteRelease, track);
const lyrics = remote ? await optional(BASE+'federation/tracks/lyrics?content_id='+encodeURIComponent(track.content_id)) :
track.has_lyrics ? await optional(BASE+'lyrics/'+id) : null;
track.has_lyrics = Boolean(lyrics?.versions?.length);
const artistImages = {}, imageUrls = new Set([track.cover_url, release.cover_url]);
const credits = new Set([...track.artists,...(track.featured_artists || []),...release.artists].map(a => a.id));
for (const credit of credits) {
const url = await this.read('meta', 'artist-image/'+credit);
if (url) { artistImages[credit] = url; imageUrls.add(url); }
}
const keys = [], assets = new Map();
for (const url of imageUrls) {
const key = coverKey(url);
if (!key || keys.includes(key)) continue;
if (!(await this.read('assets', key))) {
if (remaining <= 0) continue;
try {
const res = await get(key);
if (!res.ok || !res.headers.get('Content-Type')?.startsWith('image/')) continue;
const blob = await res.blob();
if (!blob.size || blob.size > remaining) continue;
assets.set(key,blob);
addedBytes += blob.size;
remaining -= blob.size;
} catch { signal?.throwIfAborted(); continue; }
}
keys.push(key);
}
if (!keys.includes(coverKey(track.cover_url))) track.cover_url = null;
if (!keys.includes(coverKey(release.cover_url))) release.cover_url = track.cover_url;
for (const [artist, url] of Object.entries(artistImages)) if (!keys.includes(coverKey(url))) delete artistImages[artist];
signal?.throwIfAborted();
const row = {id,file:fileKey,bytes:file.bytes,track,release,assets:keys,artistImages,downloaded_at:Date.now()};
await this.write(['tracks','files','assets','meta','lyrics','pending'], getStore => {
getStore('tracks').put(row);
getStore('files').put(file,fileKey);
getStore('meta').put(release,'release/'+track.release_id);
getStore('meta').put(used + addedBytes,'bytes');
getStore('meta').put(crypto.randomUUID(),'revision');
if (lyrics) getStore('lyrics').put(lyrics, id);
else getStore('lyrics').delete(id);
getStore('pending').delete(id);
for (const [key,blob] of assets) getStore('assets').put(blob,key);
});
newName = null;
if (previous) await this.prune(dir);
} finally {
if (newName) await dir.removeEntry(newName).catch(() => {});
}
}
async prune(dir) {
const rows = await this.all('tracks');
const usedFiles = new Set(rows.map(row => row.file));
const usedAssets = new Set(rows.flatMap(row => row.assets));
const activeNames = new Set();
const db = await this.db();
const tx = db.transaction(['files','assets']);
const [fileKeys, files, assetKeys, assets] = await Promise.all([
requests(tx.objectStore('files').getAllKeys()), requests(tx.objectStore('files').getAll()),
requests(tx.objectStore('assets').getAllKeys()), requests(tx.objectStore('assets').getAll()),
]);
await this.write(['files','assets','meta'], get => {
let bytes = 0;
fileKeys.forEach((key,i) => {
if (usedFiles.has(key)) { activeNames.add(files[i].name); bytes += files[i].bytes; }
else get('files').delete(key);
});
assetKeys.forEach((key,i) => {
if (usedAssets.has(key)) bytes += assets[i].size;
else get('assets').delete(key);
});
get('meta').put(bytes,'bytes');
});
for await (const [name] of dir.entries()) {
if (!activeNames.has(name)) await dir.removeEntry(name);
}
}
previewCleanup(criteria = {}) {
return this._cleanup(criteria, null);
}
removeMany(ids, criteria = {}) {
if (!Array.isArray(ids)) throw new TypeError('Expected selected track IDs');
const selected = new Set(ids.map(trackId).filter(Boolean));
return navigator.locks.request(this.name, () => this._cleanup(criteria, selected));
}
async remove(value) {
const id = trackId(value);
if (id) await navigator.locks.request(this.name, () => this._cleanup({}, new Set([id]), true));
}
async _cleanup(criteria, selected, cancelUnstored = false) {
for (const [field, cutoff] of Object.entries(criteria)) {
if (!['downloadedBefore','lastPlayedBefore'].includes(field) || !Number.isFinite(cutoff))
throw new TypeError('Invalid offline cleanup cutoff');
}
const deleting = selected !== null;
const db = await this.db();
const tx = db.transaction(deleting ? stores : ['tracks','plays','files','assets'], deleting ? 'readwrite' : 'readonly');
const get = name => tx.objectStore(name);
const finished = new Promise((resolve,reject) => {
tx.oncomplete = resolve;
tx.onabort = () => reject(tx.error || new DOMException('Cleanup aborted','AbortError'));
});
let ids, bytes, discardedFiles;
try {
const [rows, activity, used] = await Promise.all([
requests(get('tracks').getAll()), requests(get('plays').getAll()),
deleting ? requests(get('meta').get('bytes')) : 0,
]);
const lastPlay = new Map(activity.map(p => [p.id, p.last_played_at]));
const retainedFiles = new Set(), retainedAssets = new Set(), retainedReleases = new Set();
const files = new Set(), assets = new Set(), releases = new Set();
ids = [];
for (const row of rows) {
const lastUsed = lastPlay.get(row.id) ?? row.downloaded_at;
const matches = (!deleting || selected.has(row.id))
&& (criteria.downloadedBefore === undefined || row.downloaded_at < criteria.downloadedBefore)
&& (criteria.lastPlayedBefore === undefined || lastUsed < criteria.lastPlayedBefore);
if (matches) ids.push(row.id);
(matches ? files : retainedFiles).add(row.file);
(matches ? releases : retainedReleases).add(row.track.release_id);
for (const key of row.assets) (matches ? assets : retainedAssets).add(key);
}
const fileKeys = [...files].filter(key => !retainedFiles.has(key));
const assetKeys = [...assets].filter(key => !retainedAssets.has(key));
// OPFS holds the audio. These reads access file descriptors and Blob sizes only.
const [fileInfo, artwork] = await Promise.all([
Promise.all(fileKeys.map(key => requests(get('files').get(key)))),
Promise.all(assetKeys.map(key => requests(get('assets').get(key)))),
]);
discardedFiles = fileInfo.filter(Boolean);
bytes = discardedFiles.reduce((n,f) => n + f.bytes, 0) + artwork.reduce((n,a) => n + (a?.size || 0), 0);
if (deleting) {
// Reading plays and checking cutoffs in this same write transaction protects a newly played track.
for (const id of cancelUnstored ? selected : ids) {
for (const name of ['tracks','plays','pending','lyrics']) get(name).delete(id);
}
for (const key of fileKeys) get('files').delete(key);
for (const key of assetKeys) get('assets').delete(key);
for (const id of releases) if (!retainedReleases.has(id)) get('meta').delete('release/'+id);
if (ids.length) {
get('meta').put(Math.max(0,(used || 0) - bytes),'bytes');
get('meta').put(crypto.randomUUID(),'revision');
}
}
await finished;
} catch (error) {
try { tx.abort(); } catch { /* already completed or aborted */ }
await finished.catch(() => {});
throw error;
}
// Commit the index first so an interrupted removal can only leave an unreferenced file.
if (deleting && discardedFiles.length) {
try {
const dir = await this.directory();
for (const file of discardedFiles) {
try { await dir.removeEntry(file.name); }
catch (error) { if (error.name !== 'NotFoundError') throw error; }
}
} catch (error) {
this._reconciled = false;
throw error;
}
}
return {ids, count:ids.length, bytes};
}
async clear() {
await navigator.locks.request(this.name, async () => {
await this.write(stores, get => { for (const store of stores) get(store).clear(); });
const root = await navigator.storage.getDirectory();
try { await root.removeEntry(this.name, {recursive:true}); }
catch (error) { if (error.name !== 'NotFoundError') throw error; }
});
}
async catalog() {
const revision = await this.read('meta','revision');
if (this._catalog && this._revision === revision) return this._catalog;
const rows = await this.all('tracks');
const tracks = [];
const artists = new Map(), releases = new Map();
for (const row of rows) {
const t = savedTrack(row);
tracks.push(t);
const release = releases.get(t.release_id) || {...row.release, tracks:[]};
release.tracks.push(t);
releases.set(release.id, release);
for (const a of [...t.artists, ...(t.featured_artists || []), ...row.release.artists]) {
if (!validId(a?.id)) continue;
const artist = artists.get(a.id) || {id:a.id,name:a.name,image_url:null,
releases:new Map(), top_tracks:new Map(), featured_tracks:new Map()};
if (row.artistImages[a.id]) artist.image_url = row.artistImages[a.id];
if (row.release.artists.some(credit => credit.id === a.id)) artist.releases.set(release.id,release);
if (t.artists.some(credit => credit.id === a.id)) artist.top_tracks.set(t.id,t);
else if (t.featured_artists?.some(credit => credit.id === a.id)) artist.featured_tracks.set(t.id,t);
artists.set(a.id,artist);
}
}
for (const release of releases.values()) {
release.tracks.sort((a,b) => (a.disc_number ?? 1)-(b.disc_number ?? 1) ||
(a.track_number ?? Infinity)-(b.track_number ?? Infinity) || a.id-b.id);
}
const card = r => ({id:r.id,title:r.title,release_type:r.release_type,year:r.year,
cover_url:r.cover_url,track_count:r.tracks.length,artists:r.artists.map(a => a.name),uploaders:r.uploaders});
const artistCards = new Map();
for (const artist of artists.values()) {
artist.releases = [...artist.releases.values()].sort((a,b) => (b.year||0)-(a.year||0)).map(card);
artist.top_tracks = [...artist.top_tracks.values()].sort((a,b) => (b.lastfm_rating||0)-(a.lastfm_rating||0));
artist.featured_tracks = [...artist.featured_tracks.values()];
const credited = [...artist.top_tracks,...artist.featured_tracks];
const recorded = new Set(credited.map(contentKey));
artist.total_track_count = recorded.size;
artist.track_content_ids = [...new Set(credited.map(t => t.content_id).filter(Boolean))];
artist.total_play_count = 0;
artist.image_url ||= artist.releases.find(r => r.cover_url)?.cover_url || credited.find(t => t.cover_url)?.cover_url || null;
artistCards.set(artist.id,{id:artist.id,name:artist.name,image_url:artist.image_url,release_count:artist.releases.length,track_count:recorded.size});
}
this._revision = revision;
this._catalog = {tracks, artists, artistCards, releases, releaseCards:[...releases.values()].map(card)};
return this._catalog;
}
async likedTracks(tracks, members = []) {
const [local, federated] = await Promise.all([
this.read('meta','likes'), this.read('meta','tracks/content/like'),
]);
const byId = new Map(tracks.map(t => [t.id,t]));
const trackIds = new Set(local?.track_ids || []);
const contentIds = new Set(federated || []);
const ordered = new Map();
for (const member of members) {
const track = byId.get(member.id);
if (track && (!local || trackIds.has(track.id) || contentIds.has(track.content_id))) ordered.set(track.id, track);
if (member.content_id && (!local || trackIds.has(member.id))) contentIds.add(member.content_id);
}
for (const id of trackIds) {
const track = byId.get(id);
if (track) {
ordered.set(track.id, track);
if (track.content_id) contentIds.add(track.content_id);
}
}
// A saved federated recording has a browser-only numeric ID. Its like follows the content.
for (const track of tracks) {
if (contentIds.has(track.content_id)) ordered.set(track.id, track);
}
return [...ordered.values()];
}
async playlist(id, tracks) {
const saved = await this.read('meta','playlists/'+id);
if (!saved && id !== -1) return null;
let items;
if (id === -1) {
const seen = new Set();
items = (await this.likedTracks(tracks, saved?.members)).filter(track => {
const key = contentKey(track);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
} else {
const byId = new Map(tracks.map(t => [t.id,t])), byContent = new Map(tracks.map(t => [contentKey(t),t]));
items = saved.members.flatMap(m => {
const track = byId.get(m.id) || byContent.get(m.content_id);
return track ? [{...track, playlist_track_id:m.playlist_track_id ?? null, sort_key:m.sort_key}] : [];
});
}
const covers = [...new Set(items.map(t => t.cover_url).filter(Boolean))].slice(0,4);
const pl = saved ? summarizePlaylist(saved) : {id,kind:'likes',title:'Likes',is_own:true};
return {...pl, cover_urls:covers, cover_url:covers[0] || null, track_count:items.length, tracks:items};
}
async respond(request) {
const url = new URL(request.url);
if (url.origin !== location.origin || !url.pathname.startsWith(BASE)) return null;
const path = url.pathname.slice(BASE.length);
if (path === 'tracks-by-ids' && request.method === 'POST') {
const {ids} = await request.json().catch(() => ({}));
if (!Array.isArray(ids)) return json({error:'Expected track IDs'},400);
const rows = await Promise.all(ids.slice(0,500).map(trackId).filter(Boolean).map(id => this.read('tracks',id)));
return json(rows.filter(Boolean).map(savedTrack));
}
if (!['GET','HEAD'].includes(request.method)) return null;
let m;
if ((m = /^(?:stream\/(\d+)|federation\/cache\/([a-f\d]{64}))$/.exec(path))) {
const file = await this.openAudio(m[1] ? Number(m[1]) : {content_id:'b3:'+m[2]});
return file ? binary(file,request) : missing();
}
const art = coverKey(url.pathname + url.search);
if (art) {
const blob = await this.read('assets', art);
return blob ? binary(blob,request) : missing();
}
if ((m = /^lyrics\/(\d+)$/.exec(path))) {
const row = await this.read('tracks', Number(m[1]));
return row ? json(await this.read('lyrics',row.id) || {content_id:row.track.content_id,versions:[]}) : missing();
}
if (path === 'federation/tracks/lyrics') {
const id = trackId('fed:'+url.searchParams.get('content_id'));
return json(id && await this.read('lyrics',id) || {versions:[]});
}
if (/^playlists\/-?\d+\/federation-tracks$/.test(path)) return json([]);
if (path === 'likes' || path === 'tracks/content/like') {
const rows = await this.likedTracks((await this.catalog()).tracks);
return path === 'likes' ? json({track_ids:rows.map(t => t.id)}) :
json([...new Set(rows.map(t => t.content_id).filter(Boolean))]);
}
if (['me','pins','follows','state'].includes(path)) {
const data = await this.read('meta', path);
if (path === 'me') return data ? json(data) : json({id:this.account,name:'',role:'user',stats:{}});
if (path === 'state') return json(data || {queue:[],current_track_id:null,position_ms:0,volume:0.7});
const catalog = await this.catalog();
if (path === 'follows') {
const artists = (data?.artist_ids || []).map(id => catalog.artistCards.get(id)).filter(Boolean);
return json({artist_ids:artists.map(a => a.id),artists});
}
const local = [];
for (const pin of (data || [])) {
if ((pin.kind === 'artist' && catalog.artists.has(pin.id)) ||
(pin.kind === 'release' && catalog.releases.has(pin.id)) ||
(pin.kind === 'playlist' && (await this.playlist(pin.id,catalog.tracks))?.tracks.length)) local.push(pin);
}
return json(local);
}
if (!/^(?:artists(?:\/\d+)?|releases\/\d+|search|playlists(?:\/-?\d+)?)$/.test(path)) return null;
const cat = await this.catalog();
if (path === 'artists') {
let list = [...cat.artistCards.values()].sort((a,b) => (!a.release_count)-(!b.release_count) || a.name.localeCompare(b.name));
if (url.searchParams.get('mine') === 'true') {
const owned = await Promise.all(list.map(a => this.read('meta','mine/'+a.id)));
list = list.filter((_,i) => owned[i]);
}
const page = positiveId(url.searchParams.get('page')) || 1;
const per_page = Math.min(500, positiveId(url.searchParams.get('limit')) || 80);
return json({page,per_page,total:list.length,has_more:page*per_page<list.length,items:list.slice((page-1)*per_page,page*per_page)});
}
if ((m = /^(artists|releases)\/(\d+)$/.exec(path))) {
const entry = cat[m[1]].get(Number(m[2]));
return entry ? json(entry) : missing();
}
if (path === 'search') {
const q = (url.searchParams.get('q') || '').trim().toLocaleLowerCase(), limit = positiveId(url.searchParams.get('limit')) || 10;
const scores = {artists:{},releases:{},tracks:{}};
function search(kind, rows, text) {
return rows.filter(row => {
const [primary,...rest] = text(row).map(value => String(value || '').toLocaleLowerCase());
const words = q.split(/\s+/).filter(Boolean), all = [primary,...rest].join(' ');
if (!words.length || !words.every(word => all.includes(word))) return false;
scores[kind][row.id] = primary === q ? 100 : primary.includes(q) ? 80 : 50;
return true;
}).sort((a,b) => scores[kind][b.id]-scores[kind][a.id]).slice(0,limit);
}
const artists = search('artists',[...cat.artistCards.values()],a => [a.name]);
const releases = search('releases',cat.releaseCards,r => [r.title,...r.artists]);
const tracks = search('tracks',cat.tracks,t => [t.title,...t.artists.map(a => a.name),t.release_title,...(t.featured_artists||[]).map(a=>a.name)]);
return json({scores,artists,releases,tracks,podcasts:[]});
}
if ((m = /^playlists\/(-?\d+)$/.exec(path))) {
const pl = await this.playlist(Number(m[1]),cat.tracks);
return pl ? json(pl) : missing();
}
const ids = (await this.read('meta','playlists') || []).map(p => p.id);
if (!ids.includes(-1)) ids.unshift(-1);
const pl = await Promise.all(ids.map(id => this.playlist(id,cat.tracks)));
return json(pl.filter(p => p && p.track_count).map(({tracks,...card}) => card));
}
}
globalThis.OfflineCatalog = OfflineCatalog;
})();
+339
View File
@@ -0,0 +1,339 @@
/* global OfflineCatalog */
importScripts('/offline-catalog.js');
const CACHE = 'furumusic-player-shell-v1';
const SETTINGS = '/__furumusic_offline__/settings';
const SHELL = '/__furumusic_offline__/player';
const ASSETS = ['/player.webmanifest', '/player-icon.svg'];
const ACCOUNT = 'X-Furumusic-Player-Account';
const ORIGIN = self.location.origin;
const BINDINGS = '/__furumusic_offline__/client/';
const bound = new Map();
let statePromise;
let serial = Promise.resolve();
let network = new AbortController();
let repo;
function catalog(account) {
if (!repo || String(repo.account) !== account) repo = new OfflineCatalog(account);
return repo;
}
function exclusive(work) {
const operation = serial.then(work);
serial = operation.catch(() => {});
return operation;
}
function settings() {
if (!statePromise) {
statePromise = caches.open(CACHE).then(cache => cache.match(SETTINGS)).then(r => r ? r.json() : null);
}
return statePromise;
}
async function broadcast(type, state) {
const windows = await self.clients.matchAll({ type:'window', includeUncontrolled:true });
for (const client of windows) {
if (isPlayer(client.url)) client.postMessage({ type, account:state.account, mode:state.mode });
}
}
async function save(state) {
const cache = await caches.open(CACHE);
if (state) await cache.put(SETTINGS, Response.json(state));
else await cache.delete(SETTINGS);
statePromise = Promise.resolve(state);
network.abort();
network = new AbortController();
if (state) await broadcast('offline-mode', state);
}
async function forget(state) {
if (!state) return;
const cache = await caches.open(CACHE);
await cache.delete(SHELL);
await save(null);
// Notify pages before waiting for the catalog write lock. Downloads can hold
// that lock while their authorization response is still pending.
await broadcast('offline-purge', { account:state.account, mode:'disabled' });
await catalog(state.account).clear();
repo = undefined;
}
function isPlayer(url) {
if (!url) return false;
const loc = new URL(url);
return loc.origin === ORIGIN && loc.pathname === '/';
}
async function bind(id, account) {
if (!id || bound.get(id) === account) return;
bound.set(id, account);
await (await caches.open(CACHE)).put(BINDINGS + id, new Response(account));
}
async function accountFor(id) {
if (!id) return null;
if (!bound.has(id)) {
const response = await (await caches.open(CACHE)).match(BINDINGS + id);
if (response) bound.set(id, await response.text());
}
return bound.get(id);
}
async function cleanBindings(keep = '') {
const cache = await caches.open(CACHE);
const clients = new Set((await self.clients.matchAll({type:'window', includeUncontrolled:true})).map(c => c.id));
for (const request of await cache.keys()) {
const pathname = new URL(request.url).pathname;
if (!pathname.startsWith(BINDINGS)) continue;
const id = pathname.slice(BINDINGS.length);
if (id !== keep && !clients.has(id)) { await cache.delete(request); bound.delete(id); }
}
}
function isOffline(state) {
return state?.mode === 'manual' || state?.mode === 'auto';
}
function validShell(response, account) {
return response.status === 200 && response.headers.get(ACCOUNT) === account &&
response.headers.get('Content-Type')?.startsWith('text/html');
}
function probeAccount(response) {
const id = response.headers.get(ACCOUNT);
if (response.status === 204 && /^[1-9]\d*$/.test(id)) return id;
return response.status === 401 && id === '0' ? id : null;
}
async function verifySession(request) {
const signal = requestSignal(request, 3500);
try {
const response = await fetch('/offline-probe', {
credentials:'same-origin', cache:'no-store', redirect:'manual', signal:signal.signal,
});
return probeAccount(response);
} catch {
return null;
} finally {
signal.clear();
}
}
async function configure({ account, mode }, sourceId) {
account = String(account);
if (!/^[1-9]\d*$/.test(account) || !['manual','auto','online','disabled'].includes(mode)) {
throw Error('Invalid offline settings');
}
const current = await settings();
const cache = await caches.open(CACHE);
const caller = await accountFor(sourceId);
if ((caller && caller !== account) || (isOffline(current) && current.account !== account)) {
throw Error('Account changed');
}
if (mode === 'disabled') {
if (current?.account === account) {
await cache.delete(SHELL);
await save({ account, mode });
}
return mode;
}
if (current?.account !== account || current.mode === 'disabled' || !await cache.match(SHELL)) {
if (mode !== 'online') throw Error('Save the player online first');
const shell = await fetch('/', {cache:'no-store', credentials:'same-origin', redirect:'manual'});
if (!validShell(shell, account)) throw Error('Could not verify this account');
if (current && current.account !== account) await forget(current);
await cache.addAll(ASSETS);
await cache.put(SHELL, shell);
}
if (current?.account !== account || current.mode !== mode) await save({ account, mode });
await bind(sourceId, account);
return mode;
}
self.addEventListener('install', event => event.waitUntil(self.skipWaiting()));
self.addEventListener('activate', event => event.waitUntil(cleanBindings().then(() => self.clients.claim())));
self.addEventListener('message', event => {
if (!isPlayer(event.source?.url)) return;
if (event.data?.type === 'offline-client' && /^[1-9]\d*$/.test(String(event.data.account))) {
event.waitUntil(bind(event.source.id, String(event.data.account)));
return;
}
if (event.data?.type !== 'offline-config') return;
const reply = event.ports[0];
event.waitUntil(exclusive(() => configure(event.data, event.source.id))
.then(mode => { reply?.postMessage({ ok:true, mode }); },
e => { reply?.postMessage({ ok:false, error:e.message }); }));
});
function unavailable() {
return Response.json({ error:'Unavailable offline' }, { status:503, headers:{'Cache-Control':'no-store'} });
}
async function local(request, state, rootNavigation) {
const url = new URL(request.url);
if (url.origin !== ORIGIN) return Response.error();
const cache = await caches.open(CACHE);
if (rootNavigation) {
const shell = await cache.match(SHELL);
if (!shell || !validShell(shell, state.account)) return unavailable();
const html = (await shell.text()).replace('data-offline-mode="online"', 'data-offline-mode="' + state.mode + '"');
return new Response(html, {headers:{'Content-Type':'text/html; charset=utf-8', 'Cache-Control':'private, no-store', [ACCOUNT]:state.account}});
}
if (ASSETS.includes(url.pathname)) return await cache.match(url.pathname) || unavailable();
if (request.mode === 'navigate') return unavailable();
if (request.method === 'GET' && ['/api/player/federation/artists/events', '/api/player/federation/search/events'].includes(url.pathname)) {
// A stream opened just before disconnection must stop without reconnecting.
return new Response(null, {status:204, headers:{'Cache-Control':'no-store'}});
}
const read = ['GET','HEAD'].includes(request.method) ||
(request.method === 'POST' && url.pathname === '/api/player/tracks-by-ids');
if (read && url.pathname.startsWith('/api/')) {
try {
return await catalog(state.account).respond(request) || unavailable();
} catch {
return unavailable();
}
}
return unavailable();
}
// A mode change cuts off requests already waiting for headers and in-flight audio streams.
function requestSignal(request, timeout) {
const controller = new AbortController();
const signals = [network.signal, request.signal];
let signal;
const abort = () => controller.abort();
if (AbortSignal.any) {
signal = AbortSignal.any([...signals, controller.signal]);
} else {
signal = controller.signal;
for (const source of signals) {
if (source.aborted) controller.abort();
else source.addEventListener('abort', abort, { once:true });
}
}
const timer = timeout ? setTimeout(() => controller.abort(), timeout) : null;
return { signal, clear() {
clearTimeout(timer);
if (!AbortSignal.any) for (const source of signals) source.removeEventListener('abort', abort);
} };
}
function fallback(request, state, rootNavigation) {
return exclusive(async () => {
const now = await settings();
if (now === state && state.mode === 'online') await save({account:state.account, mode:'auto'});
return settings();
}).then(now => now?.account === state.account && isOffline(now)
? local(request, now, rootNavigation) : unavailable());
}
async function handle(event) {
const {request} = event;
const url = new URL(request.url);
const sameOrigin = url.origin === ORIGIN;
const rootNavigation = request.mode === 'navigate' && isPlayer(request.url);
const auth = sameOrigin && (url.pathname === '/logout' || url.pathname === '/auth/oidc/callback' ||
(url.pathname === '/login' && request.method === 'POST'));
const state = await settings();
if (!state) return fetch(request);
const source = event.clientId && await self.clients.get(event.clientId);
const player = rootNavigation || isPlayer(source?.url) || (!source && isPlayer(request.referrer));
if (rootNavigation) event.waitUntil(cleanBindings(event.resultingClientId));
if (isOffline(state) && sameOrigin && ASSETS.includes(url.pathname)) return local(request, state, false);
if (auth) {
if (player && isOffline(state)) return unavailable();
let response;
try {
response = await fetch(request);
return response;
} finally {
let changed = url.pathname === '/logout';
if (!changed && response && response.status < 400) {
const identity = await verifySession(request);
// A rejected login also returns 200. Keep existing downloads when
// the session still belongs to their owner.
changed = identity === null ? response.type === 'opaqueredirect' || response.redirected : identity !== state.account;
}
if (changed) {
await exclusive(async () => { if ((await settings())?.account === state.account) await forget(state); });
}
}
}
if (!player) return fetch(request);
if (state.mode === 'disabled' && !rootNavigation) return fetch(request);
if (!rootNavigation && source && (await accountFor(source.id)) !== state.account) return unavailable();
const probe = sameOrigin && url.pathname === '/offline-probe' && request.method === 'GET';
if (isOffline(state) && !(probe && state.mode === 'auto')) {
if (rootNavigation) await bind(event.resultingClientId, state.account);
return local(request, state, rootNavigation);
}
const savedAudio = /^\/api\/player\/(?:stream\/\d+|federation\/cache\/[a-f\d]{64})$/.test(url.pathname);
if (state.mode === 'online' && sameOrigin && ['GET','HEAD'].includes(request.method) &&
savedAudio && url.searchParams.get('saved') === '1') {
const saved = await catalog(state.account).respond(request).catch(() => null);
if (saved && (saved.ok || saved.status === 416)) return saved;
}
const timed = state.mode !== 'disabled' && (rootNavigation || probe || url.pathname === '/api/player/me');
const signal = requestSignal(request, timed ? 3500 : 0);
let response;
try {
// The queue lookup is a read with a JSON body; retain it for a local retry.
const queueLookup = sameOrigin && request.method === 'POST' && url.pathname === '/api/player/tracks-by-ids';
response = await fetch(queueLookup ? request.clone() : request, {signal:signal.signal});
} catch {
if (state.mode === 'disabled' || !sameOrigin) return Response.error();
// Cancelled device polls and failed reachability probes have no local payload to replay.
if (request.signal.aborted || probe) return unavailable();
if (rootNavigation) await bind(event.resultingClientId, state.account);
return fallback(request, state, rootNavigation);
} finally {
signal.clear();
}
if (([502,503,504].includes(response.status) || (rootNavigation && response.status >= 500)) &&
!probe && state.mode === 'online' && sameOrigin) {
if (rootNavigation) await bind(event.resultingClientId, state.account);
return fallback(request, state, rootNavigation);
}
// Intermediaries and older API handlers may return a login page/401 during
// an outage. Only our session endpoint or a labeled player page identifies an account.
const checkAuth = sameOrigin && (response.status === 401 ||
(rootNavigation && (response.type === 'opaqueredirect' || response.redirected ||
(response.ok && !validShell(response, state.account)))) ||
(probe && probeAccount(response) !== state.account));
if (checkAuth) {
const label = rootNavigation && response.ok ? response.headers.get(ACCOUNT) : null;
const identity = probe ? probeAccount(response) : /^\d+$/.test(label) ? label : await verifySession(request);
if (identity === state.account && !rootNavigation) return response;
if (identity === null || identity === state.account) {
if (probe) return unavailable();
if (state.mode === 'disabled') return response;
if (rootNavigation) await bind(event.resultingClientId, state.account);
return fallback(request, state, rootNavigation);
}
// Revocation aborts the previous account's streams. Detach this verified
// response first, so the login redirect or new account page still reaches the window.
const reply = response.type === 'opaqueredirect' ? Response.redirect(ORIGIN + '/login', 302) :
new Response(response.body && ![204,205,304].includes(response.status) && request.method !== 'HEAD' ? await response.blob() : null, {
headers:response.headers, status:response.status, statusText:response.statusText,
});
await exclusive(async () => { if ((await settings())?.account === state.account) await forget(state); });
return reply;
}
if (rootNavigation && state.mode === 'online' && validShell(response, state.account)) {
await bind(event.resultingClientId, state.account);
const copy = response.clone();
event.waitUntil(exclusive(async () => {
if (await settings() === state) await (await caches.open(CACHE)).put(SHELL, copy);
}));
}
return response;
}
self.addEventListener('fetch', event => {
if (['https:','http:'].includes(new URL(event.request.url).protocol)) event.respondWith(handle(event));
});
+330
View File
@@ -0,0 +1,330 @@
use super::*;
use sqlx::{PgConnection, PgPool};
#[derive(Deserialize)]
struct PinChange {
href: String,
pinned: bool,
title: String,
cover_url: Option<String>,
before_href: Option<String>,
after_href: Option<String>,
}
#[derive(Deserialize)]
struct PinMove {
href: String,
before_href: Option<String>,
}
enum Mutation {
Set(PinChange),
Move(PinMove),
}
enum MissingAnchor<'a> {
Reject,
RestoreAfter(Option<&'a str>),
}
#[derive(Debug, PartialEq)]
enum Outcome {
Applied,
Invalid,
Missing,
Stale,
}
enum Target {
Artist(i64),
Release(i64),
Playlist(i64),
Peer,
}
impl Target {
fn parse(href: &str) -> Option<Self> {
if href.len() > 2048 || href.chars().any(char::is_control) {
return None;
}
if let Some(value) = href
.strip_prefix("#artistfed?name=")
.or_else(|| href.strip_prefix("#releasefed?key="))
{
return (!value.is_empty()).then_some(Self::Peer);
}
let (kind, value) = href.split_once('/')?;
let id = value.parse::<i64>().ok()?;
if id <= 0 || value != id.to_string() {
return None;
}
match kind {
"#artist" => Some(Self::Artist(id)),
"#release" => Some(Self::Release(id)),
"#playlist" => Some(Self::Playlist(id)),
_ => None,
}
}
}
const PIN_TARGETS: &str = "FROM furumusic__sidebar_pin pin
LEFT JOIN furumusic__artist a ON a.id = pin.artist_id AND NOT a.is_hidden
LEFT JOIN furumusic__release r ON r.id = pin.release_id AND NOT r.is_hidden
LEFT JOIN furumusic__playlist p ON p.id = pin.playlist_id AND (
p.owner_id = pin.user_id OR p.is_public OR EXISTS (
SELECT 1 FROM furumusic__saved_playlist s WHERE s.user_id = pin.user_id AND s.playlist_id = p.id))";
const VISIBLE: &str = "(COALESCE(a.id, r.id, p.id) IS NOT NULL OR pin.peer_title IS NOT NULL)";
const PIN_ORDER: &str = "pin.position NULLS LAST, pin.created_at, pin.href";
async fn list(pool: &PgPool, user: i64) -> Result<Vec<serde_json::Value>, sqlx::Error> {
sqlx::query_scalar(&format!(
r#"SELECT jsonb_build_object(
'href', pin.href, 'kind', CASE WHEN pin.href LIKE '#artist%' THEN 'artist'
WHEN pin.href LIKE '#release%' THEN 'release' ELSE 'playlist' END,
'id', COALESCE(a.id, r.id, p.id), 'title', COALESCE(a.name, r.title, p.title, pin.peer_title),
'cover_url', COALESCE('/api/player/cover/' || COALESCE(a.image_file_id, r.cover_file_id) || '/small', art.urls[1], pin.peer_cover),
'cover_urls', COALESCE(art.urls, ARRAY[]::text[]))
{PIN_TARGETS} LEFT JOIN LATERAL ({}) art ON p.id IS NOT NULL
WHERE pin.user_id = $1 AND {VISIBLE} ORDER BY {PIN_ORDER}"#, super::playlist_artwork::cover_sql()))
.bind(user).fetch_all(pool).await
}
async fn set_pin(
conn: &mut PgConnection,
user: i64,
target: Target,
change: &PinChange,
) -> Result<Outcome, sqlx::Error> {
if !change.pinned {
sqlx::query("DELETE FROM furumusic__sidebar_pin WHERE user_id = $1 AND href = $2")
.bind(user)
.bind(&change.href)
.execute(conn)
.await?;
return Ok(Outcome::Applied);
}
let (artist, release, playlist, title) = match target {
Target::Artist(id) => (Some(id), None, None, None),
Target::Release(id) => (None, Some(id), None, None),
Target::Playlist(id) => (None, None, Some(id), None),
Target::Peer => (None, None, None, Some(change.title.trim())),
};
let cover = change.cover_url.as_deref().filter(|url| {
title.is_some()
&& url.len() <= 4096
&& url.starts_with("/api/player/federation/catalog/artwork/")
});
let inserted: Option<bool> = sqlx::query_scalar(r#"WITH written AS (
INSERT INTO furumusic__sidebar_pin (user_id, href, artist_id, release_id, playlist_id, peer_title, peer_cover, created_at)
SELECT $1, $2, $3, $4, $5, $6, $7, clock_timestamp() WHERE $6::text IS NOT NULL
OR EXISTS (SELECT 1 FROM furumusic__artist WHERE id = $3 AND NOT is_hidden)
OR EXISTS (SELECT 1 FROM furumusic__release WHERE id = $4 AND NOT is_hidden)
OR EXISTS (SELECT 1 FROM furumusic__playlist p WHERE p.id = $5 AND (p.owner_id = $1 OR p.is_public OR
EXISTS (SELECT 1 FROM furumusic__saved_playlist s WHERE s.user_id = $1 AND s.playlist_id = p.id)))
ON CONFLICT (user_id, href) DO UPDATE SET peer_title = EXCLUDED.peer_title, peer_cover = EXCLUDED.peer_cover
RETURNING href)
SELECT NOT EXISTS (SELECT 1 FROM furumusic__sidebar_pin WHERE user_id = $1 AND href = $2) FROM written"#)
.bind(user).bind(&change.href).bind(artist).bind(release).bind(playlist).bind(title).bind(cover)
.fetch_optional(&mut *conn).await?;
match inserted {
None => Ok(Outcome::Missing),
Some(true) if change.before_href.is_some() || change.after_href.is_some() => {
place_pin(
conn,
user,
&change.href,
change.before_href.as_deref(),
MissingAnchor::RestoreAfter(change.after_href.as_deref()),
)
.await
}
Some(_) => Ok(Outcome::Applied),
}
}
// A move requires its anchor to still exist. Undo may fall back to the old
// predecessor when the next pin was removed in another tab.
async fn place_pin(
conn: &mut PgConnection,
user: i64,
href: &str,
before: Option<&str>,
missing: MissingAnchor<'_>,
) -> Result<Outcome, sqlx::Error> {
let mut pins: Vec<(String, bool)> = sqlx::query_as(&format!(
"SELECT pin.href, {VISIBLE} {PIN_TARGETS} WHERE pin.user_id = $1 ORDER BY {PIN_ORDER}"
))
.bind(user)
.fetch_all(&mut *conn)
.await?;
let Some(source) = pins
.iter()
.position(|(key, visible)| *visible && key == href)
else {
return Ok(Outcome::Stale);
};
if before == Some(href) {
return Ok(Outcome::Applied);
}
let moved = pins.remove(source);
let visible_index = |href: &str| {
pins.iter()
.position(|(key, visible)| *visible && key == href)
};
let at = if let Some(i) = before.and_then(visible_index) {
i
} else if let MissingAnchor::RestoreAfter(previous) = missing {
previous
.and_then(visible_index)
.map_or(pins.len(), |i| i + 1)
} else if before.is_none() {
pins.len()
} else {
return Ok(Outcome::Stale);
};
if at != source {
pins.insert(at, moved);
let order: Vec<_> = pins.into_iter().map(|(key, _)| key).collect();
sqlx::query("UPDATE furumusic__sidebar_pin p SET position = u.pos
FROM unnest($2::text[]) WITH ORDINALITY AS u(href, pos)
WHERE p.user_id = $1 AND p.href = u.href AND p.position IS DISTINCT FROM u.pos")
.bind(user).bind(order).execute(conn).await?;
}
Ok(Outcome::Applied)
}
async fn mutate(pool: &PgPool, user: i64, action: Mutation) -> Result<Outcome, sqlx::Error> {
let mut tx = pool.begin().await?;
// Serialize all pin writers for this account, including when it has no pins.
sqlx::query("SELECT id FROM furumusic__user WHERE id = $1 FOR NO KEY UPDATE")
.bind(user)
.fetch_one(&mut *tx)
.await?;
let outcome = match action {
Mutation::Set(change) => {
let Some(target) = Target::parse(&change.href) else {
return Ok(Outcome::Invalid);
};
if change.pinned
&& matches!(target, Target::Peer)
&& (change.title.trim().is_empty() || change.title.len() > 2048)
{
return Ok(Outcome::Invalid);
}
set_pin(&mut tx, user, target, &change).await?
}
Mutation::Move(change) => {
place_pin(
&mut tx,
user,
&change.href,
change.before_href.as_deref(),
MissingAnchor::Reject,
)
.await?
}
};
if outcome == Outcome::Applied {
tx.commit().await?;
}
Ok(outcome)
}
async fn handle(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: PgPool,
change: Option<Mutation>,
) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
if let Some(action) = change {
match mutate(&pool, user.id, action)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?
{
Outcome::Applied => {}
Outcome::Invalid => {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"invalid sidebar target",
));
}
Outcome::Missing => {
return Ok(json_error(
StatusCode::NOT_FOUND,
"sidebar target not found",
));
}
Outcome::Stale => return Ok(json_error(StatusCode::CONFLICT, "sidebar pins changed")),
}
}
let items = list(&pool, user.id)
.await
.map_err(|err| cot::Error::internal(err.to_string()))?;
let mut response = Json(items).into_response()?;
response
.headers_mut()
.insert("Cache-Control", "private, no-store".parse().unwrap());
Ok(response)
}
#[cfg(test)]
#[path = "pins_tests.rs"]
mod tests;
pub(super) fn route(pool: Arc<tokio::sync::OnceCell<PgPool>>, config: Arc<AppConfig>) -> Route {
let connect = move || {
let pool = pool.clone();
let config = config.clone();
async move {
pool.get_or_try_init(|| async {
sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&config.database_url)
.await
})
.await
.cloned()
.map_err(|err| cot::Error::internal(err.to_string()))
}
};
let read = connect.clone();
let write = connect.clone();
Route::with_handler_and_name(
"/pins",
get(move |auth_ctx, session, db| {
let pool = read();
async move { handle(auth_ctx, session, db, pool.await?, None).await }
})
.post(move |auth_ctx, session, db, Json(body): Json<PinChange>| {
let pool = write();
async move {
handle(
auth_ctx,
session,
db,
pool.await?,
Some(Mutation::Set(body)),
)
.await
}
})
.put(move |auth_ctx, session, db, Json(body): Json<PinMove>| {
let pool = connect();
async move {
handle(
auth_ctx,
session,
db,
pool.await?,
Some(Mutation::Move(body)),
)
.await
}
}),
"player_sidebar_pins",
)
}
+224
View File
@@ -0,0 +1,224 @@
use super::*;
fn change(href: &str, pinned: bool) -> PinChange {
PinChange {
href: href.into(),
pinned,
title: "Peer album".into(),
cover_url: Some("/api/player/federation/catalog/artwork/example".into()),
before_href: None,
after_href: None,
}
}
async fn set(pool: &PgPool, user: i64, href: &str, pinned: bool) -> Result<bool, sqlx::Error> {
Ok(mutate(pool, user, Mutation::Set(change(href, pinned))).await? == Outcome::Applied)
}
async fn move_before(
pool: &PgPool,
user: i64,
href: &str,
before: Option<&str>,
) -> Result<Outcome, sqlx::Error> {
mutate(
pool,
user,
Mutation::Move(PinMove {
href: href.into(),
before_href: before.map(String::from),
}),
)
.await
}
async fn check_order(pool: &PgPool, expected: &[&str]) -> anyhow::Result<()> {
let items = list(pool, 3).await?;
let order: Vec<_> = items.iter().map(|p| p["href"].as_str().unwrap()).collect();
assert_eq!(order, expected);
Ok(())
}
async fn exercise_order(pool: &PgPool) -> anyhow::Result<()> {
let [a, b, c, d] = [
"#artistfed?name=a",
"#artistfed?name=b",
"#artistfed?name=c",
"#artistfed?name=d",
];
check_order(pool, &[a, b, c]).await?;
for _ in 0..2 {
assert_eq!(move_before(pool, 3, c, Some(a)).await?, Outcome::Applied);
check_order(pool, &[c, a, b]).await?;
}
assert!(set(pool, 3, d, true).await?);
assert_eq!(move_before(pool, 3, b, None).await?, Outcome::Applied);
check_order(pool, &[c, a, d, b]).await?;
assert!(set(pool, 3, a, false).await?);
let undo = |next: &str| {
let mut request = change(a, true);
request.before_href = Some(next.into());
request.after_href = Some(c.into());
Mutation::Set(request)
};
assert_eq!(mutate(pool, 3, undo(d)).await?, Outcome::Applied);
check_order(pool, &[c, a, d, b]).await?;
assert_eq!(move_before(pool, 3, a, None).await?, Outcome::Applied);
assert_eq!(mutate(pool, 3, undo(d)).await?, Outcome::Applied);
check_order(pool, &[c, d, b, a]).await?;
assert!(set(pool, 3, a, false).await?);
assert_eq!(
mutate(pool, 3, undo("#artistfed?name=gone")).await?,
Outcome::Applied
);
check_order(pool, &[c, a, d, b]).await?;
let (left, right) = tokio::try_join!(
move_before(pool, 3, a, Some(c)),
move_before(pool, 3, b, Some(d))
)?;
assert_eq!((left, right), (Outcome::Applied, Outcome::Applied));
check_order(pool, &[a, c, b, d]).await?;
assert_eq!(move_before(pool, 2, a, None).await?, Outcome::Stale);
assert!(list(pool, 2).await?.is_empty());
assert!(set(pool, 3, "#playlist/32", true).await?);
sqlx::query("UPDATE furumusic__playlist SET is_public = false WHERE id=32")
.execute(pool)
.await?;
assert_eq!(
move_before(pool, 3, a, Some("#playlist/32")).await?,
Outcome::Stale
);
assert_eq!(
move_before(pool, 3, "#playlist/32", None).await?,
Outcome::Stale
);
check_order(pool, &[a, c, b, d]).await?;
sqlx::query("UPDATE furumusic__playlist SET is_public = true WHERE id=32")
.execute(pool)
.await?;
sqlx::query("DELETE FROM furumusic__user WHERE id=3")
.execute(pool)
.await?;
Ok(())
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
async fn sidebar_pins_respect_visibility_and_catalog_changes() -> anyhow::Result<()> {
use std::str::FromStr;
let url = std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?;
let admin = PgPool::connect(&url).await?;
let schema = format!("sidebar_pins_{}", uuid::Uuid::new_v4().simple());
sqlx::query(&format!("CREATE SCHEMA {schema}"))
.execute(&admin)
.await?;
let options = sqlx::postgres::PgConnectOptions::from_str(&url)?
.options([("search_path", schema.as_str())]);
let pool = PgPool::connect_with(options).await?;
let result = exercise_pins(&pool).await;
pool.close().await;
sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
.execute(&admin)
.await?;
result
}
async fn exercise_pins(pool: &PgPool) -> anyhow::Result<()> {
sqlx::raw_sql("
CREATE TABLE furumusic__user (id bigint PRIMARY KEY);
CREATE TABLE furumusic__artist (id bigint PRIMARY KEY, name text, is_hidden bool, image_file_id bigint);
CREATE TABLE furumusic__release (id bigint PRIMARY KEY, title text, is_hidden bool, cover_file_id bigint);
CREATE TABLE furumusic__playlist (id bigint PRIMARY KEY, title text, owner_id bigint, is_public bool, cover_file_id bigint);
CREATE TABLE furumusic__track (id bigint PRIMARY KEY, release_id bigint, is_hidden bool, cover_file_id bigint, title text DEFAULT 'Song');
CREATE TABLE furumusic__playlist_track (id bigint, playlist_id bigint, track_id bigint, position int);
CREATE TABLE furumusic__saved_playlist (user_id bigint, playlist_id bigint);
INSERT INTO furumusic__user VALUES (1),(2),(3);
INSERT INTO furumusic__artist VALUES (10,'Artist',false,70), (11,'Hidden artist',true,NULL);
INSERT INTO furumusic__release VALUES (12,'Album',false,80), (13,'Hidden album',true,81);
INSERT INTO furumusic__track (id,release_id,is_hidden,cover_file_id) VALUES (20,12,true,90), (21,13,false,NULL), (22,12,false,NULL), (23,12,false,91);
INSERT INTO furumusic__playlist VALUES (30,'My list',1,false,99), (31,'Someone else',2,false,NULL), (32,'Public list',2,true,NULL);
INSERT INTO furumusic__playlist_track VALUES (1,32,20,1), (2,32,21,2), (3,32,22,3), (4,32,23,4);
").execute(pool).await?;
sqlx::raw_sql(include_str!("sidebar_pins.sql"))
.execute(pool)
.await?;
sqlx::raw_sql(include_str!("playlist_artwork_schema.sql"))
.execute(pool)
.await?;
sqlx::query("INSERT INTO furumusic__sidebar_pin (user_id,href,peer_title,created_at) VALUES
(3,'#artistfed?name=c','C','2026-01-02'), (3,'#artistfed?name=b','B','2026-01-01'), (3,'#artistfed?name=a','A','2026-01-01')")
.execute(pool).await?;
sqlx::raw_sql(include_str!("sidebar_pin_order.sql"))
.execute(pool)
.await?;
exercise_order(pool).await?;
assert!(set(pool, 1, "#playlist/30", true).await?);
assert!(set(pool, 1, "#playlist/30", true).await?);
assert_eq!(list(pool, 1).await?.len(), 1);
assert_eq!(
list(pool, 1).await?[0]["cover_url"],
"/api/player/cover/99/small"
);
for href in ["#playlist/31", "#artist/11", "#release/13", "#artist/99"] {
assert!(!set(pool, 1, href, true).await?, "{href}");
}
assert!(set(pool, 2, "#playlist/31", true).await?);
assert!(set(pool, 1, "#playlist/31", false).await?);
assert_eq!(list(pool, 2).await?.len(), 1);
assert!(set(pool, 1, "#playlist/32", true).await?);
let public = list(pool, 1)
.await?
.into_iter()
.find(|p| p["id"] == 32)
.unwrap();
assert_eq!(public["cover_url"], "/api/player/cover/80/small");
sqlx::query("UPDATE furumusic__playlist SET cover_ids=ARRAY[91,80]::bigint[] WHERE id=32")
.execute(pool)
.await?;
let picked = list(pool, 1)
.await?
.into_iter()
.find(|p| p["id"] == 32)
.unwrap();
assert_eq!(
picked["cover_urls"],
serde_json::json!(["/api/player/cover/91/small", "/api/player/cover/80/small"])
);
assert_eq!(picked["cover_url"], picked["cover_urls"][0]);
sqlx::query("UPDATE furumusic__playlist SET is_public = false WHERE id=32")
.execute(pool)
.await?;
assert_eq!(list(pool, 1).await?.len(), 1);
sqlx::query("INSERT INTO furumusic__saved_playlist VALUES (1,32)")
.execute(pool)
.await?;
assert_eq!(list(pool, 1).await?.len(), 2);
assert!(set(pool, 1, "#artist/10", true).await?);
assert!(set(pool, 1, "#release/12", true).await?);
let peer = "#releasefed?key=%7B%22normalized_title%22%3A%22album%22%7D";
assert!(set(pool, 1, peer, true).await?);
let pinned = list(pool, 1).await?;
assert_eq!(pinned.len(), 5);
let remote = pinned.into_iter().find(|p| p["href"] == peer).unwrap();
assert_eq!(remote["title"], "Peer album");
assert!(remote["id"].is_null());
assert_eq!(
remote["cover_url"],
"/api/player/federation/catalog/artwork/example"
);
sqlx::raw_sql("DELETE FROM furumusic__artist WHERE id=10; DELETE FROM furumusic__release WHERE id=12; DELETE FROM furumusic__playlist WHERE id=30;")
.execute(pool).await?;
assert_eq!(list(pool, 1).await?.len(), 2);
assert!(set(pool, 1, peer, false).await?);
sqlx::query("DELETE FROM furumusic__user WHERE id=1")
.execute(pool)
.await?;
let remaining: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM furumusic__sidebar_pin")
.fetch_one(pool)
.await?;
assert_eq!(remaining, 1);
assert_eq!(list(pool, 2).await?[0]["href"], "#playlist/31");
Ok(())
}
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="14" fill="#111827"/>
<path d="M27 15v31.5a9 9 0 1 1-5-8.1V22l27-6v24.5a9 9 0 1 1-5-8.1V15.9L27 20.5" fill="#67e8f9"/>
</svg>

After

Width:  |  Height:  |  Size: 223 B

+11
View File
@@ -0,0 +1,11 @@
{
"id": "/",
"name": "Furumusic",
"short_name": "Furumusic",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#121212",
"theme_color": "#121212",
"icons": [{ "src": "/player-icon.svg", "sizes": "any", "type": "image/svg+xml" }]
}
+487
View File
@@ -0,0 +1,487 @@
use super::*;
use cot::request::Request;
use schemars::JsonSchema;
use sqlx::{PgConnection, PgPool};
const CANDIDATES: &str = include_str!("playlist_cover_candidates.sql");
pub(super) fn cover_sql() -> String {
format!(include_str!("playlist_cover.sql"), candidates = CANDIDATES)
}
pub(super) fn db_error(error: sqlx::Error) -> cot::Error {
cot::Error::internal(error.to_string())
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct CoverOption {
cover_id: i64,
title: String,
cover_url: String,
#[serde(skip_serializing)]
automatic: bool,
}
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct Artwork {
cover_mode: &'static str,
cover_ids: Vec<i64>,
cover_url: Option<String>,
cover_urls: Vec<String>,
auto_cover_urls: Vec<String>,
cover_options: Vec<CoverOption>,
}
impl Artwork {
pub(super) fn automatic(urls: impl Iterator<Item = String>) -> Self {
let mut seen = HashSet::new();
let cover_urls: Vec<_> = urls
.filter(|url| seen.insert(url.clone()))
.take(4)
.collect();
Self {
cover_mode: "auto",
cover_ids: vec![],
cover_url: cover_urls.first().cloned(),
auto_cover_urls: cover_urls.clone(),
cover_urls,
cover_options: vec![],
}
}
}
pub(super) async fn load(
conn: &mut PgConnection,
id: i64,
editor: bool,
) -> Result<Artwork, sqlx::Error> {
#[derive(sqlx::FromRow)]
struct Stored {
cover_hash: Option<String>,
cover_file_id: Option<i64>,
cover_ids: Vec<i64>,
options: sqlx::types::Json<Vec<CoverOption>>,
}
let stored = sqlx::query_as::<_, Stored>(&format!(
"SELECT p.cover_hash, p.cover_file_id, p.cover_ids, (
SELECT COALESCE(jsonb_agg(jsonb_build_object(
'cover_id', c.art, 'title', c.title, 'automatic', c.automatic,
'cover_url', '/api/player/cover/' || c.art || '/small'
) ORDER BY c.position, c.item_id, c.automatic DESC, c.art), '[]')
FROM ({CANDIDATES}) c
) AS options FROM furumusic__playlist p WHERE p.id=$1"
))
.bind(id)
.fetch_one(conn)
.await?;
let options = stored.options.0;
let selected: Vec<_> = stored
.cover_ids
.iter()
.filter_map(|id| options.iter().find(|option| option.cover_id == *id))
.collect();
let ids = selected.iter().map(|o| o.cover_id).collect();
let auto_cover_urls: Vec<_> = options
.iter()
.filter(|o| o.automatic)
.take(4)
.map(|o| o.cover_url.clone())
.collect();
let upload = stored
.cover_hash
.map(|hash| format!("/api/player/playlists/{id}/cover?v={hash}"))
.or_else(|| cover_variant_url(stored.cover_file_id, "small"));
let (cover_mode, urls) = if let Some(url) = upload {
("upload", vec![url])
} else if selected.is_empty() {
("auto", auto_cover_urls.clone())
} else {
(
"releases",
selected.iter().map(|o| o.cover_url.clone()).collect(),
)
};
Ok(Artwork {
cover_mode,
cover_ids: ids,
cover_url: urls.first().cloned(),
auto_cover_urls,
cover_urls: urls,
cover_options: if editor { options } else { Vec::new() },
})
}
enum Change {
Keep,
Auto,
Releases(Vec<i64>),
Upload(Vec<u8>, String),
KeepUpload,
}
async fn cover_change(body: &mut UpdatePlaylistRequest) -> Result<Change, String> {
match (
body.cover_mode.as_deref(),
body.cover_ids.take(),
body.cover_image.take(),
) {
(None, None, None) => Ok(Change::Keep),
(Some("auto"), None, None) => Ok(Change::Auto),
(Some("releases"), Some(ids), None)
if (1..=4).contains(&ids.len())
&& ids.iter().all(|id| *id > 0)
&& ids.iter().collect::<HashSet<_>>().len() == ids.len() =>
{
Ok(Change::Releases(ids))
}
(Some("upload"), None, Some(encoded)) => {
let (jpeg, hash) = super::playlist_image::decode(encoded).await?;
Ok(Change::Upload(jpeg, hash))
}
(Some("upload"), None, None) => Ok(Change::KeepUpload),
_ => Err("Invalid playlist artwork selection".into()),
}
}
pub(super) async fn update(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: &PgPool,
path: Path<PathId>,
request: Request,
) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let id = path.0.id;
let owner: Option<i64> =
sqlx::query_scalar("SELECT owner_id FROM furumusic__playlist WHERE id=$1")
.bind(id)
.fetch_optional(pool)
.await
.map_err(db_error)?;
match owner {
None => return Ok(json_error(StatusCode::NOT_FOUND, "playlist not found")),
Some(owner) if owner != user.id => {
return Ok(json_error(StatusCode::FORBIDDEN, "not your playlist"));
}
_ => {}
}
if !request
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.split(';').next())
.is_some_and(|s| s.trim().eq_ignore_ascii_case("application/json"))
{
return Ok(json_error(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"expected application/json",
));
}
let Ok(bytes) = request
.into_body()
.into_bytes_limited(6 * 1024 * 1024)
.await
else {
return Ok(json_error(
StatusCode::PAYLOAD_TOO_LARGE,
"playlist update exceeds 6 MiB",
));
};
let Ok(mut body) = serde_json::from_slice::<UpdatePlaylistRequest>(&bytes) else {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"invalid playlist update",
));
};
let change = match cover_change(&mut body).await {
Ok(change) => change,
Err(msg) => return Ok(json_error(StatusCode::BAD_REQUEST, &msg)),
};
save(pool, user.id, id, body, change).await
}
async fn save(
pool: &PgPool,
owner: i64,
id: i64,
body: UpdatePlaylistRequest,
change: Change,
) -> cot::Result<cot::response::Response> {
let mut tx = pool.begin().await.map_err(db_error)?;
let current: Option<(String, bool)> = sqlx::query_as(
"SELECT title::text, cover_hash IS NOT NULL OR cover_file_id IS NOT NULL
FROM furumusic__playlist WHERE id=$1 AND owner_id=$2 FOR UPDATE",
)
.bind(id)
.bind(owner)
.fetch_optional(&mut *tx)
.await
.map_err(db_error)?;
let Some((old_title, uploaded)) = current else {
return Ok(json_error(StatusCode::NOT_FOUND, "playlist not found"));
};
let title = body.title.as_deref().map(str::trim).unwrap_or(&old_title);
if title.is_empty() || title.chars().count() > 255 {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"playlist name must be 1–255 characters",
));
}
if matches!(change, Change::KeepUpload) && !uploaded {
return Ok(json_error(StatusCode::BAD_REQUEST, "no uploaded cover"));
}
if let Change::Releases(ids) = &change {
let valid: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM furumusic__playlist p CROSS JOIN LATERAL ({CANDIDATES}) c
WHERE p.id=$1 AND c.art=ANY($2)"
))
.bind(id)
.bind(ids)
.fetch_one(&mut *tx)
.await
.map_err(db_error)?;
if valid != ids.len() as i64 {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"choose artwork from this playlist",
));
}
}
let keep = matches!(change, Change::Keep | Change::KeepUpload);
let (ids, jpeg, hash) = match change {
Change::Releases(selection) => (selection, None, None),
Change::Upload(bytes, digest) => (Vec::new(), Some(bytes), Some(digest)),
_ => (Vec::new(), None, None),
};
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
sqlx::query(
"UPDATE furumusic__playlist SET title=$2, description=COALESCE($3,description), updated_at=$4,
cover_file_id=CASE WHEN $5 THEN cover_file_id ELSE NULL END,
cover_ids=CASE WHEN $5 THEN cover_ids ELSE $6 END,
cover_hash=CASE WHEN $5 THEN cover_hash ELSE $7 END,
cover_jpeg=CASE WHEN $5 THEN cover_jpeg ELSE $8 END WHERE id=$1"
)
.bind(id)
.bind(title)
.bind(body.description)
.bind(now)
.bind(keep)
.bind(ids)
.bind(hash)
.bind(jpeg)
.execute(&mut *tx)
.await
.map_err(db_error)?;
let artwork = load(&mut tx, id, true).await.map_err(db_error)?;
tx.commit().await.map_err(db_error)?;
if title != old_title {
record_fed_playlist_renamed(pool, owner, id, title).await;
}
let mut response = serde_json::json!(artwork);
response["ok"] = true.into();
response["title"] = title.into();
Json(response).into_response()
}
#[derive(Deserialize)]
struct CoverVersion {
v: String,
}
async fn image_for_listener(
pool: &PgPool,
id: i64,
user: i64,
hash: &str,
) -> Result<Option<Vec<u8>>, sqlx::Error> {
sqlx::query_scalar(
"SELECT cover_jpeg FROM furumusic__playlist p WHERE p.id=$1 AND p.cover_hash=$3 AND
(p.owner_id=$2 OR p.is_public OR EXISTS(
SELECT 1 FROM furumusic__saved_playlist s WHERE s.playlist_id=p.id AND s.user_id=$2))"
).bind(id).bind(user).bind(hash).fetch_optional(pool).await
}
pub(super) fn route(pool: Arc<tokio::sync::OnceCell<PgPool>>, config: Arc<AppConfig>) -> Route {
Route::with_handler_and_name(
"/playlists/{id}/cover",
get(
move |auth_ctx: auth::AuthContext,
session: Session,
db: Database,
path: Path<PathId>,
query: UrlQuery<CoverVersion>| {
let pool = pool.clone();
let config = config.clone();
async move {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let pool = pool
.get_or_try_init(|| async {
sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&config.database_url)
.await
})
.await
.map_err(db_error)?;
let bytes = image_for_listener(pool, path.0.id, user.id, &query.0.v)
.await
.map_err(db_error)?;
let Some(bytes) = bytes else {
return Ok(json_error(StatusCode::NOT_FOUND, "cover not found"));
};
Ok::<_, cot::Error>(
cot::http::Response::builder()
.header(CONTENT_TYPE, "image/jpeg")
.header("Cache-Control", "private, no-store")
.header("X-Content-Type-Options", "nosniff")
.body(Body::fixed(bytes))
.expect("valid cover response"),
)
}
},
),
"player_playlist_cover",
)
}
#[cfg(test)]
mod tests {
use super::*;
fn request(value: serde_json::Value) -> UpdatePlaylistRequest {
serde_json::from_value(value).unwrap()
}
#[tokio::test]
async fn rejects_malformed_selections() {
for input in [
serde_json::json!({"cover_mode":"releases","cover_ids":[]}),
serde_json::json!({"cover_mode":"releases","cover_ids":[1,2,3,4,5]}),
serde_json::json!({"cover_mode":"releases","cover_ids":[1,1]}),
serde_json::json!({"cover_mode":"auto","cover_image":"ignored"}),
serde_json::json!({"cover_ids":[5]}),
] {
assert!(cover_change(&mut request(input)).await.is_err());
}
}
#[tokio::test]
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
async fn playlist_artwork_tracks_membership_and_ownership() -> anyhow::Result<()> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?)
.await?;
sqlx::raw_sql("
CREATE TEMP TABLE furumusic__playlist(id bigint PRIMARY KEY,title text,description text,owner_id bigint,is_public boolean,updated_at text,cover_file_id bigint);
CREATE TEMP TABLE furumusic__release(id bigint PRIMARY KEY,title text,is_hidden boolean DEFAULT false,cover_file_id bigint);
CREATE TEMP TABLE furumusic__track(id bigint PRIMARY KEY,title text,release_id bigint,is_hidden boolean DEFAULT false,cover_file_id bigint);
CREATE TEMP TABLE furumusic__playlist_track(id bigint,playlist_id bigint,track_id bigint,position int);
CREATE TEMP TABLE furumusic__saved_playlist(user_id bigint,playlist_id bigint);
INSERT INTO furumusic__playlist VALUES (1,'List',NULL,10,false,'',NULL),(2,'Old cover',NULL,10,false,'',60);
INSERT INTO furumusic__release(id,title,cover_file_id) VALUES (1,'A',11),(2,'B',22),(3,'C',22),(4,'D',44);
INSERT INTO furumusic__track(id,title,release_id,cover_file_id) VALUES (1,'One',1,51),(2,'Two',1,52),(3,'Three',2,NULL),(4,'Four',3,NULL),(5,'Five',4,NULL);
INSERT INTO furumusic__playlist_track VALUES (1,1,1,1),(2,1,2,2),(3,1,3,3),(4,1,4,4),(5,2,5,1);
").execute(&pool).await?;
sqlx::raw_sql(include_str!("playlist_artwork_schema.sql"))
.execute(&pool)
.await?;
let read = async |id| {
let mut conn = pool.acquire().await?;
load(&mut conn, id, true).await
};
let auto = read(1).await?;
assert_eq!(
auto.cover_urls,
["/api/player/cover/11/small", "/api/player/cover/22/small"]
);
assert_eq!(
auto.cover_options
.iter()
.map(|o| o.cover_id)
.collect::<Vec<_>>(),
[11, 51, 52, 22]
);
assert_eq!(read(2).await?.cover_mode, "upload");
let rename = || request(serde_json::json!({"title":"Invalid rename"}));
assert_eq!(
save(&pool, 9, 1, rename(), Change::Auto).await?.status(),
StatusCode::NOT_FOUND
);
assert_eq!(
save(&pool, 10, 1, rename(), Change::Releases(vec![44]))
.await?
.status(),
StatusCode::BAD_REQUEST
);
assert_eq!(
sqlx::query_scalar::<_, String>("SELECT title FROM furumusic__playlist WHERE id=1")
.fetch_one(&pool)
.await?,
"List"
);
let unchanged = || request(serde_json::json!({}));
assert_eq!(
save(&pool, 10, 1, unchanged(), Change::Releases(vec![52, 51]))
.await?
.status(),
StatusCode::OK
);
let chosen = read(1).await?;
assert_eq!(chosen.cover_mode, "releases");
assert_eq!(
chosen.cover_urls,
["/api/player/cover/52/small", "/api/player/cover/51/small"]
);
assert_eq!(chosen.auto_cover_urls, auto.cover_urls);
sqlx::query("DELETE FROM furumusic__playlist_track WHERE track_id=2")
.execute(&pool)
.await?;
assert_eq!(read(1).await?.cover_ids, [51]);
let bytes = vec![1, 2, 3];
assert_eq!(
save(
&pool,
10,
1,
unchanged(),
Change::Upload(bytes.clone(), "hash".into())
)
.await?
.status(),
StatusCode::OK
);
assert_eq!(
read(1).await?.cover_urls,
["/api/player/playlists/1/cover?v=hash"]
);
assert_eq!(
image_for_listener(&pool, 1, 10, "hash").await?,
Some(bytes.clone())
);
assert!(image_for_listener(&pool, 1, 9, "hash").await?.is_none());
assert!(
image_for_listener(&pool, 1, 10, "old-hash")
.await?
.is_none()
);
sqlx::query("UPDATE furumusic__playlist SET is_public=true WHERE id=1")
.execute(&pool)
.await?;
assert_eq!(image_for_listener(&pool, 1, 9, "hash").await?, Some(bytes));
assert_eq!(
save(&pool, 10, 1, unchanged(), Change::Auto)
.await?
.status(),
StatusCode::OK
);
assert_eq!(read(1).await?.cover_urls, auto.cover_urls);
assert!(image_for_listener(&pool, 1, 10, "hash").await?.is_none());
Ok(())
}
}
+6
View File
@@ -0,0 +1,6 @@
ALTER TABLE furumusic__playlist
ADD COLUMN cover_ids bigint[] NOT NULL DEFAULT '{}'
CHECK (cardinality(cover_ids) <= 4),
ADD COLUMN cover_jpeg bytea,
ADD COLUMN cover_hash text,
ADD CONSTRAINT playlist_cover_image_pair CHECK ((cover_jpeg IS NULL) = (cover_hash IS NULL))
+12
View File
@@ -0,0 +1,12 @@
SELECT CASE
WHEN p.cover_hash IS NOT NULL THEN ARRAY['/api/player/playlists/' || p.id || '/cover?v=' || p.cover_hash]
WHEN p.cover_file_id IS NOT NULL THEN ARRAY['/api/player/cover/' || p.cover_file_id || '/small']
ELSE (
SELECT COALESCE((array_agg(url ORDER BY choice) FILTER (WHERE choice IS NOT NULL))[1:4],
(array_agg(url ORDER BY position, item_id) FILTER (WHERE automatic))[1:4], ARRAY[]::text[])
FROM (
SELECT '/api/player/cover/' || art || '/small' AS url,
array_position(p.cover_ids, art) AS choice, position, item_id, automatic
FROM ({candidates}) options
) ranked
) END AS urls
+19
View File
@@ -0,0 +1,19 @@
WITH members AS (
SELECT r.id AS release_id, r.title::text AS release_title, r.cover_file_id AS release_art,
t.title::text AS track_title, t.cover_file_id AS track_art, pt.position, pt.id AS item_id
FROM furumusic__playlist_track pt
JOIN furumusic__track t ON t.id = pt.track_id AND NOT t.is_hidden
JOIN furumusic__release r ON r.id = t.release_id AND NOT r.is_hidden
WHERE pt.playlist_id = p.id AND COALESCE(r.cover_file_id, t.cover_file_id) IS NOT NULL
), album_tiles AS (
SELECT DISTINCT ON (release_id) COALESCE(release_art, track_art) AS art,
release_title AS title, position, item_id, true AS automatic
FROM members ORDER BY release_id, position, item_id
), tiles AS (
SELECT * FROM album_tiles
UNION ALL
SELECT track_art, track_title, position, item_id, false
FROM members WHERE track_art IS NOT NULL AND track_art IS DISTINCT FROM release_art
)
SELECT DISTINCT ON (art) art, title, position, item_id, automatic
FROM tiles ORDER BY art, automatic DESC, position, item_id
+108
View File
@@ -0,0 +1,108 @@
use std::io::Cursor;
use base64::{Engine, engine::general_purpose::STANDARD};
use image::{
DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits, codecs::jpeg::JpegEncoder,
imageops::FilterType,
};
use sha2::{Digest, Sha256};
const MAX_UPLOAD: usize = 4 * 1024 * 1024;
const MAX_DECODED: u64 = 64 * 1024 * 1024;
const INVALID: &str = "Choose a JPEG, PNG or WebP image up to 4 MiB";
const TOO_LARGE: &str = "The image dimensions are too large";
pub(super) async fn decode(encoded: String) -> Result<(Vec<u8>, String), String> {
if encoded.len() > MAX_UPLOAD.div_ceil(3) * 4 {
return Err(INVALID.into());
}
// Bound concurrent full-resolution decodes independently of the async worker pool.
static SLOTS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2);
let slot = SLOTS.acquire().await.map_err(|_| INVALID.to_owned())?;
tokio::task::spawn_blocking(move || {
let _slot = slot;
let raw = STANDARD.decode(encoded).map_err(|_| INVALID)?;
if raw.len() > MAX_UPLOAD {
return Err(INVALID);
}
canonical_cover(&raw)
})
.await
.map_err(|_| "Could not process the image".to_owned())?
.map_err(str::to_owned)
}
fn canonical_cover(raw: &[u8]) -> Result<(Vec<u8>, String), &'static str> {
let format = image::guess_format(raw).map_err(|_| INVALID)?;
if !matches!(
format,
ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::WebP
) {
return Err(INVALID);
}
let mut reader = ImageReader::with_format(Cursor::new(raw), format);
let mut limits = Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(MAX_DECODED);
reader.limits(limits);
let mut decoder = reader.into_decoder().map_err(|_| INVALID)?;
if decoder.total_bytes() > MAX_DECODED {
return Err(TOO_LARGE);
}
let orientation = decoder.orientation().map_err(|_| INVALID)?;
let mut image = DynamicImage::from_decoder(decoder).map_err(|_| INVALID)?;
image.apply_orientation(orientation);
let edge = 512.min(image.width()).min(image.height());
if edge == 0 {
return Err(INVALID);
}
let side = image.width().min(image.height());
let square = image.crop_imm(
(image.width() - side) / 2,
(image.height() - side) / 2,
side,
side,
);
let thumb = square
.resize_exact(edge, edge, FilterType::Triangle)
.to_rgba8();
// Match the dark artwork tile underneath transparent areas of the preview.
let mut rgb = image::RgbImage::new(edge, edge);
for (out, pixel) in rgb.pixels_mut().zip(thumb.pixels()) {
let alpha = u16::from(pixel[3]);
for (channel, &value) in out.0.iter_mut().zip(pixel.0.iter()) {
*channel = ((u16::from(value) * alpha + 32 * (255 - alpha)) / 255) as u8;
}
}
let mut jpeg = Vec::new();
JpegEncoder::new_with_quality(&mut jpeg, 85)
.encode_image(&rgb)
.map_err(|_| INVALID)?;
let hash = format!("{:x}", Sha256::digest(&jpeg));
Ok((jpeg, hash))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn uploads_are_validated_and_saved_as_square_jpegs() {
let mut input = Cursor::new(Vec::new());
DynamicImage::new_rgba8(10, 6)
.write_to(&mut input, ImageFormat::Png)
.unwrap();
let (jpeg, hash) = decode(STANDARD.encode(input.into_inner())).await.unwrap();
let cover = image::load_from_memory_with_format(&jpeg, ImageFormat::Jpeg).unwrap();
assert_eq!((cover.width(), cover.height()), (6, 6));
assert_eq!(hash, format!("{:x}", Sha256::digest(&jpeg)));
for invalid in [
"invalid base64!".to_owned(),
STANDARD.encode(b"<svg/>"),
"A".repeat(MAX_UPLOAD.div_ceil(3) * 4 + 1),
] {
assert!(decode(invalid).await.is_err());
}
}
}
+4 -1
View File
@@ -35,6 +35,9 @@ pub(super) struct CreatePlaylistRequest {
pub(super) struct UpdatePlaylistRequest {
pub(super) title: Option<String>,
pub(super) description: Option<String>,
pub(super) cover_mode: Option<String>,
pub(super) cover_ids: Option<Vec<i64>>,
pub(super) cover_image: Option<String>,
}
#[derive(Debug, Deserialize)]
@@ -96,7 +99,7 @@ pub(super) struct PathTrackId {
#[derive(Debug, Deserialize)]
pub(super) struct FederationLyricsQuery {
pub(super) owner: String,
pub(super) owner: Option<String>,
pub(super) content_id: String,
}
+101
View File
@@ -0,0 +1,101 @@
use sqlx::PgPool;
pub(super) async fn toggle(
pool: &PgPool,
user: i64,
release: i64,
) -> anyhow::Result<(bool, Vec<i64>)> {
let mut tx = pool.begin().await?;
crate::federation::devices::likes::lock(&mut tx, user).await?;
let recordings = sqlx::query_as::<_, (i64, Vec<i64>, bool)>(include_str!("release_likes.sql"))
.bind(user)
.bind(release)
.fetch_all(&mut *tx)
.await?;
let liked = recordings.is_empty()
|| recordings
.iter()
.any(|(_, ids, remote)| ids.is_empty() && !remote);
let changed: Vec<i64>;
if liked {
changed = recordings
.into_iter()
.filter(|(_, ids, remote)| ids.is_empty() && !remote)
.map(|(id, _, _)| id)
.collect();
sqlx::query(
"INSERT INTO furumusic__user_liked_track (user_id, track_id, created_at)
SELECT $1, id, $3 FROM unnest($2::bigint[]) AS id
ON CONFLICT (user_id, track_id) DO NOTHING",
)
.bind(user)
.bind(&changed)
.bind(chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string())
.execute(&mut *tx)
.await?;
} else {
let stored: Vec<i64> = recordings
.iter()
.flat_map(|(_, ids, _)| ids.iter().copied())
.collect();
sqlx::query(
"DELETE FROM furumusic__user_liked_track WHERE user_id=$1 AND track_id=ANY($2)",
)
.bind(user)
.bind(stored)
.execute(&mut *tx)
.await?;
changed = recordings.into_iter().map(|(id, _, _)| id).collect();
}
tx.commit().await?;
Ok((liked, changed))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
async fn release_likes_keep_one_copy_and_light_up_each_alias() -> anyhow::Result<()> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?)
.await?;
sqlx::raw_sql("
CREATE TEMP TABLE furumusic__track(id bigint, release_id bigint, is_hidden boolean DEFAULT false);
CREATE TEMP TABLE furumusic__track_content_alias(track_id bigint, content_id text, hidden boolean DEFAULT false);
CREATE TEMP TABLE furumusic__user_liked_track(user_id bigint, track_id bigint, created_at text,
PRIMARY KEY(user_id, track_id));
CREATE TEMP TABLE furumusic__fed_state_like(user_id bigint, content_id text, liked boolean, local_track_id bigint);
INSERT INTO furumusic__track(id, release_id) VALUES (1,10),(2,10),(3,10),(4,10),(5,20),(6,30),(7,40);
INSERT INTO furumusic__track_content_alias(track_id, content_id)
VALUES (1,'album'),(2,'album'),(3,'third'),(5,'album'),(6,'single'),(7,'pending');
INSERT INTO furumusic__user_liked_track VALUES (9,5,'original'),(9,6,'single'),(10,1,'other user');
INSERT INTO furumusic__fed_state_like VALUES (9,'pending',true,NULL);
").execute(&pool).await?;
let (liked, mut added) = toggle(&pool, 9, 10).await?;
added.sort_unstable();
assert!(liked);
assert_eq!(added, [3, 4]); // Preserve the original copy from release 20.
let mut ids = sqlx::query_scalar::<_, i64>(include_str!("liked_ids.sql"))
.bind(9_i64)
.fetch_all(&pool)
.await?;
ids.sort_unstable();
assert_eq!(ids, [1, 2, 3, 4, 5, 6, 7]);
let (liked, mut removed) = toggle(&pool, 9, 10).await?;
removed.sort_unstable();
assert!(!liked);
assert_eq!(removed, [1, 3, 4]);
let stored: Vec<(i64, i64)> = sqlx::query_as(
"SELECT user_id, track_id FROM furumusic__user_liked_track ORDER BY user_id, track_id",
)
.fetch_all(&pool)
.await?;
assert_eq!(stored, [(9, 6), (10, 1)]);
assert_eq!(toggle(&pool, 9, 40).await?, (false, vec![7]));
Ok(())
}
}
+26
View File
@@ -0,0 +1,26 @@
-- One candidate per recording. An unindexed track keeps its catalog identity.
WITH members AS (
SELECT DISTINCT ON (a.content_id, CASE WHEN a.content_id IS NULL THEN t.id END)
t.id AS track_id, a.content_id
FROM furumusic__track t
LEFT JOIN furumusic__track_content_alias a ON a.track_id = t.id
WHERE t.release_id = $2 AND NOT t.is_hidden
ORDER BY a.content_id, CASE WHEN a.content_id IS NULL THEN t.id END, t.id
), copies AS (
SELECT m.track_id, m.content_id, ARRAY(
SELECT m.track_id
UNION ALL
SELECT a.track_id FROM furumusic__track_content_alias a
WHERE a.content_id = m.content_id AND a.track_id <> m.track_id
) AS aliases FROM members m
)
SELECT c.track_id, ARRAY(
SELECT l.track_id FROM furumusic__user_liked_track l
WHERE l.user_id = $1 AND l.track_id = ANY(c.aliases)
) AS liked_ids,
EXISTS (
SELECT 1 FROM furumusic__fed_state_like f
WHERE f.user_id = $1 AND f.content_id = c.content_id
AND f.liked AND f.local_track_id IS NULL
) AS liked_remotely
FROM copies c
@@ -0,0 +1,7 @@
-- The web history endpoint generated this four-part ID for older clients.
-- Imports from the old play_history table use the shorter legacy-web:<id>.
UPDATE furumusic__listen_event
SET listened_ms = track_duration_ms
WHERE track_duration_ms > 0
AND listened_ms > track_duration_ms
AND listen_id ~ '^legacy-web:[0-9]+:[0-9]+:[0-9]+$'
+1 -23
View File
@@ -74,6 +74,7 @@ pub(super) struct PlaybackStateRow {
#[derive(sqlx::FromRow)]
pub(super) struct PlaylistRow {
pub(super) id: i64,
pub(super) cover_urls: Vec<String>,
pub(super) title: String,
pub(super) track_count: i64,
pub(super) is_own: bool,
@@ -182,35 +183,12 @@ pub(super) struct UploadTrackEditRow {
pub(super) release_year: Option<i32>,
}
#[derive(sqlx::FromRow)]
pub(super) struct AppearanceTrackRow {
pub(super) id: i64,
pub(super) title: String,
pub(super) release_id: i64,
pub(super) release_title: String,
pub(super) release_year: Option<i32>,
pub(super) duration_seconds: f64,
pub(super) cover_file_id: Option<i64>,
pub(super) release_cover_file_id: Option<i64>,
pub(super) uploader_name: String,
pub(super) audio_format: Option<String>,
pub(super) audio_bitrate: Option<i32>,
pub(super) audio_sample_rate: Option<i32>,
pub(super) audio_bit_depth: Option<i32>,
pub(super) file_size_bytes: Option<i64>,
pub(super) lastfm_listeners: Option<i64>,
pub(super) lastfm_playcount: Option<i64>,
pub(super) lastfm_rating: Option<f64>,
pub(super) lastfm_updated_at: Option<String>,
}
#[derive(sqlx::FromRow)]
pub(super) struct SearchArtistRow {
pub(super) id: i64,
pub(super) name: String,
pub(super) image_file_id: Option<i64>,
pub(super) release_count: i64,
pub(super) track_count: i64,
}
#[derive(sqlx::FromRow)]
+5 -4
View File
@@ -41,11 +41,12 @@ pub(super) async fn detail_handler(
let Some(mut share) = load_share(pool, &path.0.id).await? else {
return Ok(json_error(StatusCode::NOT_FOUND, "shared music not found"));
};
if auth::get_request_user(&auth_ctx, &session, &db)
let guest = auth::get_request_user(&auth_ctx, &session, &db)
.await
.is_none()
{
for track in &mut share.tracks {
.is_none();
for track in &mut share.tracks {
track.uploader_name.clear();
if guest {
track.stream_url = format!("/api/player/shares/{}/stream/{}", share.token, track.id);
if track.cover_url.is_some() {
track.cover_url = Some(format!(
+2
View File
@@ -0,0 +1,2 @@
-- Until explicitly arranged, pins retain their creation order after ordered pins.
ALTER TABLE furumusic__sidebar_pin ADD COLUMN position bigint
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE furumusic__sidebar_pin (
user_id bigint NOT NULL REFERENCES furumusic__user(id) ON DELETE CASCADE,
href text NOT NULL,
artist_id bigint REFERENCES furumusic__artist(id) ON DELETE CASCADE,
release_id bigint REFERENCES furumusic__release(id) ON DELETE CASCADE,
playlist_id bigint REFERENCES furumusic__playlist(id) ON DELETE CASCADE,
peer_title text,
peer_cover text,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, href),
CHECK (num_nonnulls(artist_id, release_id, playlist_id, peer_title) = 1)
)
+21
View File
@@ -0,0 +1,21 @@
(()=>{var bt=!1,Et=!1,B=[],vt=-1,Fe=!1,wt=!1;function gr(e){ai(e)}function xr(){wt=!0}function yr(){wt=!1,br()}function ai(e){B.includes(e)||(B.push(e),e._x_schedulerPriority!==void 0&&(Fe=!0)),br()}function ue(e){let t=B.indexOf(e);t!==-1&&t>vt&&B.splice(t,1)}function br(){if(!Et&&!bt){if(wt)return;bt=!0,queueMicrotask(ci)}}function ci(){bt=!1,Et=!0;for(let e=0;e<B.length;e++)Fe&&li(e),B[e](),vt=e;B.length=0,vt=-1,Fe=!1,Et=!1}function li(e){let t=new Map,r=B.slice(e).sort((n,i)=>fi(n,i,t));for(let n=0;n<r.length;n++)B[e+n]=r[n];Fe=!1}function fi(e,t,r){return yt(e)?yt(t)?_r(e._x_schedulerPriority.el,r)-_r(t._x_schedulerPriority.el,r)||e._x_schedulerPriority.order-t._x_schedulerPriority.order:-1:yt(t)?1:0}function yt(e){return e._x_schedulerPriority!==void 0}function _r(e,t){if(t.has(e))return t.get(e);let r=0,n=e;for(;e;)r++,e._x_teleportBack?e=e._x_teleportBack:typeof ShadowRoot=="function"&&e.parentNode instanceof ShadowRoot?e=e.parentNode.host:e=e.parentElement;return t.set(n,r),r}var D,P,H,At,ui=0,St=!0;function Er(e){St=!1,e(),St=!0}function vr(e){D=e.reactive,H=e.release,P=t=>e.effect(t,{scheduler:r=>{St?gr(r):r()}}),At=e.raw}function Tt(e){P=e}function wr(e){let t=()=>{};return[(n,i)=>{let o=i?.priority==="structural"?ui++:void 0,s=P(n);return o!==void 0&&s!==void 0&&(s._x_schedulerPriority={el:e,order:o}),e._x_effects||(e._x_effects=new Set,e._x_runEffects=()=>{e._x_effects.forEach(a=>a())}),e._x_effects.add(s),t=()=>{s!==void 0&&(e._x_effects.delete(s),H(s))},s},()=>{t()}]}function Ve(e,t){let r=!0,n,i,o=P(()=>{let s=e(),a=JSON.stringify(s);if(!r&&(typeof s=="object"||s!==n)){let c=typeof n=="object"?JSON.parse(i):n;queueMicrotask(()=>{t(s,c)})}n=s,i=a,r=!1});return()=>{ue(o),H(o)}}async function Sr(e){xr();try{await e(),await Promise.resolve()}finally{yr()}}var Ar=[],Tr=[],Or=[];function Nr(e){Or.push(e)}function de(e,t){typeof t=="function"?(e._x_cleanups||(e._x_cleanups=[]),e._x_cleanups.push(t)):(t=e,Tr.push(t))}function Be(e){Ar.push(e)}function He(e,t,r){e._x_attributeCleanups||(e._x_attributeCleanups={}),e._x_attributeCleanups[t]||(e._x_attributeCleanups[t]=[]),e._x_attributeCleanups[t].push(r)}function Ot(e,t){e._x_attributeCleanups&&Object.entries(e._x_attributeCleanups).forEach(([r,n])=>{(t===void 0||t.includes(r))&&(n.forEach(i=>i()),delete e._x_attributeCleanups[r])})}function Cr(e){for(e._x_effects?.forEach(ue);e._x_cleanups?.length;)e._x_cleanups.pop()()}var Ue=new MutationObserver(qe),Nt=!1;function we(){Ue.observe(document,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0}),Nt=!0}function Ct(){di(),Ue.disconnect(),Nt=!1}var Z=[];function di(){let e=Ue.takeRecords();Z.push(()=>e.length>0&&qe(e));let t=Z.length;queueMicrotask(()=>{if(Z.length===t)for(;Z.length>0;)Z.shift()()})}function Rr(){for(;Z.length>0;)Z.shift()();let e=Ue.takeRecords();e.length>0&&qe(e)}function h(e){if(!Nt)return e();Ct();try{return e()}finally{we()}}var Rt=!1,$e=[];function Dr(){Rt=!0}function Mr(){Rt=!1,qe($e),$e=[]}function qe(e){if(Rt){$e=$e.concat(e);return}let t=[],r=new Set,n=new Map,i=new Map;for(let o=0;o<e.length;o++)if(!e[o].target._x_ignoreMutationObserver&&(e[o].type==="childList"&&(e[o].removedNodes.forEach(s=>{s.nodeType===1&&s._x_marker&&r.add(s)}),e[o].addedNodes.forEach(s=>{if(s.nodeType===1){if(r.has(s)){r.delete(s);return}s._x_marker||t.push(s)}})),e[o].type==="attributes")){let s=e[o].target,a=e[o].attributeName,c=e[o].oldValue,l=()=>{n.has(s)||n.set(s,[]),n.get(s).push({name:a,value:s.getAttribute(a)})},f=()=>{i.has(s)||i.set(s,[]),i.get(s).push(a)};s.hasAttribute(a)&&c===null?l():s.hasAttribute(a)?(f(),l()):f()}i.forEach((o,s)=>{Ot(s,o)}),n.forEach((o,s)=>{Ar.forEach(a=>a(s,o))});for(let o of r)t.some(s=>s.contains(o))||Tr.forEach(s=>s(o));for(let o of t)o.isConnected&&Or.forEach(s=>s(o));t=null,r=null,n=null,i=null}function ze(e){return L(U(e))}function I(e,t,r){return e._x_dataStack=[t,...U(r||e)],()=>{e._x_dataStack=e._x_dataStack.filter(n=>n!==t)}}function U(e){return e._x_dataStack?e._x_dataStack:typeof ShadowRoot=="function"&&e instanceof ShadowRoot?U(e.host):e.parentNode?U(e.parentNode):[]}function L(e){return new Proxy({objects:e},pi)}function kr(e,t){return e===null||e===Object.prototype?null:Object.prototype.hasOwnProperty.call(e,t)?e:kr(Object.getPrototypeOf(e),t)}var pi={ownKeys({objects:e}){return Array.from(new Set(e.flatMap(t=>Object.keys(t))))},has({objects:e},t){return t==Symbol.unscopables?!1:e.some(r=>Object.prototype.hasOwnProperty.call(r,t)||Reflect.has(r,t))},get({objects:e},t,r){return t=="toJSON"?hi:Reflect.get(e.find(n=>Reflect.has(n,t))||{},t,r)},set({objects:e},t,r,n){let i;for(let s of e)if(i=kr(s,t),i)break;i||(i=e[e.length-1]);let o=Object.getOwnPropertyDescriptor(i,t);return o?.set&&o?.get?o.set.call(n,r)||!0:Reflect.set(i,t,r)}};function hi(){return Reflect.ownKeys(this).reduce((t,r)=>(t[r]=Reflect.get(this,r),t),{})}function pe(e,t=()=>{}){let r=i=>typeof i=="object"&&!Array.isArray(i)&&i!==null,n=(i,o="")=>{Object.entries(Object.getOwnPropertyLine truncated
${r?'Expression: "'+r+`"
`:""}`,t),setTimeout(()=>{throw e},0)}var he=!0;function We(e){let t=he;he=!1;let r=e();return he=t,r}function M(e,t,r={}){let n;return x(e,t)(i=>n=i,r),n}function x(...e){return Fr(...e)}var Fr=()=>{};function Vr(e){Fr=e}var $r;function Br(e){$r=e}function Hr(e,t){let r={};G(r,e);let n=[r,...U(e)],i=typeof t=="function"?xi(n,t):bi(n,t,e);return Ir.bind(null,e,t,i)}function xi(e,t){return(r=()=>{},{scope:n={},params:i=[],context:o}={})=>{if(!he){Se(r,t,L([n,...e]),i);return}let s=t.apply(L([n,...e]),i);Se(r,s)}}var kt={};function yi(e,t){if(kt[e])return kt[e];let r=Object.getPrototypeOf(async function(){}).constructor,n=/^[\n\s]*if.*\(.*\)/.test(e.trim())||/^(let|const)\s/.test(e.trim())?`(async()=>{ ${e} })()`:e,o=(()=>{try{let s=new r(["__self","scope"],`with (scope) { __self.result = ${n} }; __self.finished = true; return __self.result;`);return Object.defineProperty(s,"name",{value:`[Alpine] ${e}`}),s}catch(s){return Y(s,t,e),Promise.resolve()}})();return kt[e]=o,o}function bi(e,t,r){let n=yi(t,r);return(i=()=>{},{scope:o={},params:s=[],context:a}={})=>{n.result=void 0,n.finished=!1;let c=L([o,...e]);if(typeof n=="function"){let l=n.call(a,n,c).catch(f=>Y(f,r,t));n.finished?(Se(i,n.result,c,s,r),n.result=void 0):l.then(f=>{Se(i,f,c,s,r)}).catch(f=>Y(f,r,t)).finally(()=>n.result=void 0)}}}function Se(e,t,r,n,i){if(he&&typeof t=="function"){let o=t.apply(r,n);o instanceof Promise?o.then(s=>Se(e,s,r,n)).catch(s=>Y(s,i,t)):e(o)}else typeof t=="object"&&t instanceof Promise?t.then(o=>e(o)):e(t)}function Ur(...e){return $r(...e)}function qr(e,t,r={}){let n={};G(n,e);let i=[n,...U(e)],o=L([r.scope??{},...i]),s=r.params??[];if(t.includes("await")){let a=Object.getPrototypeOf(async function(){}).constructor,c=/^[\n\s]*if.*\(.*\)/.test(t.trim())||/^(let|const)\s/.test(t.trim())?`(async()=>{ ${t} })()`:t;return new a(["scope"],`with (scope) { let __result = ${c}; return __result }`).call(r.context,o)}else{let a=/^[\n\s]*if.*\(.*\)/.test(t.trim())||/^(let|const)\s/.test(t.trim())?`(()=>{ ${t} })()`:t,l=new Function(["scope"],`with (scope) { let __result = ${a}; return __result }`).call(r.context,o);return typeof l=="function"&&he?l.apply(o,s):l}}var Lt="x-";function N(e=""){return Lt+e}function zr(e){Lt=e}var Ge={};function p(e,t){return Ge[e]=t,{before(r){if(!Ge[r]){console.warn(String.raw`Cannot find directive \`${r}\`. \`${e}\` will use the default order of execution`);return}let n=Q.indexOf(r);Q.splice(n>=0?n:Q.indexOf("DEFAULT"),0,e)}}}function Kr(e){return Object.keys(Ge).includes(e)}function ee(e,t,r){if(t=Array.from(t),e._x_virtualDirectives){let o=Object.entries(e._x_virtualDirectives).map(([a,c])=>({name:a,value:c})),s=jt(o);o=o.map(a=>s.find(c=>c.name===a.name)?{name:`x-bind:${a.name}`,value:`"${a.value}"`}:a),t=t.concat(o)}let n={};return t.map(Yr((o,s)=>n[o]=s)).filter(Xr).map(vi(n,r)).sort(wi).map(o=>Ei(e,o))}function jt(e){return Array.from(e).map(Yr()).filter(t=>!Xr(t))}var Pt=!1,Ae=new Map,Wr=Symbol();function Gr(e){Pt=!0;let t=Symbol();Wr=t,Ae.set(t,[]);let r=()=>{for(;Ae.get(t).length;)Ae.get(t).shift()();Ae.delete(t)},n=()=>{Pt=!1,r()};e(r),n()}function Mt(e){let t=[],r=a=>t.push(a),[n,i]=wr(e);return t.push(i),[{Alpine:q,effect:n,cleanup:r,evaluateLater:x.bind(x,e),evaluate:M.bind(M,e)},()=>t.forEach(a=>a())]}function Ei(e,t){let r=()=>{},n=Ge[t.type]||r,[i,o]=Mt(e);He(e,t.original,o);let s=()=>{e._x_ignore||e._x_ignoreSelf||(n.inline&&n.inline(e,t,i),n=n.bind(n,e,t,i),Pt?Ae.get(Wr).push(n):n())};return s.runCleanups=o,s}var Ye=(e,t)=>({name:r,value:n})=>(r.startsWith(e)&&(r=r.replace(e,t)),{name:r,value:n}),Je=e=>e;function Yr(e=()=>{}){return({name:t,value:r})=>{let{name:n,value:i}=Jr.reduce((o,s)=>s(o),{name:t,value:r});return n!==t&&e(n,t),{name:n,value:i}}}var Jr=[];function me(e){Jr.push(e)}function Xr({name:e}){return Zr().test(e)}var Zr=()=>new RegExp(`^${Lt}([^:^.]+)\\b`);function vi(e,t){return({name:r,value:n})=>{r===n&&(n="");let i=r.match(Zr()),o=r.match(/:([a-zA-Z0-9\-_:]+)/),s=r.match(/\.[^.\]]+(?=[^\]]*$)/g)||[],a=t||e[r]||r;return{type:i?i[1]:null,value:o?o[1]:null,modifiers:s.map(c=>c.replace(".","")),expression:n,original:a}}}var It="DEFAULT",Q=["ignore","ref","id","data","anchor","bind","init","for","model","modelable","transition","show","if",It,"teleport"];function wi(e,t){let r=Q.indexOf(e.type)===-1?It:e.type,n=Q.indexOf(t.type)===-1?It:t.type;return Q.indexOf(r)-Q.indexOf(n)}function j(e,t){if(typeof ShadowRoot=="function"&&e instanceof ShadowRoot){Array.from(e.children).forEach(i=>j(i,t));return}let r=!1;if(t(e,()=>r=!0),r)return;let n=e.firstElementChild;for(;n;)j(n,t,!1),n=n.nextElementSibling}var C=!1;function w(e,t=()=>{}){return(...r)=>C?t(...r):e(...r)}function Qr(e){return(...t)=>C&&e(...t)}var en=[];function F(e){en.push(e)}function tn(e,t){en.forEach(r=>r(e,t)),C=!0,nn(()=>{S(t,(r,n)=>{n(r,()=>{})})}),C=!1}var Xe=!1;function rn(e,t){t._x_dataStack||(t._x_dataStack=e._x_dataStack),C=!0,Xe=!0,nn(()=>{Si(t)}),C=!1,Xe=!1}function Si(e){let t=!1;S(e,(n,i)=>{j(n,(oLine truncated
/*! Bundled license information:
@vue/shared/dist/shared.esm-bundler.js:
(**
* @vue/shared v3.5.41
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**)
@vue/reactivity/dist/reactivity.esm-bundler.js:
(**
* @vue/reactivity v3.5.41
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**)
*/
+21
View File
@@ -0,0 +1,21 @@
# MIT License
Copyright © 2019-2025 Caleb Porzio and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1
View File
@@ -0,0 +1 @@
!function(f){typeof module!='undefined'&&typeof exports=='object'?module.exports=f():typeof define!='undefined'&&define.amd?define(f):(typeof self!='undefined'?self:this).fflate=f()}(function(){var _e={};"use strict";var t=(typeof module!='undefined'&&typeof exports=='object'?function(_f){"use strict";var e,t=";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";try{e=require("worker_threads").Worker}catch(e){}exports.default=e?function(r,n,o,a,s){var u=!1,i=new e(r+t,{eval:!0}).on("error",(function(e){return s(e,null)})).on("message",(function(e){return s(null,e)})).on("exit",(function(e){e&&!u&&s(Error("exited with code "+e),null)}));return i.postMessage(o,a),i.terminate=function(){return u=!0,e.prototype.terminate.call(i)},i}:function(e,t,r,n,o){setImmediate((function(){return o(Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)}));var a=function(){};return{terminate:a,postMessage:a}};return _f}:function(_f){"use strict";var e={};_f.default=function(r,t,s,a,n){var o=new Worker(e[t]||(e[t]=URL.createObjectURL(new Blob([r+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return o.onmessage=function(e){var r=e.data,t=r.$e$;if(t){var s=Error(t[0]);s.code=t[1],s.stack=t[2],n(s,null)}else n(null,r)},o.postMessage(s,a),o};return _f})({}),n=Uint8Array,r=Uint16Array,e=Int32Array,i=new n([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),o=new n([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),s=new n([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,n){for(var i=new r(31),o=0;o<31;++o)i[o]=n+=1<<t[o-1];var s=new e(i[30]);for(o=1;o<30;++o)for(var a=i[o];a<i[o+1];++a)s[a]=a-i[o]<<5|o;return{b:i,r:s}},u=a(i,2),h=u.b,f=u.r;h[28]=258,f[258]=28;for(var l=a(o,0),c=l.b,p=l.r,v=new r(32768),d=0;d<32768;++d){var g=(43690&d)>>1|(21845&d)<<1;v[d]=((65280&(g=(61680&(g=(52428&g)>>2|(13107&g)<<2))>>4|(3855&g)<<4))>>8|(255&g)<<8)>>1}var y=function(t,n,e){for(var i=t.length,o=0,s=new r(n);o<i;++o)t[o]&&++s[t[o]-1];var a,u=new r(n);for(o=1;o<n;++o)u[o]=u[o-1]+s[o-1]<<1;if(e){a=new r(1<<n);var h=15-n;for(o=0;o<i;++o)if(t[o])for(var f=o<<4|t[o],l=n-t[o],c=u[t[o]-1]++<<l,p=c|(1<<l)-1;c<=p;++c)a[v[c]>>h]=f}else for(a=new r(i),o=0;o<i;++o)t[o]&&(a[o]=v[u[t[o]-1]++]>>15-t[o]);return a},m=new n(288);for(d=0;d<144;++d)m[d]=8;for(d=144;d<256;++d)m[d]=9;for(d=256;d<280;++d)m[d]=7;for(d=280;d<288;++d)m[d]=8;var b=new n(32);for(d=0;d<32;++d)b[d]=5;var w=y(m,9,0),x=y(m,9,1),z=y(b,5,0),k=y(b,5,1),M=function(t){for(var n=t[0],r=1;r<t.length;++r)t[r]>n&&(n=t[r]);return n},S=function(t,n,r){var e=n/8|0;return(t[e]|t[e+1]<<8)>>(7&n)&r},A=function(t,n){var r=n/8|0;return(t[r]|t[r+1]<<8|t[r+2]<<16)>>(7&n)},T=function(t){return(t+7)/8|0},D=function(t,r,e){return(null==r||r<0)&&(r=0),(null==e||e>t.length)&&(e=t.length),new n(t.subarray(r,e))};_e.FlateErrorCode={UnexpectedEOF:0,InvalidBlockType:1,InvalidLengthLiteral:2,InvalidDistance:3,StreamFinished:4,NoStreamHandler:5,InvalidHeader:6,NoCallback:7,InvalidUTF8:8,ExtraFieldTooLong:9,InvalidDate:10,FilenameTooLong:11,StreamFinishing:12,InvalidZipData:13,UnknownCompressionMethod:14};var C=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],I=function(t,n,r){var e=Error(n||C[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,I),!r)throw e;return e},U=function(t,r,e,a){var u=t.length,f=a?a.length:0;if(!u||r.f&&!r.l)return e||new n(0);var l=!e,p=l||2!=r.i,v=r.i;l&&(e=new n(3*u));var d=function(t){var r=e.length;if(t>r){var i=new n(Math.max(2*r,t));i.set(e),e=i}},g=r.f||0,m=r.p||0,b=r.b||0,w=r.l,z=r.d,C=r.m,U=r.n,F=8*u;do{if(!w){g=S(t,m,1);var E=S(t,m+1,3);if(m+=3,!E){var Z=t[(J=T(m)+4)-4]|t[J-3]<<8,q=J+Z;if(q>u){v&&I(0);break}p&&d(b+Z),e.set(t.subarray(J,q),b),r.b=b+=Z,r.p=m=8*q,r.f=g;continue}if(1==E)w=x,z=k,C=9,U=5;else if(2==E){var O=S(t,m,31)+257,G=S(t,m+10,15)+4,L=O+S(t,m+5,31)+1;m+=14;for(var H=new n(L),j=new n(19),N=0;N<G;++N)j[s[N]]=S(t,m+3*N,7);m+=3*G;var P=M(j),B=(1<<P)-1,Y=y(j,P,1);for(N=0;N<L;){var J,K=Y[S(t,m,B)];if(m+=15&K,(J=K>>4)<16)H[N++]=J;else{var Q=0,R=0;for(16==J?(R=3+S(t,m,3),m+=2,Q=H[N-1]):17==J?(R=3+S(t,m,7),m+=3):18==J&&(R=11+S(t,m,127),m+=7);R--;)H[N++]=Q}}var V=H.subarray(0,O),W=H.subarray(O);C=M(V),U=M(W),w=y(V,C,1),z=y(W,U,1)}else I(1);if(m>F){v&&I(0);break}}p&&d(b+131072);for(var X=(1<<C)-1,$=(1<<U)-1,_=m;;_=m){var tt=(Q=w[A(t,m)&X])>>4;if((m+=15&Q)>F){v&&I(0);break}if(Q||I(2),tt<256)e[b++]=tt;else{if(256==tt){_=m,w=null;break}var nt=tt-254;tt>264&&(nt=S(t,m,(1<<(it=i[N=tt-257]))-1)+h[N],m+=it);var rt=z[A(t,m)&$],et=rLine truncated
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff. Show more