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
132 changed files with 25253 additions and 5106 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.
+62
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,59 @@
- 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.
Generated
+2 -1
View File
@@ -2062,7 +2062,7 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "furumusic"
version = "0.16.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.16.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.
+14 -12
View File
@@ -127,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),
}
}
+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"]);
}
+291 -9
View File
@@ -1903,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>,
@@ -2360,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,
@@ -2371,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);
@@ -2400,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)
@@ -2411,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)
@@ -2422,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(
@@ -2433,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(
@@ -2446,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(
@@ -2457,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 {
@@ -2467,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)
}
@@ -4011,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,
@@ -4413,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
@@ -4857,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(())
}
+50
View File
@@ -702,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()
@@ -1325,6 +1330,51 @@ 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,
+208 -7
View File
@@ -292,6 +292,9 @@ translations! {
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" , "Управление офлайн-музыкой";
@@ -340,6 +343,27 @@ translations! {
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" , "Обложка альбома";
@@ -393,6 +417,7 @@ translations! {
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" , "Авто";
@@ -413,8 +438,18 @@ 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" , "Информация";
@@ -444,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";
@@ -489,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" , "Торренты";
@@ -505,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" , "Не добавлять в плейлист";
@@ -640,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" , "Развернуть всё";
@@ -654,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" , "вниз";
@@ -663,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" , "Не удалось загрузить историю";
@@ -697,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(())
}
+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.
+1
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)]
+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
+25
View File
@@ -9,6 +9,7 @@ mod import_playlists;
mod jobs;
mod lastfm;
mod library_cleanup;
mod library_import;
mod local_uploads;
mod lyrics;
mod media_paths;
@@ -69,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)
}
@@ -301,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/")) }),
@@ -320,6 +327,11 @@ impl App for FuruApp {
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({
@@ -588,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;
@@ -614,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),
+24
View File
@@ -3061,7 +3061,31 @@ pub mod db_migrations {
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,
+9
View File
@@ -43,6 +43,15 @@ 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());
+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(())
}
+193 -65
View File
@@ -28,14 +28,15 @@ use crate::youtube::{YouTubePreviewRequest, YouTubeService, YouTubeStartRequest}
#[cfg(test)]
mod artist_tests;
mod download_history;
mod dto;
mod helpers;
mod listening;
mod pins;
mod playlist_artwork;
mod playlist_image;
mod release_likes;
mod queries;
mod release_likes;
mod rows;
mod sharing;
@@ -2992,7 +2993,24 @@ async fn user_upload_review_save_handler(
};
let result_json = serde_json::to_string(&normalized)
.map_err(|e| cot::Error::internal(format!("failed to serialize review fields: {e}")))?;
save_user_upload_review_result(&db, review_id, result_json).await?;
let owner_pattern = format!(r#""uploaded_by_user_id"\s*:\s*{}([^0-9]|$)"#, user.id);
let updated = sqlx::query(
"UPDATE furumusic__pending_review SET result_json=$3, updated_at=$4
WHERE id=$1 AND context_json ~ $2 AND status IN ('pending','failed')",
)
.bind(review_id)
.bind(owner_pattern)
.bind(result_json)
.bind(now_iso_string())
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
if updated.rows_affected() == 0 {
return Ok(json_error(
StatusCode::CONFLICT,
"review is no longer editable",
));
}
let mut reviews = load_user_upload_reviews(pool, user.id, Some(review_id), 1)
.await?
.0;
@@ -3013,20 +3031,10 @@ async fn user_upload_review_delete_handler(
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let review_id = path.0.id;
let uploaded_by_pattern = format!(r#""uploaded_by_user_id"\s*:\s*{}([^0-9]|$)"#, user.id);
let result = sqlx::query(
r#"DELETE FROM furumusic__pending_review
WHERE id = $1
AND context_json IS NOT NULL
AND context_json ~ $2
AND status IN ('pending', 'failed')"#,
)
.bind(review_id)
.bind(uploaded_by_pattern)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
if result.rows_affected() == 0 {
let affected = crate::scheduler::PendingReview::dismiss(pool, &[review_id], Some(user.id))
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
if affected == 0 {
return Ok(json_error(StatusCode::NOT_FOUND, "upload review not found"));
}
let page = load_user_uploads_page(pool, user.id, 500).await?;
@@ -3058,46 +3066,44 @@ async fn user_upload_review_approve_handler(
.await
.map_err(|e| cot::Error::internal(format!("db error: {e}")))?
.ok_or_else(|| cot::Error::internal("upload review not found"))?;
let status = review.status.as_str();
if status == "processing" || status == "approved" || status == "auto_approved" {
if !review
.claim_for_processing(pool, Some(result_json))
.await
.map_err(|e| cot::Error::internal(format!("db error: {e}")))?
{
return Ok(json_error(
StatusCode::BAD_REQUEST,
"review cannot be approved from this status",
));
}
review
.set_result_json(&db, result_json)
.await
.map_err(|e| cot::Error::internal(format!("db error: {e}")))?;
let context: serde_json::Value =
serde_json::from_str(review.context_json_str()).unwrap_or_default();
let (live_config, _) = AppConfig::load_with_db(&db).await;
let input_path = crate::media_paths::resolve_path_from_root(
&live_config.agent_inbox_dir,
review.input_path_str(),
);
let input_path = input_path.to_string_lossy().to_string();
match crate::jobs::inbox_process::finalize_approved(
&db,
pool,
&live_config,
&input_path,
review.input_path_str(),
&normalized,
&context,
&live_config.agent_storage_dir,
None,
crate::jobs::inbox_process::ReviewApproval::Check(None),
)
.await
{
Ok(()) => {
let _ = review.set_approved(&db).await;
review
.set_approved(&db)
.await
.map_err(|e| cot::Error::internal(format!("db error: {e}")))?;
let page = load_user_uploads_page(pool, user.id, 500).await?;
Json(page).into_response()
}
Err(err) => {
let message = err.to_string();
let _ = review.set_failed(&db, &message).await;
review
.set_approval_error(&db, &err)
.await
.map_err(|e| cot::Error::internal(format!("db error: {e}")))?;
Ok(json_error(StatusCode::BAD_REQUEST, &message))
}
}
@@ -3500,22 +3506,6 @@ async fn uploaded_track_release_ids(
Ok(rows)
}
async fn save_user_upload_review_result(
db: &Database,
review_id: i64,
result_json: String,
) -> cot::Result<()> {
let mut review = crate::scheduler::PendingReview::get_by_id(db, review_id)
.await
.map_err(|e| cot::Error::internal(format!("db error: {e}")))?
.ok_or_else(|| cot::Error::internal("upload review not found"))?;
review
.set_result_json(db, result_json)
.await
.map_err(|e| cot::Error::internal(format!("db error: {e}")))?;
Ok(())
}
async fn replace_release_artists(
pool: &sqlx::PgPool,
release_id: i64,
@@ -7302,6 +7292,85 @@ async fn content_playlist_add_handler(
Json(serde_json::json!({ "ok": true })).into_response()
}
/// Result of removing a federated track from a playlist.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ContentRemoval {
Removed,
NotOwned,
InvalidContentId,
}
/// Removes a track identified by its content id from the user's own playlist
/// with the existing `PlaylistTrackRemoved` operation: the register becomes
/// `present = false` and a materialized row, if any, is deleted. Federated
/// tracks have no `playlist_track` row, so this is how the web removes them.
pub(crate) async fn remove_content_from_playlist(
pool: &sqlx::PgPool,
user_id: i64,
playlist_id: i64,
content_id: &str,
) -> anyhow::Result<ContentRemoval> {
let Some(content_id) = music_dht::normalize_content_id(content_id) else {
return Ok(ContentRemoval::InvalidContentId);
};
let owns: bool = sqlx::query_scalar(
"SELECT EXISTS (
SELECT 1 FROM furumusic__playlist WHERE id = $1 AND owner_id = $2
)",
)
.bind(playlist_id)
.bind(user_id)
.fetch_one(pool)
.await?;
if !owns {
return Ok(ContentRemoval::NotOwned);
}
crate::federation::devices::record_playlist_tracks_removed(
pool,
user_id,
playlist_id,
&[content_id],
)
.await?;
Ok(ContentRemoval::Removed)
}
// ---------------------------------------------------------------------------
// DELETE /api/player/tracks/content/playlist — remove a federated track
// ---------------------------------------------------------------------------
async fn content_playlist_remove_handler(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: &sqlx::PgPool,
Json(body): Json<ContentTrackMutation>,
) -> 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 Some(playlist_id) = body.playlist_id else {
return Ok(json_error(StatusCode::BAD_REQUEST, "missing playlist id"));
};
match remove_content_from_playlist(pool, user.id, playlist_id, &body.content_id).await {
Ok(ContentRemoval::Removed) => Json(serde_json::json!({ "ok": true })).into_response(),
Ok(ContentRemoval::NotOwned) => Ok(json_error(StatusCode::FORBIDDEN, "not your playlist")),
Ok(ContentRemoval::InvalidContentId) => {
Ok(json_error(StatusCode::BAD_REQUEST, "invalid content id"))
}
Err(err) => {
tracing::warn!(
playlist_id,
"fed device playlist remove op was not recorded: {err:#}"
);
Ok(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
"could not remove the track",
))
}
}
}
async fn federation_playlist_tracks_handler(
auth_ctx: auth::AuthContext,
session: Session,
@@ -7521,6 +7590,40 @@ async fn federation_artwork_discovery_handler(
// POST /api/player/playlists — create playlist
// ---------------------------------------------------------------------------
/// Inserts a private playlist owned by `user_id` in the caller's transaction.
/// Recording its Device Sync operation is up to the caller.
pub(crate) async fn create_owned_playlist_tx(
conn: &mut sqlx::PgConnection,
user_id: i64,
title: &str,
description: Option<&str>,
) -> sqlx::Result<i64> {
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
sqlx::query_scalar(
"INSERT INTO furumusic__playlist (owner_id, title, description, is_public, created_at, updated_at) \
VALUES ($1, $2, $3, false, $4, $4) RETURNING id",
)
.bind(user_id)
.bind(title)
.bind(description)
.bind(&now)
.fetch_one(conn)
.await
}
/// [`create_owned_playlist_tx`] in a transaction of its own.
pub(crate) async fn create_owned_playlist(
pool: &sqlx::PgPool,
user_id: i64,
title: &str,
description: Option<&str>,
) -> sqlx::Result<i64> {
let mut tx = pool.begin().await?;
let playlist_id = create_owned_playlist_tx(&mut tx, user_id, title, description).await?;
tx.commit().await?;
Ok(playlist_id)
}
async fn create_playlist_handler(
auth_ctx: auth::AuthContext,
session: Session,
@@ -7535,22 +7638,14 @@ async fn create_playlist_handler(
if title.is_empty() {
return Ok(json_error(StatusCode::BAD_REQUEST, "title is required"));
}
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
let row: (i64,) = sqlx::query_as(
"INSERT INTO furumusic__playlist (owner_id, title, is_public, created_at, updated_at) \
VALUES ($1, $2, false, $3, $3) RETURNING id",
)
.bind(user.id)
.bind(&title)
.bind(&now)
.fetch_one(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let playlist_id = create_owned_playlist(pool, user.id, &title, None)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
record_fed_playlist_created(pool, user.id, row.0, &title).await;
record_fed_playlist_created(pool, user.id, playlist_id, &title).await;
Json(PlaylistCard {
id: row.0,
id: playlist_id,
cover_url: None,
cover_urls: Vec::new(),
title,
@@ -8151,8 +8246,17 @@ impl App for PlayerApp {
let youtube_service: Arc<tokio::sync::OnceCell<Arc<YouTubeService>>> =
Arc::new(tokio::sync::OnceCell::new());
let device_hub = Arc::clone(&self.device_hub);
let [history, hide_history] = download_history::Services {
pool: pool.clone(),
config: pool_config.clone(),
torrents: torrent_service.clone(),
youtube: youtube_service.clone(),
scheduler: self.scheduler_handle.clone(),
}
.routes();
Router::with_urls([
history, hide_history,
pins::route(pool.clone(), pool_config.clone()),
playlist_artwork::route(pool.clone(), pool_config.clone()),
// -- Current user profile --
@@ -8501,7 +8605,7 @@ impl App for PlayerApp {
.list(
pg_pool,
user.id,
&live_config.agent_inbox_dir,
&live_config,
proxy_url,
cookie_contents,
)
@@ -8574,7 +8678,7 @@ impl App for PlayerApp {
pg_pool,
user.id,
json.0,
&live_config.agent_inbox_dir,
&live_config,
proxy_url,
cookie_contents,
)
@@ -8647,7 +8751,7 @@ impl App for PlayerApp {
pg_pool,
user.id,
&path.0.id,
&live_config.agent_inbox_dir,
&live_config,
proxy_url,
cookie_contents,
)
@@ -10671,6 +10775,30 @@ impl App for PlayerApp {
content_playlist_add_handler(auth_ctx, session, db, pg_pool, json).await
}
}
})
.delete({
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
move |auth_ctx: auth::AuthContext,
session: Session,
db: Database,
json: Json<ContentTrackMutation>| {
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
async move {
let pg_pool = pool
.get_or_init(|| async {
sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&pool_config.database_url)
.await
.expect("player pool")
})
.await;
content_playlist_remove_handler(auth_ctx, session, db, pg_pool, json)
.await
}
}
}),
"player_content_playlist",
),
+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!(
+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
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Arjun Barrett
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.
+36
View File
@@ -0,0 +1,36 @@
WITH selected AS MATERIALIZED (
SELECT id, input_path,
lower(substring(context_json from '"sha256"[[:space:]]*:[[:space:]]*"([0-9A-Fa-f]{64})"')) AS sha256
FROM furumusic__pending_review
WHERE id = ANY($1) AND status <> 'processing'
AND ($2::text IS NULL OR (status IN ('pending','failed') AND context_json ~ $2))
FOR UPDATE
), eligible AS (
-- Older unfinished reviews without a hash stay visible until discovery
-- identifies their bytes. A later upload must not inherit the dismissal.
SELECT * FROM selected WHERE input_path IS NULL OR input_path = '' OR sha256 IS NOT NULL
), targets AS (
SELECT id FROM eligible
UNION
-- Older scanners could enqueue the very same upload more than once.
-- Include only unfinished copies belonging to that exact path and hash.
SELECT r.id FROM furumusic__pending_review r
JOIN eligible e ON r.input_path=e.input_path
AND lower(substring(r.context_json from '"sha256"[[:space:]]*:[[:space:]]*"([0-9A-Fa-f]{64})"'))=e.sha256
WHERE r.status IN ('queued','pending','failed','rejected') AND ($2 IS NULL OR r.context_json ~ $2)
), removed AS (
DELETE FROM furumusic__pending_review r USING targets t
WHERE r.id=t.id AND r.status <> 'processing'
AND (r.id IN (SELECT id FROM eligible) OR r.status IN ('queued','pending','failed','rejected'))
RETURNING r.id, r.input_path, r.status,
lower(substring(r.context_json from '"sha256"[[:space:]]*:[[:space:]]*"([0-9A-Fa-f]{64})"')) AS sha256
), recorded AS (
INSERT INTO furumusic__dismissed_review(input_path, sha256, review_id, imported)
SELECT DISTINCT ON (input_path, sha256) input_path, sha256, id, status IN ('approved','auto_approved')
FROM removed WHERE input_path IS NOT NULL AND input_path <> '' AND sha256 IS NOT NULL
ORDER BY input_path, sha256, id DESC
ON CONFLICT (input_path, sha256) DO UPDATE
SET review_id = EXCLUDED.review_id, imported = EXCLUDED.imported
WHERE EXCLUDED.review_id > furumusic__dismissed_review.review_id
)
SELECT count(*) FROM removed WHERE id = ANY($1)
+190 -45
View File
@@ -387,30 +387,6 @@ impl PendingReview {
Ok(review)
}
pub async fn create_queued(
db: &Database,
job_run_id: i64,
review_type: &str,
input_path: Option<&str>,
context_json: Option<&str>,
) -> cot::db::Result<Self> {
let now = now_iso();
let mut review = Self {
id: Auto::auto(),
job_run_id,
review_type: LimitedString::new(review_type).unwrap(),
input_path: input_path.map(|s| s.to_owned()),
context_json: context_json.map(|s| s.to_owned()),
result_json: None,
status: LimitedString::new("queued").unwrap(),
created_at: now.clone(),
updated_at: now,
error_message: None,
};
review.insert(db).await?;
Ok(review)
}
pub async fn list_all(db: &Database) -> cot::db::Result<Vec<Self>> {
Self::objects().all(db).await
}
@@ -445,10 +421,39 @@ impl PendingReview {
self.save(db).await
}
pub async fn set_processing(&mut self, db: &Database) -> cot::db::Result<()> {
/// Claim the version of the review the caller read, optionally applying
/// edited metadata in the same update as the transition to processing.
pub async fn claim_for_processing(
&mut self,
pool: &sqlx::PgPool,
edited_result: Option<String>,
) -> sqlx::Result<bool> {
if matches!(
self.status_str(),
"processing" | "approved" | "auto_approved"
) {
return Ok(false);
}
let now = now_iso();
let result: Option<Option<String>> = sqlx::query_scalar(
"UPDATE furumusic__pending_review SET status = 'processing', updated_at = $2, \
error_message = NULL, result_json = COALESCE($3, result_json) \
WHERE id = $1 AND status = $4 RETURNING result_json",
)
.bind(self.id_val())
.bind(now.as_str())
.bind(edited_result)
.bind(self.status_str())
.fetch_optional(pool)
.await?;
let Some(result_json) = result else {
return Ok(false);
};
self.status = LimitedString::new("processing").unwrap();
self.updated_at = now_iso();
self.save(db).await
self.updated_at = now;
self.error_message = None;
self.result_json = result_json;
Ok(true)
}
pub async fn set_auto_approved(&mut self, db: &Database) -> cot::db::Result<()> {
@@ -474,6 +479,21 @@ impl PendingReview {
self.save(db).await
}
pub async fn set_approval_error(
&mut self,
db: &Database,
error: &anyhow::Error,
) -> cot::db::Result<()> {
if let Some(conflict) = error.downcast_ref::<crate::agent::dedup::DuplicateReview>() {
self.status = LimitedString::new("pending").unwrap();
self.error_message = Some(conflict.to_string());
self.updated_at = now_iso();
self.save(db).await
} else {
self.set_failed(db, &format!("{error:#}")).await
}
}
pub async fn list_queued(db: &Database) -> cot::db::Result<Vec<Self>> {
let status_val: LimitedString<32> = LimitedString::new("queued").unwrap();
cot::db::query!(PendingReview, $status == status_val)
@@ -555,26 +575,113 @@ impl PendingReview {
Ok(())
}
pub async fn requeue_by_ids(db: &Database, ids: &[i64]) -> cot::db::Result<()> {
let now = now_iso().to_string();
for chunk in ids.chunks(1000) {
if chunk.is_empty() {
continue;
}
let id_list = chunk
.iter()
.map(i64::to_string)
.collect::<Vec<_>>()
.join(",");
db.raw(&format!(
"UPDATE furumusic__pending_review \
SET status = 'queued', error_message = NULL, updated_at = '{}' \
WHERE id IN ({id_list})",
now.replace('\'', "''")
))
pub async fn requeue(pool: &sqlx::PgPool, ids: &[i64]) -> sqlx::Result<u64> {
let result = sqlx::query(
"UPDATE furumusic__pending_review SET status='queued', error_message=NULL, updated_at=$2 \
WHERE id=ANY($1) AND status IN ('failed','rejected','pending') \
AND COALESCE(error_message,'') NOT LIKE '%Duplicate check needs review:%'",
)
.bind(ids)
.bind(now_iso().as_str())
.execute(pool)
.await?;
Ok(result.rows_affected())
}
pub async fn is_dismissed<'e>(
executor: impl sqlx::PgExecutor<'e>,
input_path: &str,
sha256: &str,
) -> sqlx::Result<bool> {
sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM furumusic__dismissed_review \
WHERE input_path=$1 AND sha256=lower($2))",
)
.bind(input_path)
.bind(sha256)
.fetch_one(executor)
.await
}
// Discovery does file I/O before calling this. Only serialize its final
// database decision with other discoverers and explicit dismissals.
async fn discovery_transaction(
pool: &sqlx::PgPool,
) -> sqlx::Result<sqlx::Transaction<'_, sqlx::Postgres>> {
let mut transaction = pool.begin().await?;
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended('furumi-inbox-discovery',0))")
.execute(&mut *transaction)
.await?;
Ok(transaction)
}
pub async fn enqueue_discovered(
pool: &sqlx::PgPool,
run_id: i64,
input_path: &str,
sha256: &str,
context_json: &str,
) -> sqlx::Result<bool> {
let mut transaction = Self::discovery_transaction(pool).await?;
if Self::is_dismissed(&mut *transaction, input_path, sha256).await? {
return Ok(false);
}
Ok(())
let current: Option<(i64, String, Option<String>)> = sqlx::query_as(
"SELECT id, status::text, context_json FROM furumusic__pending_review \
WHERE input_path=$1 ORDER BY id DESC LIMIT 1 FOR UPDATE",
)
.bind(input_path)
.fetch_optional(&mut *transaction)
.await?;
let now = now_iso();
if let Some((id, status, context)) = current
&& !matches!(status.as_str(), "approved" | "auto_approved")
{
let recorded =
context.and_then(|json| serde_json::from_str::<serde_json::Value>(&json).ok());
let previous_sha = recorded.as_ref().and_then(|json| json["sha256"].as_str());
if status == "processing"
|| previous_sha.is_some_and(|previous| previous.eq_ignore_ascii_case(sha256))
{
return Ok(false);
}
// A replacement needs its own identity: a stale admin dialog for
// the old bytes must not approve or dismiss the new upload.
sqlx::query("DELETE FROM furumusic__pending_review WHERE id=$1")
.bind(id)
.execute(&mut *transaction)
.await?;
}
sqlx::query(
"INSERT INTO furumusic__pending_review \
(job_run_id,review_type,input_path,context_json,status,created_at,updated_at) \
VALUES ($1,'new_file',$2,$3,'queued',$4,$4)",
)
.bind(run_id)
.bind(input_path)
.bind(context_json)
.bind(now.as_str())
.execute(&mut *transaction)
.await?;
transaction.commit().await?;
Ok(true)
}
pub async fn dismiss(
pool: &sqlx::PgPool,
ids: &[i64],
owner: Option<i64>,
) -> sqlx::Result<u64> {
let mut transaction = Self::discovery_transaction(pool).await?;
let owner_pattern =
owner.map(|id| format!(r#""uploaded_by_user_id"\s*:\s*{id}([^0-9]|$)"#));
let affected: i64 = sqlx::query_scalar(include_str!("dismiss_reviews.sql"))
.bind(ids)
.bind(owner_pattern)
.fetch_one(&mut *transaction)
.await?;
transaction.commit().await?;
Ok(affected as u64)
}
pub fn id_val(&self) -> i64 {
@@ -933,6 +1040,43 @@ pub mod db_migrations {
.build()];
}
#[cot::db::migrations::migration_op]
async fn create_review_dismissals(
ctx: migrations::MigrationContext<'_>,
) -> cot::db::Result<()> {
for statement in include_str!("review_dismissal_schema.sql").split(';') {
if !statement.trim().is_empty() {
ctx.db.raw(statement).await?;
}
}
// Older instances may have marked an archived upload complete after
// its inbox file was removed. Restore its recorded dismissal.
ctx.db
.raw(
"UPDATE furumusic__local_upload u SET status='cancelled', error=NULL, \
updated_at=to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'), \
completed_at=COALESCE(u.completed_at, u.updated_at) \
FROM furumusic__upload_review_state r WHERE r.input_path=u.inbox_path \
AND r.status='cancelled' AND u.status <> 'cancelled'",
)
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0064ReviewDismissals;
impl migrations::Migration for M0064ReviewDismissals {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0064_review_dismissals";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0063_download_history",
)];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(create_review_dismissals).build()];
}
pub const MIGRATIONS: &[&SyncDynMigration] = &[
&M0022CreateScheduledJob,
&M0023CreateJobRun,
@@ -940,6 +1084,7 @@ pub mod db_migrations {
&M0025CreateSchedulerIndexes,
&M0026AddPendingReviewErrorMessage,
&M0027CreateProcessingStats,
&M0064ReviewDismissals,
];
}
+18
View File
@@ -0,0 +1,18 @@
CREATE TABLE IF NOT EXISTS furumusic__dismissed_review (
input_path text NOT NULL,
sha256 text NOT NULL,
review_id bigint NOT NULL,
imported boolean NOT NULL,
PRIMARY KEY (input_path, sha256)
);
CREATE INDEX idx_pending_review_input_path ON furumusic__pending_review(input_path, id DESC);
-- Transfer history follows the latest decision for each file, including dismissed reviews.
CREATE VIEW furumusic__upload_review_state AS
SELECT DISTINCT ON (input_path) input_path, status, error_message
FROM (
SELECT id, input_path, status::text, error_message FROM furumusic__pending_review
UNION ALL
SELECT review_id, input_path, CASE WHEN imported THEN 'approved' ELSE 'cancelled' END, NULL::text
FROM furumusic__dismissed_review
) AS decisions
ORDER BY input_path, id DESC;
+39 -16
View File
@@ -456,21 +456,7 @@ impl TorrentService {
.collect::<HashMap<_, _>>()
};
for row in rows.iter().filter(|row| row.status == "resolving") {
if row.source_kind == "magnet" {
if let Some(magnet) = row.source_label.clone() {
self.spawn_resolve_pending_magnet(
pool.clone(),
user_id,
row.id.clone(),
magnet,
row.created_at.clone(),
proxy_url.clone(),
)
.await;
}
}
}
self.resume_pending(pool, user_id, proxy_url).await?;
Ok(rows
.iter()
@@ -478,6 +464,42 @@ impl TorrentService {
.collect())
}
pub(crate) async fn resume_pending(
self: &Arc<Self>,
pool: &PgPool,
user_id: i64,
proxy: Option<String>,
) -> anyhow::Result<()> {
let pending: Vec<(String, String, String)> = sqlx::query_as(
"SELECT id, source_label, created_at FROM furumusic__torrent_session
WHERE user_id=$1 AND status='resolving' AND source_kind='magnet' AND source_label IS NOT NULL"
).bind(user_id).fetch_all(pool).await?;
for (id, magnet, created_at) in pending {
self.spawn_resolve_pending_magnet(
pool.clone(),
user_id,
id,
magnet,
created_at,
proxy.clone(),
)
.await;
}
Ok(())
}
/// Download percentages change in memory between persisted state transitions.
pub(crate) async fn live_progress(&self, user_id: i64, id: &str) -> Option<f64> {
let jobs = self.jobs.lock().await;
let job = jobs.get(id).filter(|job| job.user_id == user_id)?;
let stats = job.handle.as_ref()?.stats();
Some(
progress_percent(stats.progress_bytes, stats.total_bytes)
.unwrap_or(job.progress_percent)
.clamp(0.0, 100.0),
)
}
pub async fn details(
&self,
pool: &PgPool,
@@ -1279,6 +1301,7 @@ async fn mark_job_started(
sqlx::query(
r#"UPDATE furumusic__torrent_session
SET selected_files_json = $2,
history_processed = false,
status = 'downloading',
selected_size = $3,
downloaded_bytes = 0,
@@ -1499,7 +1522,7 @@ mod playlist_tests {
id text PRIMARY KEY,user_id bigint,name text,info_hash text,source_kind text,source_label text,torrent_bytes bytea,
files_json text,selected_files_json text,status text,total_size bigint DEFAULT 0,selected_size bigint DEFAULT 0,
downloaded_bytes bigint DEFAULT 0,uploaded_bytes bigint DEFAULT 0,progress_percent float8 DEFAULT 0,
error text,created_at text,updated_at text,completed_at text,target_playlist_id bigint);
error text,created_at text,updated_at text,completed_at text,target_playlist_id bigint,history_processed boolean DEFAULT false);
"#).execute(&pool).await.unwrap();
let root = std::env::temp_dir().join(format!("furumi-torrent-test-{}", Uuid::new_v4()));
let mut service = TorrentService::new(Arc::new(OnceCell::new()));
+180 -70
View File
@@ -18,6 +18,7 @@ use tokio::sync::{Mutex, OnceCell, Semaphore};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use crate::config::AppConfig;
use crate::scheduler::SchedulerHandle;
const YOUTUBE_LIST_LIMIT: i64 = 100;
@@ -546,12 +547,12 @@ impl YouTubeService {
pool: &PgPool,
user_id: i64,
request: YouTubeStartRequest,
inbox_dir: &str,
config: &AppConfig,
proxy_url: Option<String>,
cookie_contents: Option<String>,
) -> anyhow::Result<YouTubeJobDto> {
let url = validate_youtube_url(&request.url)?;
validate_inbox_dir(inbox_dir)?;
validate_inbox_dir(&config.agent_inbox_dir)?;
let selected: HashSet<String> = request
.selected_source_ids
.into_iter()
@@ -666,14 +667,8 @@ impl YouTubeService {
);
}
self.spawn_job(
pool.clone(),
id.clone(),
inbox_dir.to_string(),
proxy_url,
cookie_contents,
)
.await;
self.spawn_job(pool.clone(), id.clone(), config, proxy_url, cookie_contents)
.await;
load_job_dto(pool, user_id, &id).await
}
@@ -681,34 +676,18 @@ impl YouTubeService {
self: &Arc<Self>,
pool: &PgPool,
user_id: i64,
inbox_dir: &str,
config: &AppConfig,
proxy_url: Option<String>,
cookie_contents: Option<String>,
) -> anyhow::Result<Vec<YouTubeJobDto>> {
validate_inbox_dir(inbox_dir)?;
sync_ai_statuses(pool, user_id).await?;
let resumable: Vec<(String, String)> = sqlx::query_as(
r#"SELECT id, status::text
FROM furumusic__youtube_download
WHERE user_id = $1
AND status IN ('queued', 'resolving', 'downloading', 'postprocessing')
ORDER BY created_at"#,
)
.bind(user_id)
.fetch_all(pool)
.await?;
for (id, _) in resumable {
self.spawn_job(
pool.clone(),
id,
inbox_dir.to_string(),
proxy_url.clone(),
cookie_contents.clone(),
)
.await;
validate_inbox_dir(&config.agent_inbox_dir)?;
sync_ai_statuses(pool, user_id, None).await?;
if let Err(error) = sync_target_playlist_tracks_for_user(pool, user_id).await {
tracing::warn!(user_id, %error, "could not synchronize imported YouTube tracks with their target playlists");
}
let pending = self.pending_jobs(pool, user_id).await?;
self.resume_jobs(pool, pending, config, proxy_url, cookie_contents)
.await;
let ids: Vec<String> = sqlx::query_scalar(
r#"SELECT id FROM furumusic__youtube_download
WHERE user_id = $1 ORDER BY created_at DESC, id DESC LIMIT $2"#,
@@ -717,27 +696,64 @@ impl YouTubeService {
.bind(YOUTUBE_LIST_LIMIT)
.fetch_all(pool)
.await?;
for id in &ids {
refresh_parent(pool, id).await?;
}
let mut jobs = Vec::with_capacity(ids.len());
for id in ids {
refresh_parent(pool, &id).await?;
jobs.push(load_job_dto(pool, user_id, &id).await?);
}
Ok(jobs)
}
pub(crate) async fn pending_jobs(
&self,
pool: &PgPool,
user_id: i64,
) -> anyhow::Result<Vec<String>> {
let mut resumable: Vec<String> = sqlx::query_scalar(
r#"SELECT id
FROM furumusic__youtube_download
WHERE user_id = $1
AND status IN ('queued', 'resolving', 'downloading', 'postprocessing')
ORDER BY created_at"#,
)
.bind(user_id)
.fetch_all(pool)
.await?;
let running = self.running_jobs.lock().await;
resumable.retain(|id| !running.contains(id));
Ok(resumable)
}
pub(crate) async fn resume_jobs(
self: &Arc<Self>,
pool: &PgPool,
resumable: Vec<String>,
config: &AppConfig,
proxy_url: Option<String>,
cookie_contents: Option<String>,
) {
for id in resumable {
self.spawn_job(
pool.clone(),
id,
config,
proxy_url.clone(),
cookie_contents.clone(),
)
.await;
}
}
pub async fn retry(
self: &Arc<Self>,
pool: &PgPool,
user_id: i64,
id: &str,
inbox_dir: &str,
config: &AppConfig,
proxy_url: Option<String>,
cookie_contents: Option<String>,
) -> anyhow::Result<YouTubeJobDto> {
validate_inbox_dir(inbox_dir)?;
validate_inbox_dir(&config.agent_inbox_dir)?;
let job = load_job_row(pool, user_id, id).await?;
if is_active_job_status(&job.status) {
bail!("YouTube download is already active");
@@ -769,7 +785,7 @@ impl YouTubeService {
self.spawn_job(
pool.clone(),
id.to_string(),
inbox_dir.to_string(),
config,
proxy_url,
cookie_contents,
)
@@ -860,7 +876,7 @@ impl YouTubeService {
self: &Arc<Self>,
pool: PgPool,
id: String,
inbox_dir: String,
config: &AppConfig,
proxy_url: Option<String>,
cookie_contents: Option<String>,
) {
@@ -877,6 +893,7 @@ impl YouTubeService {
.insert(id.clone(), cancel.clone());
let service = Arc::clone(self);
let config = config.clone();
tokio::spawn(async move {
let permit = tokio::select! {
permit = Arc::clone(&service.concurrency).acquire_owned() => permit.ok(),
@@ -887,7 +904,7 @@ impl YouTubeService {
.run_job(
&pool,
&id,
&inbox_dir,
&config,
proxy_url.as_deref(),
cookie_contents.as_deref(),
&cancel,
@@ -905,7 +922,7 @@ impl YouTubeService {
let _ = fail_parent(&pool, &id, &err.to_string()).await;
}
if cancel.is_cancelled()
&& let Ok(inbox_root) = validate_inbox_dir(&inbox_dir)
&& let Ok(inbox_root) = validate_inbox_dir(&config.agent_inbox_dir)
{
let _ = tokio::fs::remove_dir_all(staging_job_root(&inbox_root, &id)).await;
}
@@ -918,7 +935,7 @@ impl YouTubeService {
&self,
pool: &PgPool,
id: &str,
inbox_dir: &str,
config: &AppConfig,
proxy_url: Option<&str>,
cookie_contents: Option<&str>,
cancel: &CancellationToken,
@@ -930,7 +947,7 @@ impl YouTubeService {
if cancel.is_cancelled() {
return Ok(());
}
let inbox_root = validate_inbox_dir(inbox_dir)?;
let inbox_root = validate_inbox_dir(&config.agent_inbox_dir)?;
let job: YouTubeJobRow = sqlx::query_as(
r#"SELECT id, user_id, source_url, title, source_kind,
target_playlist_id, status,
@@ -1016,7 +1033,7 @@ impl YouTubeService {
continue;
}
if let Err(err) = self
.process_item(pool, &job, &item, &inbox_root, ytdlp, cancel)
.process_item(pool, &job, &item, config, ytdlp, cancel)
.await
{
if cancel.is_cancelled() {
@@ -1045,7 +1062,7 @@ impl YouTubeService {
pool: &PgPool,
job: &YouTubeJobRow,
item: &YouTubeItemRow,
inbox_root: &Path,
config: &AppConfig,
ytdlp: YtDlpOptions<'_>,
cancel: &CancellationToken,
) -> anyhow::Result<()> {
@@ -1055,7 +1072,8 @@ impl YouTubeService {
set_item_status(pool, &item.id, "downloading", None).await?;
set_parent_status(pool, &job.id, "downloading", None).await?;
let stage = staging_item_root(inbox_root, &job.id, &item.id);
let inbox_root = validate_inbox_dir(&config.agent_inbox_dir)?;
let stage = staging_item_root(&inbox_root, &job.id, &item.id);
tokio::fs::create_dir_all(&stage).await?;
let mut forbidden_retries = 0;
loop {
@@ -1108,7 +1126,7 @@ impl YouTubeService {
set_item_status(pool, &item.id, "postprocessing", None).await?;
set_parent_status(pool, &job.id, "postprocessing", None).await?;
let prepared =
prepare_downloaded_folder(pool, inbox_root, job.user_id, item, &stage, cancel).await?;
prepare_downloaded_folder(pool, config, job.user_id, item, &stage, cancel).await?;
let now = now_string();
if prepared.all_files_known {
@@ -1515,7 +1533,7 @@ async fn persist_item_progress(
async fn prepare_downloaded_folder(
pool: &PgPool,
inbox_root: &Path,
config: &AppConfig,
user_id: i64,
item: &YouTubeItemRow,
stage: &Path,
@@ -1571,13 +1589,7 @@ async fn prepare_downloaded_folder(
preserve_track_numbers(&mut audio_files, chapter_count, item.playlist_index, cancel).await?;
for audio in &audio_files {
let hash = sha256_file(audio, cancel).await?;
if crate::agent::rag::file_hash_exists(pool, &hash)
.await
.unwrap_or(false)
{
tokio::fs::remove_file(audio).await?;
}
reuse_archived_audio(pool, config, &item.id, audio, cancel).await?;
}
audio_files = find_audio_files(stage).await?;
if audio_files.is_empty() {
@@ -1594,6 +1606,7 @@ async fn prepare_downloaded_folder(
bail!("YouTube import cancelled");
}
let folder_name = format!("{} [{}]", sanitize_component(&item.title), item.source_id);
let inbox_root = validate_inbox_dir(&config.agent_inbox_dir)?;
let destination = inbox_root
.join("user_uploads")
.join(user_id.to_string())
@@ -1630,6 +1643,33 @@ async fn prepare_downloaded_folder(
})
}
async fn reuse_archived_audio(
pool: &PgPool,
config: &AppConfig,
item_id: &str,
audio: &Path,
cancel: &CancellationToken,
) -> anyhow::Result<()> {
let hash = sha256_file(audio, cancel).await?;
if let Some(media_id) =
crate::agent::rag::verified_audio_media(pool, &hash, &config.agent_storage_dir).await?
{
// Preserve the relation used to populate the destination playlist,
// even when this recording came from a different upload or source.
sqlx::query(
"INSERT INTO furumusic__youtube_import_media (item_id,media_file_id)
VALUES ($1,$2) ON CONFLICT DO NOTHING",
)
.bind(item_id)
.bind(media_id)
.execute(pool)
.await?;
sync_target_playlists_for_imported_media(pool, media_id).await?;
crate::jobs::remove_exact_inbox_copy(config, audio, &hash).await?;
}
Ok(())
}
async fn sha256_file(path: &Path, cancel: &CancellationToken) -> anyhow::Result<String> {
let mut file = tokio::fs::File::open(path).await?;
let mut hasher = Sha256::new();
@@ -1923,7 +1963,11 @@ fn is_audio_path(path: &Path) -> bool {
.unwrap_or(false)
}
async fn sync_ai_statuses(pool: &PgPool, user_id: i64) -> anyhow::Result<()> {
pub(crate) async fn sync_ai_statuses(
pool: &PgPool,
user_id: i64,
jobs: Option<&[String]>,
) -> anyhow::Result<()> {
let items: Vec<YouTubeItemRow> = sqlx::query_as(
r#"SELECT i.id, i.job_id, i.source_id, i.source_url, i.title,
i.playlist_index, i.status, i.progress_percent,
@@ -1933,10 +1977,12 @@ async fn sync_ai_statuses(pool: &PgPool, user_id: i64) -> anyhow::Result<()> {
FROM furumusic__youtube_download_item i
JOIN furumusic__youtube_download j ON j.id = i.job_id
WHERE j.user_id = $1
AND ($2::text[] IS NULL OR j.id = ANY($2))
AND i.status IN ('awaiting_ai', 'ai_processing', 'needs_review', 'ai_failed')
AND i.inbox_path IS NOT NULL"#,
)
.bind(user_id)
.bind(jobs)
.fetch_all(pool)
.await?;
@@ -1947,7 +1993,7 @@ async fn sync_ai_statuses(pool: &PgPool, user_id: i64) -> anyhow::Result<()> {
};
let states: Vec<(String, i64)> = sqlx::query_as(
r#"SELECT status::text, COUNT(*)
FROM furumusic__pending_review
FROM furumusic__upload_review_state
WHERE input_path = $1
OR left(input_path, length($1) + 1) = $1 || '/'
GROUP BY status"#,
@@ -1990,14 +2036,19 @@ async fn sync_ai_statuses(pool: &PgPool, user_id: i64) -> anyhow::Result<()> {
|| counts.get("rejected").copied().unwrap_or(0) > 0
{
("needs_review", None)
} else if counts.get("cancelled").copied().unwrap_or(0) > 0 {
("cancelled", None)
} else {
("complete", None)
};
if item.status != next || item.error != error {
let now = now_string();
let completed_at =
matches!(next, "complete" | "needs_review" | "ai_failed").then(|| now.clone());
let completed_at = matches!(
next,
"complete" | "needs_review" | "ai_failed" | "cancelled"
)
.then(|| now.clone());
sqlx::query(
r#"UPDATE furumusic__youtube_download_item
SET status = $2, error = $3, completed_at = $4, updated_at = $5
@@ -2016,13 +2067,6 @@ async fn sync_ai_statuses(pool: &PgPool, user_id: i64) -> anyhow::Result<()> {
for job_id in touched_jobs {
refresh_parent(pool, &job_id).await?;
}
if let Err(error) = sync_target_playlist_tracks_for_user(pool, user_id).await {
tracing::warn!(
user_id,
%error,
"could not synchronize imported YouTube tracks with their target playlists"
);
}
Ok(())
}
@@ -2135,7 +2179,9 @@ async fn refresh_parent(pool: &PgPool, job_id: &str) -> anyhow::Result<()> {
"awaiting_ai"
} else if failed == total {
"failed"
} else if failed > 0 {
} else if count("cancelled") == total {
"cancelled"
} else if failed > 0 || count("cancelled") > 0 {
"complete_with_errors"
} else if review > 0 {
"needs_review"
@@ -2605,6 +2651,70 @@ pub mod db_migrations {
mod tests {
use super::*;
#[tokio::test]
#[ignore = "requires disposable PostgreSQL in FURU_IMPORT_TEST_DATABASE_URL"]
async fn youtube_staging_keeps_unverified_audio_and_links_verified_playlist_tracks()
-> anyhow::Result<()> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&std::env::var("FURU_IMPORT_TEST_DATABASE_URL")?)
.await?;
sqlx::raw_sql(r#"
CREATE TEMP TABLE furumusic__media_file(id bigint, file_path text, file_type text, sha256_hash text);
CREATE TEMP TABLE furumusic__track(id bigint, audio_file_id bigint, track_number int);
CREATE TEMP TABLE furumusic__youtube_import_media(item_id text, media_file_id bigint, PRIMARY KEY(item_id,media_file_id));
CREATE TEMP TABLE furumusic__youtube_download(id text, user_id bigint, target_playlist_id bigint);
CREATE TEMP TABLE furumusic__youtube_download_item(id text, job_id text, source_id text, playlist_index int);
CREATE TEMP TABLE furumusic__playlist(id bigint, owner_id bigint, updated_at text);
CREATE TEMP TABLE furumusic__playlist_track(playlist_id bigint,track_id bigint,position int,added_at text,added_by_user_id bigint);
INSERT INTO furumusic__track VALUES (43,7,1);
INSERT INTO furumusic__youtube_download VALUES ('job',1,4);
INSERT INTO furumusic__youtube_download_item VALUES ('item','job','video',1);
INSERT INTO furumusic__playlist VALUES (4,1,'');
"#).execute(&pool).await?;
let temp = tempfile::tempdir()?;
let inbox = temp.path().join("inbox");
let library = temp.path().join("library");
std::fs::create_dir(&inbox)?;
std::fs::create_dir(&library)?;
let audio = inbox.join("staged.mp3");
let catalog = library.join("existing.mp3");
let config = AppConfig {
agent_inbox_dir: inbox.to_string_lossy().into_owned(),
agent_storage_dir: library.to_string_lossy().into_owned(),
..Default::default()
};
let cancel = CancellationToken::new();
let bytes = b"downloaded audio";
std::fs::write(&audio, bytes)?;
std::fs::write(&catalog, b"different bytes")?;
sqlx::query("INSERT INTO furumusic__media_file VALUES (7,'existing.mp3','audio',$1)")
.bind(sha256_file(&audio, &cancel).await?)
.execute(&pool)
.await?;
reuse_archived_audio(&pool, &config, "item", &audio, &cancel).await?;
assert_eq!(std::fs::read(&audio)?, bytes);
assert_eq!(
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM furumusic__youtube_import_media")
.fetch_one(&pool)
.await?,
0
);
std::fs::write(&catalog, bytes)?;
reuse_archived_audio(&pool, &config, "item", &audio, &cancel).await?;
assert!(!audio.exists());
assert_eq!(std::fs::read(&catalog)?, bytes);
assert_eq!(
sqlx::query_scalar::<_, i64>(
"SELECT track_id FROM furumusic__playlist_track WHERE playlist_id=4"
)
.fetch_one(&pool)
.await?,
43
);
Ok(())
}
#[test]
fn cookie_models_use_exact_migrated_table_name() {
assert_eq!(
+1 -1
View File
@@ -70,7 +70,7 @@ html { overscroll-behavior:none; }
.task-form-body { overflow:visible; }
.run-log-body { min-height:300px; overflow:visible; }
.run-log-output { min-height:50dvh; max-height:70dvh; }
.settings-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"access" "oidc" "agent" "agentstatus" "similarity" "similaritystatus" "downloads" "federation" "lastfm" "developer" "lyrics" "actions"; }
.settings-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"access" "oidc" "agent" "agentstatus" "similarity" "similaritystatus" "downloads" "federation" "lastfm" "developer" "spotify" "lyrics" "actions"; }
.settings-federation-body { grid-template-columns:minmax(0,1fr); }
.repair-shell { grid-template-columns:250px minmax(0,1fr); }
}
+2
View File
@@ -867,6 +867,7 @@ tbody tr:hover {
"downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads"
"federation federation federation federation federation federation federation federation federation federation federation federation"
"lastfm lastfm lastfm lastfm lastfm lastfm lastfm lastfm developer developer developer developer"
"spotify spotify spotify spotify spotify spotify spotify spotify spotify spotify spotify spotify"
"lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics"
"actions actions actions actions actions actions actions actions actions actions actions actions";
gap: 16px;
@@ -890,6 +891,7 @@ tbody tr:hover {
.settings-downloads { grid-area: downloads; }
.settings-federation { grid-area: federation; }
.settings-lastfm { grid-area: lastfm; }
.settings-spotify { grid-area: spotify; }
.settings-lyrics { grid-area: lyrics; min-width:0; }
.lyrics-search-status {margin:0 16px 16px;min-width:0}
.lyrics-search-status .probe-row {gap:12px;flex-wrap:wrap}
+84 -20
View File
@@ -45,7 +45,7 @@
<section class="panel jobs-list-panel">
<div class="panel-head">
<div class="panel-title">
<strong>Pending Reviews</strong>
<strong>Review Queue</strong>
<span x-text="reviewPanelSubtitle()"></span>
</div>
<div class="toolbar">
@@ -82,7 +82,7 @@
<i data-lucide="check"></i>
<span x-text="reviewBulkBusy && reviewBulkAction === 'approve' ? 'Approving…' : 'Approve selected'"></span>
</button>
<button class="btn warn" @click="bulkReviews('requeue')" :disabled="reviewBulkBusy || selectedReviewCount() === 0">
<button class="btn warn" @click="bulkReviews('requeue')" :disabled="reviewBulkBusy || !selectedRequeueCount()">
<i data-lucide="rotate-ccw"></i>
Requeue selected
</button>
@@ -631,7 +631,7 @@
<div class="settings-page">
<label class="section-jump">Settings section
<select class="search" @change="jumpToSettings($event.target.value)">
<option value="access">Access</option><option value="oidc">SSO</option><option value="agent">Import agent</option><option value="similarity">Similarity</option><option value="downloads">Downloads</option><option value="podcasts">Podcasts</option><option value="federation">Federation</option><option value="lastfm">Last.fm</option><option value="developer">Developer</option>
<option value="access">Access</option><option value="oidc">SSO</option><option value="agent">Import agent</option><option value="similarity">Similarity</option><option value="downloads">Downloads</option><option value="podcasts">Podcasts</option><option value="federation">Federation</option><option value="lastfm">Last.fm</option><option value="spotify">Spotify import</option><option value="developer">Developer</option>
</select>
</label>
{% include "admin/podcasts.html" %}
@@ -1036,6 +1036,39 @@
</div>
</section>
<section class="panel settings-section settings-spotify" id="settings-spotify">
<div class="panel-head">
<div class="panel-title">
<strong>Spotify Import</strong>
<span>Optional playlist import through the Spotify Web API</span>
</div>
<span class="badge" :class="settingsDraft.spotify_client_id ? 'ok' : 'disabled'" x-text="settingsDraft.spotify_client_id ? 'Web API enabled' : 'Data export only'"></span>
</div>
<div class="settings-grid">
<div class="setting-field">
<label>
<span>Client ID</span>
<span class="source-pill" :class="sourceClass('spotify_client_id')" x-text="settingSource('spotify_client_id')"></span>
</label>
<input x-model="settingsDraft.spotify_client_id" autocomplete="off" spellcheck="false" />
<div class="setting-help">Client ID of a Spotify application owned by a Premium account. Authorization uses PKCE, so no client secret is needed. In Development Mode only users on the application's allowlist can sign in. Leave empty to offer only the data export.</div>
</div>
<div class="setting-field">
<label>
<span>Redirect URI</span>
<span class="source-pill" :class="sourceClass('spotify_redirect_uri')" x-text="settingSource('spotify_redirect_uri')"></span>
</label>
<input x-model="settingsDraft.spotify_redirect_uri" :placeholder="spotifyCallbackUrl()" autocomplete="off" spellcheck="false" />
<div class="setting-help">Optional. Set it when the public address differs from the one this page was opened at. Spotify requires HTTPS; plain HTTP is accepted only for 127.0.0.1.</div>
</div>
<div class="setting-field settings-wide">
<label for="spotify-callback-url">Redirect URI to register in Spotify</label>
<input id="spotify-callback-url" type="text" :value="settingsDraft.spotify_redirect_uri || spotifyCallbackUrl()" readonly @click="$el.select()" />
<div class="setting-help">Add this exact address to the Redirect URIs of your Spotify application.</div>
</div>
</div>
</section>
<section class="panel settings-section settings-lyrics" id="settings-lyrics">
<div class="panel-head"><div class="panel-title"><strong>Lyrics</strong><span>LRCLIB enrichment and local lyrics search</span></div></div>
<div class="setting-toggle">
@@ -1045,7 +1078,7 @@
</div>
<div class="setting-toggle">
<label class="setting-toggle-row"><span>Index lyrics for local semantic search</span><input type="checkbox" x-model="settingsDraft.lyrics_indexing_enabled" /></label>
<div class="setting-help">All saved versions and translations are indexed locally. Disabling pauses new embeddings; saved vectors and text search remain available. No lyrics or queries leave this instance.</div>
<div class="setting-help">Enabling indexing downloads the model once (487 MB) from Hugging Face. All lyrics versions and queries are processed locally. Turning indexing off keeps the model and existing index.</div>
<span class="source-pill" :class="sourceClass('lyrics_indexing_enabled')" x-text="settingSource('lyrics_indexing_enabled')"></span>
</div>
<div class="lyrics-search-status" aria-live="polite">
@@ -1395,10 +1428,10 @@
<input readonly :value="activeReview?.model_name || 'not processed yet'" />
</div>
<div class="field" x-show="activeReview?.error_message">
<label>Error</label>
<label x-text="activeReview?.status === 'conflict' ? 'Recording conflict' : 'Error'"></label>
<textarea readonly x-text="activeReview?.error_message || ''"></textarea>
</div>
<div x-show="activeReview?.status === 'pending'">
<div x-show="['pending', 'conflict'].includes(activeReview?.status)">
<div class="field">
<label>Artist</label>
<input x-model="reviewDraft.artist" />
@@ -1448,17 +1481,21 @@
</div>
</div>
<div class="toolbar dialog-actions">
<button class="btn primary" x-show="activeReview?.status === 'pending'" @click="approveActiveReview()">
<button class="btn primary" x-show="['pending', 'conflict'].includes(activeReview?.status)" :disabled="reviewApprovalBusy" @click="approveActiveReview()">
<i data-lucide="check"></i>
Approve
<span x-text="activeReview?.status === 'conflict' ? 'Check edited metadata' : 'Approve'"></span>
</button>
<button class="btn warn" @click="bulkOneReview('requeue', activeReview)">
<button class="btn" x-show="activeReview?.status === 'conflict'" :disabled="reviewApprovalBusy" @click="approveActiveReview(true)">
<i data-lucide="disc"></i>
Import as a separate recording
</button>
<button class="btn warn" x-show="['pending','failed','rejected'].includes(activeReview?.status)" :disabled="reviewApprovalBusy" @click="bulkOneReview('requeue', activeReview)">
<i data-lucide="rotate-ccw"></i>
Requeue
</button>
<button class="btn danger" @click="bulkOneReview('delete', activeReview)">
<button class="btn danger" :disabled="reviewApprovalBusy || activeReview?.status === 'processing'" @click="bulkOneReview('delete', activeReview)">
<i data-lucide="trash-2"></i>
Delete
<span x-text="activeReview?.status === 'conflict' ? 'Dismiss upload' : 'Delete'"></span>
</button>
</div>
</div>
@@ -2112,11 +2149,13 @@ function adminV2() {
notes: ''
},
reviewModalOpen: false,
reviewApprovalBusy: false,
reviewStatuses: [
{ value: null, label: 'All' },
{ value: 'queued', label: 'Queued' },
{ value: 'processing', label: 'Processing' },
{ value: 'pending', label: 'Pending' },
{ value: 'conflict', label: 'Recording conflicts' },
{ value: 'failed', label: 'Failed' }
],
jobs: [],
@@ -2227,7 +2266,9 @@ function adminV2() {
download_proxies: [],
torrent_proxy_id: '',
youtube_proxy_id: '',
youtube_cookie_id: ''
youtube_cookie_id: '',
spotify_client_id: '',
spotify_redirect_uri: ''
},
settingsProbe: { status: 'idle', ok: false },
settingsProbeLoading: false,
@@ -3100,6 +3141,10 @@ function adminV2() {
return `${window.location.origin}/api/player/lastfm/callback`;
},
spotifyCallbackUrl() {
return `${window.location.origin}/api/imports/providers/spotify/callback`;
},
settingsProbeBadge() {
if (this.settingsProbeLoading) return 'running';
if (this.settingsProbe.status === 'ok') return 'ok';
@@ -3184,6 +3229,15 @@ function adminV2() {
return Object.values(this.selectedReviewIds).filter(status => status === 'pending').length;
},
selectedRequeueCount() {
const eligible = ['pending', 'failed', 'rejected'];
if (this.reviewSelectionScope === 'filter') {
const counts = this.filterStatusCounts();
return eligible.reduce((total, status) => total + (counts[status] || 0), 0);
}
return Object.values(this.selectedReviewIds).filter(status => eligible.includes(status)).length;
},
reviewSelectionSummary() {
const total = this.selectedReviewCount();
if (!total) return 'Nothing selected';
@@ -3210,7 +3264,8 @@ function adminV2() {
const count = this.selectedReviewCount();
if (!count) return;
if (action === 'approve' && !this.selectedPendingReviewCount()) return;
if (action === 'delete' && !confirm(`Delete ${count} review row(s)?`)) return;
if (action === 'requeue' && !this.selectedRequeueCount()) return;
if (action === 'delete' && !confirm(`Dismiss ${count} review(s)? Furumi will skip these files on future scans. Audio files are kept.`)) return;
const payload = {
action,
mode: this.reviewSelectionScope,
@@ -3229,10 +3284,11 @@ function adminV2() {
});
this.showToast(action === 'approve'
? `${result.affected} review(s) approved · ${result.failed || 0} failed · ${result.skipped || 0} skipped`
: `${result.affected} review row(s) updated`);
: `${result.affected} review(s) ${action === 'delete' ? 'dismissed' : 'requeued'} · ${result.skipped || 0} skipped`);
this.clearReviewSelection();
await this.loadReviews(false);
if (action === 'approve') await this.loadLibrary(false);
return true;
} catch (error) {
this.showToast(error.message);
} finally {
@@ -3244,16 +3300,17 @@ function adminV2() {
async bulkOneReview(action, row) {
this.reviewSelectionScope = 'ids';
this.selectedReviewIds = { [row.id]: row.status };
await this.bulkReviews(action);
this.reviewModalOpen = false;
if (await this.bulkReviews(action)) this.reviewModalOpen = false;
},
async approveActiveReview() {
if (!this.activeReview) return;
async approveActiveReview(importSeparately = false) {
if (!this.activeReview || this.reviewApprovalBusy) return;
const row = this.activeReview;
this.reviewApprovalBusy = true;
try {
await this.request(`${this.apiBase}/reviews/${this.activeReview.id}/approve`, {
await this.request(`${this.apiBase}/reviews/${row.id}/approve`, {
method: 'POST',
body: JSON.stringify(this.reviewDraft)
body: JSON.stringify({ ...this.reviewDraft, import_separately: importSeparately })
});
this.showToast('Review approved');
this.reviewModalOpen = false;
@@ -3262,6 +3319,13 @@ function adminV2() {
await this.loadLibrary(false);
} catch (error) {
this.showToast(error.message);
if (error.message.startsWith('Duplicate check needs review:')) {
row.status = 'conflict';
row.error_message = error.message;
await this.loadReviews(false);
}
} finally {
this.reviewApprovalBusy = false;
}
},
+21
View File
@@ -23,15 +23,35 @@ if ('serviceWorker' in navigator) {
{% include "player/sidebar_styles.html" %}
{% include "player/collection_styles.html" %}
{% include "player/listening_styles.html" %}
<style>{% include "player/dialog_styles.css" %}</style>
{% if !guest %}
<style>{% include "player/get_app.css" %}</style>
{% include "player/imports_styles.html" %}
{% endif %}
{% if downloads_enabled %}
<style>
{% include "player/download_manager.css" %}
{% include "player/download_sources.css" %}
{% include "player/download_torrent.css" %}
</style>
{% endif %}
{% endblock head_extra %}
{% block body %}
{% include "player/shell.html" %}
{% include "player/modals.html" %}
{% if !guest %}
{# Body-level dialogs need an Alpine root, like the modals above. #}
<div x-data>
{% include "player/get_app.html" %}
{% include "player/imports_wizard.html" %}
</div>
{% endif %}
{% include "player/lyrics_modal.html" %}
{% include "player/offline_scripts.html" %}
{% include "player/offline_manager_scripts.html" %}
{% include "player/podcast_scripts.html" %}
{% if !guest %}{% include "player/imports_scripts.html" %}{% endif %}
{% include "player/lyrics_scripts.html" %}
{% include "player/lyrics_search_scripts.html" %}
{% include "player/search_group_scripts.html" %}
@@ -41,5 +61,6 @@ if ('serviceWorker' in navigator) {
{% include "player/playlist_header_scripts.html" %}
{% include "player/playlist_filter_scripts.html" %}
{% include "player/scripts.html" %}
{% if downloads_enabled %}{% include "player/download_manager_scripts.html" %}{% endif %}
<script>{{ self.alpine()|safe }}</script>
{% endblock body %}
+9
View File
@@ -38,10 +38,19 @@
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0m.5-9 2.5 2.5L23 9"/></svg>
{{ t.player_followed_page }}
</a>
<a data-online-only href="#imports" :aria-current="['imports', 'import_detail'].includes($store.library.view) ? 'page' : null">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v11m-4-4 4 4 4-4M5 14v6h14v-6"/></svg>
{{ t.player_import_library }}
</a>
<button type="button" @click="$store.user.openSettings()">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h9m4 0h3M4 12h2m4 0h10M4 18h8m4 0h4"/><circle cx="15" cy="6" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="14" cy="18" r="2"/></svg>
{{ t.nav_settings }}
</button>
<button type="button" aria-haspopup="dialog" aria-controls="get-app-dialog"
@click="$store.user.menuOpen = false; $store.user.getAppOpen = true">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v12m-4-4 4 4 4-4M4 16v4h16v-4"/></svg>
{{ t.player_get_app }}
</button>
<a data-online-only href="/admin/" x-show="$store.user.profile?.role === 'admin'" x-cloak>
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3 4.5 6v5c0 4.5 3.2 8 7.5 10 4.3-2 7.5-5.5 7.5-10V6z"/><path d="m9 12 2 2 4-4"/></svg>
{{ t.player_admin_panel }}
+2 -2
View File
@@ -1,6 +1,6 @@
<section class="artist-release-group artist-top-tracks" x-data="artistPopularTracks" :class="{'artist-top-folding':folding}"
x-effect="setTracks($store.library.currentArtist?.top_tracks)">
<h2 class="artist-release-group-title">{{ t.player_top_tracks }}</h2>
<h2 class="artist-release-group-title" x-ref="heading">{{ t.player_top_tracks }}</h2>
<div class="track-list-header">
<span>#</span>
<span>{{ t.player_title }}</span>
@@ -22,7 +22,7 @@
</div>
</div>
<button class="artist-top-tracks-toggle" type="button" x-show="groups.length > 5" x-cloak
@click="anchorListScroll($el); toggleList()" :aria-expanded="expanded" aria-controls="artist-popular-tracks">
@click="toggleList(); $nextTick(() => scrollList())" :aria-expanded="expanded" aria-controls="artist-popular-tracks">
<span x-text="expanded ? '{{ t.player_collapse }}' : '{{ t.player_expand_all }}'"></span>
<svg viewBox="0 0 36 8" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
<path d="m1 1 17 5 17-5" stroke-linecap="round" stroke-linejoin="round"/>
+4
View File
@@ -0,0 +1,4 @@
<button class="player-dialog-close" type="button" @click="$dispatch('dismiss-player-dialog')"
aria-label="{{ t.player_close }}" title="{{ t.player_close }}">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg>
</button>
+11
View File
@@ -0,0 +1,11 @@
<header class="player-dialog-head {{ dialog_head_class }}">
<svg class="player-dialog-icon" viewBox="0 0 24 24" aria-hidden="true">
<path d="{{ dialog_icon }}"/>
</svg>
<h2 id="{{ dialog_title_id }}" tabindex="-1">{{ dialog_title }}</h2>
{% if show_version %}
<a class="settings-app-version" data-online-only href="https://gt.hexor.cy/Furumi/furumi-web"
target="_blank" rel="noopener noreferrer" aria-label="Furumi v{{ t.app_version() }}">v{{ t.app_version() }}</a>
{% endif %}
{% include "player/dialog_close.html" %}
</header>
+48
View File
@@ -0,0 +1,48 @@
.player-dialog {
--dialog-gutter: clamp(14px, 3vw, 22px);
--dialog-edge: 16px;
position: fixed; inset: 0; margin: 0; box-sizing: border-box;
width: 100%; height: 100%; max-width: none; max-height: none;
padding: max(var(--dialog-edge), env(safe-area-inset-top)) max(var(--dialog-edge), env(safe-area-inset-right))
max(var(--dialog-edge), env(safe-area-inset-bottom)) max(var(--dialog-edge), env(safe-area-inset-left));
border: 0; background: rgb(0 0 0 / .65); color: var(--text-primary); color-scheme: dark;
}
.player-dialog::backdrop { background: transparent; }
.player-dialog[open] { display: grid; place-items: center; }
.player-dialog-surface {
width: min(var(--dialog-width, 760px), 100%); min-width: 0;
max-height: 100%; box-sizing: border-box; overflow: auto; overscroll-behavior: contain;
border: 1px solid var(--bg-active); border-radius: 14px; background: var(--bg-secondary);
box-shadow: 0 16px 60px #0007; scrollbar-width: thin;
}
.player-dialog-head {
position: sticky; top: 0; z-index: 5; display: flex; align-items: center;
gap: 10px; padding: 10px var(--dialog-gutter);
border-bottom: 1px solid var(--border-color); background: var(--bg-secondary);
}
.player-dialog-head h2 { min-width: 0; margin: 0; font-size: 21px; line-height: 1.25; }
.player-dialog-head h2:focus { outline: none; }
.player-dialog-icon, .player-dialog-close svg {
width: 20px; height: 20px; flex: none; fill: none; stroke: currentColor;
stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round;
}
.player-dialog-icon { color: var(--accent); }
.player-dialog-close {
display: grid; place-items: center; flex: none; width: 34px; height: 34px;
margin-inline-start: auto; padding: 0; border: 0; border-radius: 50%;
background: var(--bg-elevated); color: var(--text-secondary); cursor: pointer;
}
.player-dialog-close svg { width: 17px; height: 17px; }
.player-dialog-close:hover { color: var(--text-primary); background: var(--bg-active); }
.player-dialog-close:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
@media (max-width: 600px) {
.player-dialog { --dialog-edge: 6px; }
.player-dialog-head { gap: 8px; padding-block: 6px; }
.player-dialog-head h2 { font-size: 19px; }
.player-dialog-close { width: 40px; height: 40px; }
}
@media (prefers-reduced-motion: no-preference) {
.player-dialog[open] .player-dialog-surface { animation: player-dialog-in 140ms ease-out; }
.player-dialog-close { transition: color 120ms, background-color 120ms; }
@keyframes player-dialog-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
}
@@ -0,0 +1,39 @@
<div class="download-destination">
<div class="download-destination-label">
<label for="{{ kind }}-target-playlist">{{ t.player_download_playlist_label }}</label>
<span class="download-playlist-help" x-data="{ help:false }"
@mouseenter="help=true" @mouseleave="help=false" @click.outside="help=false">
<button type="button" class="download-help-button" aria-label="{{ t.player_info }}"
aria-describedby="{{ kind }}-playlist-hint" @focus="help=true" @blur="help=false"
@click="help=true" @keydown.escape="if (help) { $event.stopPropagation(); $event.preventDefault(); help=false }">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true">
<circle cx="12" cy="12" r="9"/><path d="M12 11v6m0-10v1"/>
</svg>
</button>
<span id="{{ kind }}-playlist-hint" role="tooltip" x-cloak x-show="help" x-transition.opacity.duration.120ms>
{% if kind == "youtube" %}{{ t.player_youtube_destination_hint }}{% else %}{{ t.player_import_destination_hint }}{% endif %}
</span>
</span>
</div>
<div class="download-destination-fields">
<select class="download-field" id="{{ kind }}-target-playlist" x-model="$store.torrents.{{ kind }}PlaylistChoice"
{% if kind == "youtube" %}@change="$store.torrents.youtubePlaylistChoiceChanged()" :disabled="$store.torrents.youtubeSubmitting"
{% else %}@change="$store.torrents.importPlaylistChoiceChanged('{{ kind }}')"
{% if kind == "local" %}:disabled="$store.torrents.localFilesUploading || $store.torrents.localPlaylistLocked"
{% else %}:disabled="$store.torrents.loading || $store.torrents.torrentDestinationLocked()"{% endif %}{% endif %}>
<option value="">{{ t.player_youtube_no_destination }}</option>
<template x-for="playlist in $store.torrents.youtubeOwnedPlaylists()" :key="playlist.id">
<option :value="String(playlist.id)" x-text="playlist.title"></option>
</template>
<option value="__new__">{{ t.player_youtube_create_playlist }}</option>
</select>
<template x-if="$store.torrents.{{ kind }}PlaylistChoice === '__new__'">
<input class="download-field" type="text" maxlength="255" autocomplete="off"
x-model="$store.torrents.{{ kind }}NewPlaylistTitle" placeholder="{{ t.player_youtube_new_playlist_name }}"
aria-label="{{ t.player_youtube_new_playlist_name }}"
{% if kind == "local" %}:disabled="$store.torrents.localFilesUploading || $store.torrents.localPlaylistLocked"
{% else if kind == "torrent" %}:disabled="$store.torrents.loading || $store.torrents.torrentDestinationLocked()"
{% else %}:disabled="$store.torrents.youtubeSubmitting"{% endif %}>
</template>
</div>
</div>
+47
View File
@@ -0,0 +1,47 @@
<input id="direct-audio-file-input" type="file" multiple accept="audio/*,.mp3,.flac,.wav,.m4a,.ogg,.opus,.aac" hidden
:disabled="$store.torrents.localFilesUploading" @change="$store.torrents.setLocalFiles($event.target.files); $event.target.value=''">
<template x-if="manager.sourceTab === 'files'">
<section id="downloads-files" class="download-source-pane" role="tabpanel" aria-labelledby="downloads-tab-files">
<input id="direct-audio-folder-input" type="file" webkitdirectory multiple hidden
:disabled="$store.torrents.localFilesUploading" @change="$store.torrents.setLocalFiles($event.target.files); $event.target.value=''">
<div class="download-local-drop" :class="{dragging:$store.torrents.localFilesDragging}"
@dragenter.prevent="$store.torrents.localFilesDragging=true" @dragover.prevent="$store.torrents.localFilesDragging=true"
@dragleave.prevent="$store.torrents.leaveLocalFileDrop($event)" @drop.prevent="$store.torrents.dropLocalFiles($event)">
<div class="download-local-lead">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4m-5 5 5-5 5 5M4 15v4a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-4"/></svg>
<div><strong class="download-local-desktop">{{ t.player_drop_audio_title }}</strong><strong class="download-local-mobile">{{ t.player_local_files }}</strong>
<small>{{ t.player_drop_audio_formats }}</small>
</div>
</div>
<div class="download-pick-actions">
<button type="button" class="download-button" :class="{primary:!manager.localFiles.length}" :disabled="manager.localFilesUploading"
@click="document.getElementById('direct-audio-file-input').click()">{{ t.player_choose_audio_files }}</button>
<button type="button" class="download-button" :disabled="$store.torrents.localFilesUploading" title="{{ t.player_audio_folder_hint }}"
@click="document.getElementById('direct-audio-folder-input').click()">{{ t.player_choose_audio_folder }}</button>
</div>
</div>
<template x-if="manager.localFiles.length && !manager.localFilesUploading">
<div class="download-local-selection">
<div class="download-preview-title">
<h4 x-text="manager.localFiles.length === 1 ? manager.localFiles[0].name : (manager.localFiles[0]?.webkitRelativePath?.split('/')[0] || '{{ t.player_file_uploads }}')"></h4>
<span x-text="$store.torrents.localUploadSummary()"></span>
</div>
{% let kind = "local" %}
{% include "player/download_destination.html" %}
<div class="download-selection-actions">
<button type="button" class="download-button" :disabled="$store.torrents.localFilesUploading"
@click="$store.torrents.clearLocalFiles()">{{ t.player_cancel }}</button>
<button type="button" class="download-button primary" :disabled="$store.torrents.localFilesUploading || !$store.torrents.importDestinationValid('local')"
@click="$store.torrents.uploadLocalFiles()">{{ t.player_upload_selected_files }}</button>
</div>
</div>
</template>
<button type="button" class="download-button primary" x-show="manager.localPendingFinish && !manager.localFilesUploading"
@click="manager.uploadLocalFiles()">{{ t.player_finish_upload }}</button>
<div class="download-source-progress" x-show="manager.localFilesUploading" x-cloak>
<div><span x-text="T.uploadingFiles"></span>
<span x-text="$store.torrents.uploadProgressText"></span></div>
<progress max="100" :value="$store.torrents.uploadProgress" aria-label="{{ t.player_file_uploads }}"></progress>
</div>
</section>
</template>
+58
View File
@@ -0,0 +1,58 @@
<template x-if="manager.sourceTab === 'history'">
<section id="downloads-history" class="download-history" role="tabpanel" aria-labelledby="downloads-tab-history">
<template x-if="manager.historyLoaded && (manager.downloadHistory.length || checked.size)">
<div class="download-history-tools">
<label><input type="checkbox" x-ref="all" :disabled="confirming || !manager.downloadHistory.length"
:checked="manager.downloadHistory.length > 0 && checkedOnPage === manager.downloadHistory.length"
x-effect="$el.indeterminate = checkedOnPage > 0 && checkedOnPage < manager.downloadHistory.length"
@change="mark(manager.downloadHistory,$el.checked)">
<span>{{ t.player_download_select_page }}</span>
</label>
<button type="button" class="download-button forget-button" x-ref="remove" x-show="checked.size && !confirming"
@click="removalError=''; confirming=true; $nextTick(() => $refs.keep.focus())">
{{ t.player_remove_from_history }} <b x-text="checked.size"></b>
</button>
</div>
</template>
<template x-if="confirming">
<div class="download-confirm" role="group" aria-label="{{ t.player_download_forget_question }}">
<div><strong>{{ t.player_download_forget_question }} (<span x-text="checked.size"></span>)</strong>
<small>{{ t.player_download_forget_hint }}</small></div>
<button type="button" class="download-button" x-ref="keep" :disabled="removing" @click="stopConfirmation()">{{ t.player_cancel }}</button>
<button type="button" class="download-button forget-button" :disabled="removing" @click="forget()">{{ t.player_download_forget }}</button>
</div>
</template>
<p class="download-history-error" role="alert" x-show="removalError" x-text="removalError"></p>
<div class="download-history-error" role="status" x-show="manager.historyError">
<span x-text="manager.historyError"></span>
<button type="button" class="download-button" @click="manager.refreshDownloads()">{{ t.player_refresh }}</button>
</div>
<template x-if="!manager.historyLoaded && manager.historyLoading">
<div class="page-skeleton" role="status"><span class="loading-label">{{ t.player_loading_content }}</span>{% include "player/skeleton_tracks.html" %}</div>
</template>
<template x-if="manager.historyLoaded && !manager.downloadHistory.length && !manager.historyError">
<p class="download-history-empty">{{ t.player_download_empty }}</p>
</template>
<ul class="download-activity" x-show="manager.historyLoaded">
<template x-for="row in manager.downloadHistory" :key="key(row)">
<li class="download-history-row">
<input type="checkbox" :aria-label="titleFor(row)" :disabled="confirming"
:checked="checked.has(key(row))" @change="mark([row],$el.checked)">
<svg class="download-source-icon" aria-hidden="true"><use :href="'#download-symbol-' + row.source"/></svg>
<div class="download-job-title">
<template x-if="canOpen(row)"><button type="button" :title="titleFor(row)" :disabled="confirming" @click="openTransfer(row)" x-text="titleFor(row)"></button></template>
<template x-if="!canOpen(row)"><strong :title="titleFor(row)" x-text="titleFor(row)"></strong></template>
<small x-text="metaFor(row)"></small>
<small class="download-history-error" x-show="row.error" x-text="row.error"></small>
</div>
<span class="download-job-status" :data-tone="tone(row)" x-text="statusFor(row)"></span>
</li>
</template>
</ul>
<div class="download-history-pages" x-show="manager.historyPage || manager.historyHasMore">
<button type="button" class="download-button" :disabled="!manager.historyPage || manager.historyLoading || confirming" @click="manager.changeHistoryPage(-1)">{{ t.player_previous }}</button>
<span x-text="manager.historyPage+1"></span>
<button type="button" class="download-button" :disabled="!manager.historyHasMore || manager.historyLoading || confirming" @click="manager.changeHistoryPage(1)">{{ t.player_next }}</button>
</div>
</section>
</template>
+83
View File
@@ -0,0 +1,83 @@
.downloads-shell { display: flex; flex-direction: column; overflow: hidden; }
.downloads-nav {
display: flex; flex: none; align-items: center; gap: 5px;
padding: 10px var(--dialog-gutter) 0;
}
.downloads-nav button, .download-button, .download-icon-button {
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
min-height: 34px; padding: 5px 11px; border: 1px solid var(--bg-active); border-radius: 7px;
background: var(--bg-elevated); color: var(--text-primary); cursor: pointer; font: inherit; font-size: 13px; font-weight: 600;
}
.downloads-nav button { border-color: transparent; background: transparent; color: var(--text-secondary); }
.downloads-nav button:last-of-type { margin-inline-start: auto; }
.downloads-nav button[aria-selected=true] { color: #a1e6b6; background: #1d3827; }
.download-icon-button { width: 34px; flex: none; padding: 0; border-color: transparent; background: transparent; color: var(--text-secondary); }
.download-button:hover,.download-icon-button:hover,.downloads-nav button:hover:not([aria-selected=true]) { background: var(--bg-hover); color: var(--text-primary); }
.download-button.primary { border-color: transparent; background: var(--accent); color: #081a0e; }
.download-button.primary:hover { background: var(--accent-hover); }
.downloads-shell button:disabled { opacity: .45; cursor: default; }
.downloads-content :is(button,input,select,summary):focus-visible,.downloads-nav button:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.downloads-nav svg,.download-icon-button svg,.download-button svg,.downloads-latest svg,.download-source-icon {
width: 17px; height: 17px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round;
}
.downloads-content { min-width: 0; min-height: 0; padding: 16px var(--dialog-gutter); overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; }
.download-field { min-height: 35px; padding: 6px 9px; border: 1px solid var(--bg-active); border-radius: 6px; background: var(--bg-primary); color: var(--text-primary); font: inherit; font-size: 13px; }
.downloads-notice { display: flex; align-items: center; gap: 8px; flex: none; margin: 8px var(--dialog-gutter) 0; padding-inline: 9px 0; border-inline-start: 2px solid var(--accent); color: #b5dbbf; font-size: 13px; }
.downloads-notice span { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.downloads-notice.error { color: #f1abab; border-color: #d58e8e; }
.downloads-latest,.downloads-stats {
display: flex; align-items: baseline; gap: 8px; flex: none; min-width: 0; margin: 0;
padding: 10px var(--dialog-gutter); color: var(--text-secondary); font: inherit; font-size: 12px;
text-align: start; border: 0; border-top: 1px solid var(--border-color); background: transparent;
}
.downloads-stats { background: var(--bg-primary); }
.downloads-stats strong { color: var(--text-primary); font-weight: 500; font-variant-numeric: tabular-nums; }
.downloads-latest { width: 100%; align-items: center; cursor: pointer; }
.downloads-latest:hover { background: var(--bg-hover); }
.downloads-latest span { flex: none; }
.downloads-latest strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; color: var(--text-primary); }
.downloads-latest small { margin-inline-start: auto; text-align: end; font: inherit; }
.downloads-shell [data-tone=success] { color: #9adeb0; }
.downloads-shell [data-tone=attention] { color: #e3c694; }
.download-history { min-width: 0; }
.download-history-tools, .download-confirm, .download-history-pages { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.download-history-tools { justify-content: space-between; min-height: 40px; }
.download-history-tools label { display: flex; align-items: center; gap: 10px; min-height: 34px; font-size: 12px; cursor: pointer; color: var(--text-secondary); }
.download-history input[type=checkbox] { width: 17px; height: 17px; margin: 0; accent-color: var(--accent); cursor: pointer; }
.download-history-tools b { font-variant-numeric: tabular-nums; }
.download-button.forget-button { color: #efb0ac; }
.download-confirm { padding: 10px; margin-block: 4px; border: 1px solid #634242; border-radius: 7px; background: #2c2323; }
.download-confirm div { flex: 1 1 190px; font-size: 13px; }
.download-confirm small { display: block; margin-top: 3px; color: var(--text-secondary); font-size: 12px; }
.download-history-empty,.download-history-error { margin: 0; padding-block: 8px; font-size: 13px; color: var(--text-secondary); }
.download-history-error { color: #f1abab; }
.download-activity { display: grid; list-style: none; padding: 0; margin: 0; }
.download-history-row { display: grid; grid-template-columns: auto auto minmax(0,1fr) auto; align-items: center; gap: 10px; min-height: 50px; padding-block: 6px; border-top: 1px solid var(--border-color); }
.download-source-icon { color: var(--text-secondary); }
.download-job-title { display: grid; gap: 3px; min-width: 0; }
.download-job-title :is(strong,button,small) { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; text-align: start; }
.download-job-title :is(strong,button) { font: inherit; color: inherit; font-size: 14px; font-weight: 600; }
.download-job-title button { width: fit-content; max-width: 100%; padding: 0; border: 0; background: transparent; cursor: pointer; }
.download-job-title button:hover { text-decoration: underline; }
.download-job-title small,.download-job-status { font-size: 12px; color: var(--text-secondary); }
.download-job-title .download-history-error { padding: 0; color: #efb0ac; overflow-wrap: anywhere; white-space: normal; }
.download-job-status { max-width: 16ch; text-align: end; }
.download-history-pages { justify-content: flex-end; margin-top: 10px; font: inherit; font-size: 12px; }
@media (prefers-reduced-motion: no-preference) {
.downloads-content > [role=tabpanel],.download-confirm { animation: player-dialog-in 120ms ease-out; }
}
@media(max-width: 600px) {
.downloads-nav { gap: 2px; padding-top: 6px; }
.downloads-nav button { padding-inline: 7px; font-size: 12px; }
.downloads-nav svg { width: 15px; height: 15px; }
.download-button,.download-icon-button,.downloads-nav button { min-height: 40px; }
.downloads-content { padding-block: 12px; }
.download-field { font-size: 16px; }
.download-history-row { gap: 6px; }
.download-job-status { max-width: 10ch; }
.downloads-latest { display: grid; grid-template-columns: minmax(0,1fr) auto auto; gap: 3px 6px; }
.downloads-latest span { grid-column: 1 / -1; }
}
@media(max-width: 375px) {
.downloads-nav button { flex: 1; flex-direction: column; gap: 2px; padding-inline: 2px; }
}
+52
View File
@@ -0,0 +1,52 @@
<template x-if="$store.torrents.modal">
<dialog class="player-dialog downloads-dialog" x-data="downloadManager" aria-labelledby="downloads-title"
x-init="$nextTick(() => { if ($el.isConnected) { $el.showModal(); document.getElementById('downloads-title').focus({preventScroll:true}) } })"
x-effect="if ($store.offline.active) manager.close()" @cancel.prevent="cancel()"
@dismiss-player-dialog.stop="dismiss()" @click.self="dismiss()" @keydown.stop>
<svg aria-hidden="true" width="0" height="0" style="position:absolute">
<symbol id="download-symbol-history" viewBox="0 0 24 24"><path d="M3 5v5h5M3.5 10a8.5 8.5 0 1 1 1 7M12 7v5l3 2"/></symbol>
<symbol id="download-symbol-youtube" viewBox="0 0 24 24"><rect x="2" y="5" width="20" height="14" rx="4"/><path d="m10 9 5 3-5 3Z"/></symbol>
<symbol id="download-symbol-torrents" viewBox="0 0 24 24"><circle cx="12" cy="5" r="2.5"/><circle cx="5" cy="18" r="2.5"/><circle cx="19" cy="18" r="2.5"/><path d="m10.6 7.1-4.2 8.6m7-8.6 4.2 8.6M7.5 18h9"/></symbol>
<symbol id="download-symbol-files" viewBox="0 0 24 24"><path d="M3 7V5a1 1 0 0 1 1-1h5l2 3h9a1 1 0 0 1 1 1v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/></symbol>
</svg>
<div class="player-dialog-surface downloads-shell">
{% let dialog_head_class = "downloads-head" %}
{% let dialog_title_id = "downloads-title" %}
{% let dialog_title = t.player_download_music %}
{% let dialog_icon = "M12 3v11m-4-4 4 4 4-4M4 15v4a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-4" %}
{% let show_version = false %}
{% include "player/dialog_header.html" %}
<nav class="downloads-nav" role="tablist" aria-label="{{ t.player_download_title }}" @keydown="navigate($event)">
<template x-for="section in sections" :key="section.id">
<button type="button" role="tab" :id="'downloads-tab-' + section.id" :aria-controls="'downloads-' + section.id"
:aria-selected="manager.sourceTab === section.id" :tabindex="manager.sourceTab === section.id ? 0 : -1" @click="select(section.id)">
<svg aria-hidden="true"><use :href="'#download-symbol-' + section.id"/></svg>
<span x-text="section.label"></span>
</button>
</template>
</nav>
<div class="downloads-notice" role="status" x-show="manager.message" :class="{error:manager.error}" x-cloak>
<span x-text="manager.message"></span>
<button type="button" class="download-icon-button" aria-label="{{ t.player_close }}" @click="manager._setMessage('')"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg></button>
</div>
<div class="downloads-content">
{% include "player/download_files.html" %}
{% if torrent_downloads_enabled %}{% include "player/download_torrent.html" %}{% endif %}
{% if youtube_downloads_enabled %}{% include "player/download_youtube.html" %}{% endif %}
{% include "player/download_history.html" %}
</div>
<template x-if="manager.latestDownload && manager.sourceTab !== 'history' && !(manager.sourceTab === 'torrents' && manager.workspaceMode === 'session') && !(manager.sourceTab === 'youtube' && manager.youtubeDetail)">
<button type="button" class="downloads-latest" @click="select('history')">
<span>{{ t.player_download_latest }}</span>
<strong x-text="titleFor(manager.latestDownload)"></strong>
<small :data-tone="tone(manager.latestDownload)" x-text="statusFor(manager.latestDownload)"></small>
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>
</button>
</template>
<footer class="downloads-stats" id="downloads-stats" x-show="manager.downloadStats" x-cloak>
<span>{{ t.player_my_uploads }}</span>
<strong x-text="manager.downloadStats ? formatArtistCount(manager.downloadStats.tracks,'tracks') + ' / ' + formatArtistCount(manager.downloadStats.releases,'releases') : ''"></strong>
</footer>
</div>
</dialog>
</template>
@@ -0,0 +1,112 @@
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('downloadManager', () => ({
get manager() { return Alpine.store('torrents'); },
sections: [
{id:'files', label:'{{ t.player_files }}'},
{% if torrent_downloads_enabled %}{id:'torrents', label:'{{ t.player_torrents }}'},{% endif %}
{% if youtube_downloads_enabled %}{id:'youtube', label:'{{ t.player_youtube }}'},{% endif %}
{id:'history', label:'{{ t.player_download_history_tab }}'},
],
checked: new Map(),
confirming: false,
removing: false,
removalError: '',
sourceLabel(id) {
return {files:'{{ t.player_files }}', torrents:'{{ t.player_torrents }}', youtube:'{{ t.player_youtube }}'}[id];
},
fileCount(n) {
const forms = {one:'{{ t.player_download_file_one }}', few:'{{ t.player_download_file_few }}', other:'{{ t.player_files_count }}'};
return n + ' ' + (forms[artistPluralRules.select(n)] || forms.other);
},
titleFor(row) { return row.title || (row.item_count ? this.fileCount(row.item_count) : this.sourceLabel(row.source)); },
metaFor(row) {
const parts = [this.sourceLabel(row.source)];
if (row.title && row.item_count > 1) parts.push(this.fileCount(row.item_count));
if (row.created_at) parts.push(this.manager.formatUploadDate(row.created_at));
return parts.join(' · ');
},
tone(row) {
if (['complete','completed','skipped'].includes(row.status)) return 'success';
if (['failed','ai_failed','needs_review','complete_with_errors'].includes(row.status)) return 'attention';
return 'normal';
},
statusFor(row) {
const transfer = row.source === 'torrents' && ['preview','moving','paused','completed'].includes(row.status);
const label = transfer ? this.manager.statusLabel(row) : this.manager.youtubeStatusLabel(row.status);
return row.status === 'downloading' && row.progress_percent != null ? label + ' · ' + Math.round(row.progress_percent) + '%' : label;
},
select(id) {
if (this.removing) return;
this.confirming = false;
this.manager.showSourceTab(id);
this.$nextTick(() => document.getElementById('downloads-tab-' + id)?.focus({preventScroll:true}));
},
navigate(event) {
const index = this.sections.findIndex(s => s.id === this.manager.sourceTab);
const count = this.sections.length;
const next = {ArrowLeft:(index+count-1)%count, ArrowRight:(index+1)%count, Home:0, End:count-1}[event.key];
if (next === undefined) return;
event.preventDefault();
this.select(this.sections[next].id);
},
canOpen(row) {
return row.source === 'torrents' && this.manager.torrentDownloadsEnabled || row.source === 'youtube' && this.manager.youtubeDownloadsEnabled;
},
openTransfer(row) {
if (row.source === 'torrents') {
this.select('torrents');
this.manager.openSession(row.id);
} else {
this.manager.openYoutubeJob(row);
}
},
key(row) { return row.source + ':' + row.id; },
mark(rows, value) {
for (const row of rows) {
if (value) this.checked.set(this.key(row), {source:row.source, id:row.id});
else this.checked.delete(this.key(row));
}
},
get checkedOnPage() { return this.manager.downloadHistory.filter(row => this.checked.has(this.key(row))).length; },
stopConfirmation() {
this.confirming = false;
this.$nextTick(() => this.$refs.remove?.focus());
},
async forget() {
if (this.removing || !this.checked.size) return;
this.removing = true;
this.removalError = '';
try {
const res = await fetch('/api/player/downloads/history/hide', {
method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({items:[...this.checked.values()]})
});
if (!res.ok) throw new Error();
const m = this.manager;
m.downloadHistory = m.downloadHistory.filter(row => !this.checked.has(this.key(row)));
if (m.latestDownload && this.checked.has(this.key(m.latestDownload))) m.latestDownload = null;
if (m.youtubeDetail && this.checked.has('youtube:' + m.youtubeDetail.id)) m.youtubeDetail = null;
if (m.previewData && this.checked.has('torrents:' + m.previewData.id)) m.addNew();
this.checked.clear();
this.confirming = false;
await m.refreshDownloads();
this.$nextTick(() => this.$refs.all?.focus({preventScroll:true}));
} catch {
this.removalError = '{{ t.player_download_forget_error }}';
} finally {
this.removing = false;
}
},
cancel() {
if (this.confirming && !this.removing) this.stopConfirmation();
else this.dismiss();
},
dismiss() {
finishPlayerDialog(this.$root, () => {
this.manager.close();
this.$nextTick(() => document.querySelector('.torrent-import-btn')?.focus({preventScroll:true}));
});
},
}));
});
</script>
+79
View File
@@ -0,0 +1,79 @@
.download-source-pane { display: grid; gap: 12px; min-width: 0; }
.download-source-pane > * { min-width: 0; }
.download-link-form { display: grid; gap: 6px; }
.download-link-form label, .download-destination-label label { font-size: 13px; font-weight: 600; color: var(--text-secondary); }
.download-link-controls { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px; }
.download-link-controls input, .download-destination-fields :is(select,input) { min-width: 0; width: 100%; }
.download-destination {
display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center;
column-gap: 10px; min-width: 0;
}
.download-destination-label { display: flex; align-items: center; gap: 1px; }
.download-destination-fields { display: flex; min-width: 0; gap: 6px; }
.download-destination-fields > :is(select, input) { flex: 1 1 0; }
.download-playlist-help { position: relative; display: inline-flex; }
.download-help-button {
display: grid; place-items: center; width: 28px; height: 30px;
border: 0; background: none; border-radius: 5px; color: var(--text-secondary); cursor: help;
}
.download-help-button:hover { color: var(--text-primary); background: var(--bg-hover); }
.download-playlist-help [role=tooltip] {
position: absolute; inset-block-end: calc(100% + 3px); inset-inline-start: -42px;
width: min(240px, 65vw); z-index: 4; padding: 8px 10px;
background: var(--bg-active); color: var(--text-primary); border: 1px solid var(--border-color);
box-shadow: 0 4px 15px #0006; border-radius: 6px; font-size: 12px; line-height: 1.45;
}
.download-preview-title, .download-selection-actions, .download-pick-actions {
display: flex; align-items: center; gap: 8px;
}
.download-preview-title { min-width: 0; justify-content: space-between; }
.download-preview-title h4 { margin: 0; min-width: 0; overflow-wrap: anywhere; color: var(--text-primary); font-size: 14px; line-height: 1.35; }
.download-preview-title > span { flex: none; color: var(--text-secondary); font-size: 12px; font-variant-numeric: tabular-nums; }
.download-video-preview, .download-local-selection, .download-source-detail { display: grid; gap: 10px; min-width: 0; }
.download-choose-videos { justify-self: start; }
.download-video-picker { min-width: 0; border: 1px solid var(--border-color); border-radius: 7px; }
.download-video-all, .download-video-row {
display: flex; align-items: center; gap: 9px; min-width: 0; min-height: 35px;
padding: 5px 8px; cursor: pointer; font-size: 13px;
}
.download-video-all { background: var(--bg-elevated); font-weight: 600; }
.download-video-row:hover { background: var(--bg-hover); }
.download-video-all input, .download-video-row input { flex: none; width: 16px; height: 16px; margin: 0; accent-color: var(--accent); }
.download-video-list { max-height: min(42dvh, 350px); overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; }
.download-video-row > :last-child { overflow-wrap: anywhere; }
.download-video-index { color: var(--text-secondary); font-size: 12px; font-variant-numeric: tabular-nums; }
.download-selection-actions { justify-content: end; flex-wrap: wrap; }
.download-local-drop {
display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px 16px;
min-height: 76px; padding: 12px; border: 1px dashed var(--bg-active); border-radius: 8px; background: var(--bg-primary);
transition: border-color 140ms, background 140ms;
}
.download-local-drop.dragging { border-color: var(--accent); background: #1db95410; }
.download-local-lead { display: flex; align-items: center; gap: 10px; min-width: 0; }
.download-local-lead > svg { width: 21px; height: 21px; color: var(--text-secondary); }
.download-source-pane svg { fill: none; stroke: currentColor; stroke-width: 1.65; stroke-linecap: round; stroke-linejoin: round; flex: none; }
.download-local-lead strong, .download-local-lead small { display: block; }
.download-local-lead strong { font-size: 14px; }
.download-local-lead small { margin-top: 2px; color: var(--text-secondary); font-size: 12px; line-height: 1.4; }
.download-local-lead .download-local-mobile { display: none; }
.download-source-progress { display: grid; gap: 4px; color: var(--text-secondary); font-size: 12px; }
.download-source-progress div { display: flex; justify-content: space-between; gap: 8px; }
.download-source-progress progress { display: block; width: 100%; height: 4px; border: 0; border-radius: 3px; background: var(--bg-active); color: var(--accent); accent-color: var(--accent); }
.download-source-progress progress::-webkit-progress-bar { background: var(--bg-active); border-radius: 3px; }
.download-source-progress progress::-webkit-progress-value { background: var(--accent); border-radius: 3px; }
.download-source-progress progress::-moz-progress-bar { background: var(--accent); border-radius: 3px; }
.download-source-error { margin: 0; overflow-wrap: anywhere; color: #eba8a8; font-size: 12px; }
@media (max-width: 600px) {
.download-link-controls { gap: 5px; }
.download-destination { align-items: start; gap: 6px; }
.download-destination-label { min-height: 38px; }
.download-destination-fields { flex-direction: column; }
.download-destination-fields > :is(select,input) { flex: auto; }
.download-video-all, .download-video-row { min-height: 40px; }
.download-local-lead .download-local-desktop { display: none; }
.download-local-lead .download-local-mobile { display: block; }
}
@media (prefers-reduced-motion: reduce) {
.download-local-drop { transition: none; }
.download-playlist-help [role=tooltip], #download-video-picker, #torrent-file-picker { transition-duration: 0s !important; }
}
+76
View File
@@ -0,0 +1,76 @@
.download-torrent-panel, .torrent-session-detail { display: grid; gap: 8px; min-width: 0; }
.torrent-pane-empty { margin: 0; padding: 10px 0; color: var(--text-secondary); font-size: 13px; }
.torrent-selection-summary { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--text-secondary); font-size: 12px; }
.download-torrent-panel svg { width: 17px; height: 17px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
.download-torrent-panel :is(button, input, select, summary, [tabindex="0"]):focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.download-torrent-panel progress { display: block; width: min(140px, 100%); height: 3px; appearance: none; overflow: hidden; border: 0; border-radius: 4px; background: var(--bg-active); color: var(--accent); }
.download-torrent-panel progress::-webkit-progress-bar { background: var(--bg-active); }
.download-torrent-panel progress::-webkit-progress-value { background: var(--accent); }
.download-torrent-panel progress::-moz-progress-bar { background: var(--accent); }
.torrent-source-form {
flex: none; display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center;
width: 100%;
}
.torrent-source-form .torrent-input-label, .torrent-source-form > input { grid-column: 1 / -1; }
.torrent-source-form .torrent-input-label { margin: 0; color: var(--text-secondary); font-size: 13px; }
.torrent-source-form input[type="text"] { min-width: 0; width: 100%; margin: 0; }
.torrent-source-form .torrent-file-source {
position: relative; display: flex; align-items: center; gap: 8px; justify-self: start; min-width: 0; max-width: 100%; min-height: 36px;
margin: 0; padding: 4px 10px; border: 1px dashed var(--border-color); border-radius: 6px;
color: var(--text-secondary); cursor: pointer; font-size: 13px;
}
.torrent-file-source:hover, .torrent-source-form .torrent-file-source.picked { background: var(--bg-hover); color: var(--text-primary); }
.torrent-file-source:focus-within { outline: 2px solid var(--accent); outline-offset: 1px; }
.torrent-file-source input[type="file"] { position: absolute; inset: 0; opacity: 0; width: 100%; height: 100%; cursor: pointer; }
.torrent-file-source span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.torrent-file-source small { font-weight: 400; font-size: 12px; color: var(--text-secondary); }
.torrent-transfer-summary { display: flex; align-items: center; gap: 8px; color: var(--text-secondary); font-size: 12px; }
.torrent-node small { color: var(--text-secondary); font-size: 12px; font-variant-numeric: tabular-nums; }
.torrent-live-progress { display: flex; align-items: center; gap: 7px; margin-inline-start: auto; }
.torrent-live-progress progress { width: clamp(22px, 8vw, 100px); }
.torrent-transfer-info { position: relative; margin-inline-start: auto; }
.torrent-transfer-info summary { list-style: none; cursor: pointer; }
.torrent-transfer-info summary::-webkit-details-marker { display: none; }
.torrent-transfer-info dl { position: absolute; z-index: 4; inset: 100% 0 auto auto; width: min(260px, 65vw); margin: 0; padding: 8px 12px; border: 1px solid var(--bg-active); border-radius: 8px; background: var(--bg-elevated); box-shadow: 0 6px 22px #0007; }
.torrent-transfer-info dl > div { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; padding-block: 4px; font-size: 12px; }
.torrent-transfer-info dt { color: var(--text-secondary); }
.torrent-transfer-info dd { margin: 0; text-align: end; overflow-wrap: anywhere; }
.torrent-selection-tools {
display: flex; align-items: center; justify-content: space-between; gap: 8px; flex: none; min-height: 36px; padding: 0 6px;
background: var(--bg-elevated); border: 1px solid var(--border-color); border-bottom: 0; border-radius: 7px 7px 0 0;
}
.torrent-selection-tools .torrent-master-check { display: flex; align-items: center; gap: 8px; min-height: 36px; margin: 0; cursor: pointer; color: var(--text-secondary); font-size: 12px; font-weight: 500; font-variant-numeric: tabular-nums; }
.torrent-tree-controls { display: flex; }
.download-torrent-panel input[type="checkbox"] { flex: none; width: 16px; height: 16px; margin: 0; accent-color: var(--accent); cursor: pointer; }
.torrent-session-detail .torrent-file-tree {
max-height: min(42dvh, 350px); margin: 0; overflow: auto; overscroll-behavior: contain;
border: 1px solid var(--border-color); border-radius: 0 0 7px 7px; background: var(--bg-primary);
}
.torrent-file-tree .torrent-tree-row {
display: flex; align-items: stretch; gap: 0; min-height: 35px; padding: 0 9px 0 calc(4px + var(--depth, 0) * 12px);
border-bottom: 1px solid var(--border-color);
}
.torrent-file-tree .torrent-tree-row:last-child { border-bottom: 0; }
.torrent-file-tree .torrent-tree-row:hover { background: var(--bg-hover); }
.torrent-folder-toggle { display: grid; place-items: center; flex: none; width: 28px; padding: 0; border: 0; border-radius: 4px; color: var(--text-secondary); background: transparent; cursor: pointer; }
.torrent-folder-toggle:hover { background: var(--bg-hover); color: var(--text-primary); }
.torrent-folder-toggle svg { width: 14px; height: 14px; transition: transform 120ms ease; }
.torrent-folder-toggle[aria-expanded="true"] svg { transform: rotate(90deg); }
.torrent-file-tree .torrent-node { display: flex; align-items: center; flex: 1; gap: 8px; min-width: 0; margin: 0; color: var(--text-primary); cursor: pointer; font-size: 13px; font-weight: 400; }
.torrent-node span { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.torrent-node svg { color: var(--text-secondary); width: 15px; }
.torrent-node small { white-space: nowrap; }
.torrent-start-bar { display: flex; gap: 12px; align-items: end; justify-content: space-between; flex: none; padding: 10px 0 0; }
.torrent-start-bar .download-destination { flex: 1; min-width: 0; max-width: 510px; }
.torrent-start { flex: none; }
.torrent-loading { overflow: hidden; }
@media(max-width: 600px) {
.torrent-start, .torrent-file-source { min-height: 40px; }
.torrent-file-source small { display: none; }
.torrent-file-tree .torrent-tree-row { min-height: 40px; padding-inline-start: calc(2px + var(--depth, 0) * 6px); }
.torrent-folder-toggle { width: 32px; }
.torrent-selection-tools .torrent-master-check { min-height: 40px; }
.torrent-start-bar { display: grid; grid-template-columns: minmax(0, 1fr); gap: 6px; padding-top: 4px; }
.torrent-start-bar .download-destination { max-width: none; }
}
@media (prefers-reduced-motion: reduce) { .torrent-folder-toggle svg { transition: none; } }
+111
View File
@@ -0,0 +1,111 @@
<template x-if="manager.sourceTab === 'torrents'">
<section id="downloads-torrents" class="download-torrent-panel" role="tabpanel" aria-labelledby="downloads-tab-torrents"
x-data="{ get torrent() { return $store.torrents } }">
<template x-if="torrent.isImporting()">
<form class="torrent-source-form" @submit.prevent="torrent.preview()">
<label class="torrent-input-label" for="torrent-magnet-input">{{ t.player_magnet_link }}</label>
<input class="download-field" id="torrent-magnet-input" type="text" autocomplete="off" spellcheck="false" x-model="torrent.magnet"
:disabled="torrent.loading" @input="torrent.file = null" placeholder="magnet:?xt=urn:btih:…">
<label class="torrent-file-source" :class="{picked:torrent.file}">
<input type="file" id="torrent-file-input" accept=".torrent,application/x-bittorrent" :disabled="torrent.loading"
@change="if ($el.files.length) { torrent.file = $el.files[0]; torrent.magnet = ''; $el.value = '' }">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14 2H5v20h14V7ZM14 2v6h5M8 15h8m-4-4v8"/></svg>
<span x-text="torrent.file?.name || '{{ t.player_torrent_file }}'"></span>
<small>.torrent</small>
</label>
<button type="submit" class="download-button primary torrent-preview-submit" :disabled="torrent.loading || !(torrent.file || torrent.magnet.trim())">{{ t.player_upload_content }}</button>
</form>
</template>
<template x-if="torrent.workspaceMode === 'opening' || (torrent.isImporting() && torrent.loading)">
<div class="page-skeleton torrent-loading" role="status"><span class="loading-label">{{ t.player_loading_content }}</span>
{% include "player/skeleton_tracks.html" %}
</div>
</template>
<template x-if="torrent.workspaceMode === 'session' && torrent.previewData">
<div class="torrent-session-detail" x-data="{choosing:false}">
<div class="download-preview-title">
<h4 x-text="torrent.previewData.name" :title="torrent.previewData.name"></h4>
<button type="button" class="download-button" :disabled="torrent.loading"
@click="torrent.addNew(); $nextTick(() => document.getElementById('torrent-magnet-input')?.focus())">{{ t.player_download_another }}</button>
</div>
<template x-if="torrent.currentJob">
<div class="torrent-transfer-summary">
<span class="torrent-status-badge" :class="torrent.statusBadgeClass(torrent.currentJob)" x-text="torrent.statusLabel(torrent.currentJob)"></span>
<small x-text="torrent.progressDetailText(torrent.currentJob)"></small>
<span class="torrent-live-progress" x-show="torrent.isCurrentDownloading()">
<progress max="100" :value="torrent.progressValue(torrent.currentJob)" :aria-label="torrent.statusLabel(torrent.currentJob)"></progress>
<small x-text="torrent.progressValue(torrent.currentJob).toFixed(0) + '%'"></small>
</span>
<details class="torrent-transfer-info" @click.outside="$el.open = false"
@keydown.escape="if ($el.open) { $event.stopPropagation(); $event.preventDefault(); $el.open = false; $refs.info.focus() }">
<summary class="download-icon-button" x-ref="info" title="{{ t.player_info }}" aria-label="{{ t.player_info }}">
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 11v6m0-10v1"/></svg>
</summary>
<dl>
<div><dt>{{ t.player_status }}</dt><dd x-text="torrent.statusText(torrent.currentJob)"></dd></div>
<div><dt>{{ t.player_size }}</dt><dd x-text="torrent.bytes(torrent.previewData.total_size)"></dd></div>
<div x-show="!torrent.isCurrentCompleted()"><dt>{{ t.player_speed }}</dt><dd x-text="torrent.speedText(torrent.currentJob)"></dd></div>
<div x-show="!torrent.isCurrentCompleted()"><dt>{{ t.player_peers }}</dt><dd x-text="torrent.peerText(torrent.currentJob)"></dd></div>
<div x-show="torrent.etaText(torrent.currentJob)"><dt>{{ t.player_eta }}</dt><dd x-text="torrent.etaText(torrent.currentJob)"></dd></div>
</dl>
</details>
</div>
</template>
<div class="torrent-selection-summary" x-show="torrent.previewData.files.length">
<span x-text="torrent.selected.size + ' / ' + torrent.previewData.files.length + ' · ' + torrent.bytes(torrent.selectedBytes())"></span>
<button type="button" class="download-button torrent-choose-files" :aria-expanded="choosing" aria-controls="torrent-file-picker"
@click="if (!torrent.treeRoot) torrent.treeRoot=torrent._buildTree(torrent.previewData.files); choosing=!choosing">{{ t.player_choose_audio_files }}</button>
</div>
<template x-if="!torrent.previewData.files.length && torrent.normalizedStatus(torrent.currentJob) === 'resolving'">
<div class="page-skeleton" role="status"><span class="loading-label">{{ t.player_resolving }}</span>{% include "player/skeleton_tracks.html" %}</div>
</template>
<p class="torrent-pane-empty" x-show="!torrent.previewData.files.length && torrent.normalizedStatus(torrent.currentJob) !== 'resolving'">{{ t.player_no_torrent_files }}</p>
<div id="torrent-file-picker" x-show="choosing" x-transition.opacity.duration.130ms>
<template x-if="torrent.treeRoot"><div class="torrent-file-picker">
<div class="torrent-selection-tools">
<label class="torrent-master-check">
<input type="checkbox" :checked="torrent.selected.size > 0 && torrent.selected.size === torrent.previewData.files.length"
x-effect="$el.indeterminate = torrent.selected.size > 0 && torrent.selected.size < torrent.previewData.files.length"
@change="torrent.selectAll($el.checked)" aria-label="{{ t.player_youtube_select_all }}">
<span>{{ t.player_youtube_select_all }}</span>
</label>
<div class="torrent-tree-controls" x-show="torrent.treeRoot?.children.some(node => node.type === 'folder')">
<button type="button" class="download-icon-button" @click="torrent.expandAll(true)" title="{{ t.player_expand_all }}" aria-label="{{ t.player_expand_all }}">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m7 8 5-5 5 5m-5-5v7m-5 6 5 5 5-5m-5 5v-7"/></svg>
</button>
<button type="button" class="download-icon-button" @click="torrent.expandAll(false)" title="{{ t.player_collapse }}" aria-label="{{ t.player_collapse }}">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m7 5 5 5 5-5m-5 5V2m-5 17 5-5 5 5m-5-5v8"/></svg>
</button>
</div>
</div>
<div class="torrent-file-tree" tabindex="0" role="region" aria-label="{{ t.player_files }}">
<template x-for="node in torrent.visibleNodes()" :key="node.key">
<div class="torrent-tree-row" :style="{'--depth': Math.min(node.depth, 5)}">
<button type="button" class="torrent-folder-toggle" :style="node.type === 'folder' ? null : 'visibility:hidden'"
:aria-label="(torrent.expanded.has(node.key) ? '{{ t.player_collapse }}' : '{{ t.player_expand }}') + ' · ' + node.name"
:aria-expanded="torrent.expanded.has(node.key)" @click="torrent.toggleExpand(node)">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9 5 7 7-7 7"/></svg>
</button>
<label class="torrent-node" :title="node.name">
<input type="checkbox" :checked="torrent.nodeState(node) === 'checked'" x-effect="$el.indeterminate = torrent.nodeState(node) === 'partial'"
@change="torrent.toggleNode(node)">
<svg x-show="node.type === 'folder'" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 6h7l2 3h9v11H3Z"/></svg>
<span x-text="node.name"></span>
<small x-text="torrent.bytes(node.size)"></small>
</label>
</div>
</template>
</div>
</div></template>
</div>
<footer class="torrent-start-bar">
{% let kind = "torrent" %}{% include "player/download_destination.html" %}
<button type="button" class="download-button torrent-start" :class="{primary:!torrent.isCurrentDownloading() && !torrent.isCurrentCompletedLocked()}"
@click="await torrent.toggleDownloadAction(); if (torrent.isCurrentDownloading()) choosing=false"
:disabled="torrent.actionButtonDisabled()" x-text="torrent.actionButtonText()"></button>
</footer>
</div>
</template>
</section>
</template>
+76
View File
@@ -0,0 +1,76 @@
<template x-if="manager.sourceTab === 'youtube'">
<section id="downloads-youtube" class="download-source-pane" role="tabpanel" aria-labelledby="downloads-tab-youtube">
<template x-if="manager.youtubeDetail">
<div class="download-source-detail">
<div class="download-preview-title">
<h4 x-text="manager.youtubeDetail.title"></h4>
<span class="torrent-status-badge" :class="manager.youtubeStatusClass(manager.youtubeDetail.status)" x-text="manager.youtubeStatusLabel(manager.youtubeDetail.status)"></span>
</div>
<p x-show="manager.youtubeDetail.error" x-text="manager.youtubeDetail.error" class="download-source-error"></p>
<div class="download-selection-actions">
<button type="button" class="download-button" x-show="manager.youtubeJobCancellable(manager.youtubeDetail.status)" :disabled="manager.youtubeActionBusy"
@click="manager.cancelYoutubeJob(manager.youtubeDetail.id)">{{ t.player_youtube_stop }}</button>
<button type="button" class="download-button" x-show="['failed','complete_with_errors'].includes(manager.youtubeDetail.status)" :disabled="manager.youtubeActionBusy"
@click="manager.retryYoutubeJob(manager.youtubeDetail.id)">{{ t.player_retry_failed }}</button>
<button type="button" class="download-button" @click="manager.youtubeDetail=null; $nextTick(() => $refs.urlInput.focus())">{{ t.player_download_another }}</button>
</div>
</div>
</template>
<form x-show="!manager.youtubeDetail" class="download-link-form" @submit.prevent="$store.torrents.previewYoutubeUrl()">
<label for="youtube-download-url">{{ t.player_youtube_url }}</label>
<div class="download-link-controls">
<input x-ref="urlInput" class="download-field" id="youtube-download-url" type="text" inputmode="url" autocomplete="url"
spellcheck="false" x-model="$store.torrents.youtubeUrl" @input="$store.torrents.clearYoutubePreview()"
placeholder="https://youtu.be/…" :readonly="$store.torrents.youtubeSubmitting">
<button class="download-button primary" type="submit"
:disabled="$store.torrents.youtubePreviewLoading || $store.torrents.youtubeSubmitting || !$store.torrents.youtubeUrl.trim()">
{{ t.player_youtube_parse }}
</button>
</div>
</form>
<template x-if="!manager.youtubeDetail && manager.youtubePreviewLoading">
<div class="page-skeleton" aria-label="{{ t.player_youtube_parsing }}" aria-busy="true">{% include "player/skeleton_tracks.html" %}</div>
</template>
<template x-if="!manager.youtubeDetail && manager.youtubePreview">
<div class="download-video-preview" x-data="{choosing:false, visited:false}">
<div class="download-preview-title">
<h4 x-text="$store.torrents.youtubePreview.title"></h4>
<span x-text="$store.torrents.youtubePreviewSelectedCount() + ' / ' + $store.torrents.youtubePreview.items.length"></span>
</div>
<button type="button" class="download-button download-choose-videos" x-show="manager.youtubePreview.items.length > 1 || !manager.youtubePreviewSelectedCount() || choosing"
:aria-expanded="choosing" aria-controls="download-video-picker" @click="visited=true; choosing=!choosing">{{ t.player_youtube_preview_title }}</button>
<div id="download-video-picker" x-show="choosing" x-transition.opacity.duration.130ms>
<template x-if="visited"><div class="download-video-picker">
<label class="download-video-all">
<input type="checkbox" :disabled="$store.torrents.youtubeSubmitting"
:checked="$store.torrents.youtubePreviewSelectedCount() === $store.torrents.youtubePreview.items.length"
x-effect="$el.indeterminate = $store.torrents.youtubePreviewSelectedCount() > 0 && $store.torrents.youtubePreviewSelectedCount() < $store.torrents.youtubePreview.items.length"
@change="$el.checked ? $store.torrents.selectAllYoutubePreview() : $store.torrents.clearYoutubePreviewSelection()">
<span>{{ t.player_youtube_select_all }}</span>
</label>
<div class="download-video-list" role="group" aria-label="{{ t.player_youtube_preview_title }}">
<template x-for="item in $store.torrents.youtubePreview.items" :key="item.source_id">
<label class="download-video-row">
<input type="checkbox" :disabled="$store.torrents.youtubeSubmitting"
:checked="$store.torrents.youtubePreviewIsSelected(item.source_id)"
@change="$store.torrents.toggleYoutubePreviewItem(item.source_id)">
<span class="download-video-index" x-text="item.playlist_index"></span>
<span x-text="item.title"></span>
</label>
</template>
</div>
</div>
</template>
</div>
{% let kind = "youtube" %}
{% include "player/download_destination.html" %}
<div class="download-selection-actions">
<button type="button" class="download-button" :disabled="$store.torrents.youtubeSubmitting"
@click="$store.torrents.clearYoutubePreview()">{{ t.player_cancel }}</button>
<button type="button" class="download-button primary" @click="$store.torrents.startYoutubeDownload()"
:disabled="$store.torrents.youtubeSubmitting || !$store.torrents.youtubePreviewSelectedCount() || !$store.torrents.youtubeDestinationValid()">{{ t.player_youtube_start_import }}</button>
</div>
</div>
</template>
</section>
</template>
+83
View File
@@ -0,0 +1,83 @@
.get-app-body {
display: grid;
gap: 12px;
padding: var(--dialog-gutter);
}
.get-app-client {
min-width: 0;
padding: 14px;
border: 1px solid var(--border-color);
border-radius: 12px;
}
.get-app-client h3, .get-app-guide h4 {
margin: 0;
font-size: 1rem;
}
.get-app-client-type, .get-app-guide p {
margin: 4px 0 0;
color: var(--text-secondary);
font-size: .875rem;
line-height: 1.5;
}
.get-app-tiles {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
margin-top: 12px;
}
.get-app-tile {
display: grid;
justify-items: center;
align-content: center;
gap: 6px;
min-height: 66px;
padding: 8px 4px;
border: 1px solid var(--border-color);
border-radius: 8px;
background: var(--bg-elevated);
color: var(--text-primary);
font: inherit;
font-size: .8125rem;
cursor: pointer;
}
.get-app-tile svg { width: 22px; height: 22px; fill: currentColor; }
.get-app-tile:hover { background: var(--bg-active); }
.get-app-tile[aria-expanded="true"] { border-color: var(--accent); }
.get-app-tile:focus-visible, .get-app-links a:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.get-app-guides { display: grid; }
.get-app-guide {
grid-area: 1 / 1;
min-width: 0;
margin-top: 12px;
padding: 12px;
border-radius: 8px;
background: var(--bg-elevated);
}
.get-app-guide[inert] { pointer-events: none; }
.get-app-guide pre {
margin: 8px 0 0;
padding: 8px 10px;
border-radius: 6px;
background: var(--bg-secondary);
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: .8125rem;
}
.get-app-links { display: flex; flex-wrap: wrap; gap: 6px 16px; margin-top: 10px; }
.get-app-links a {
color: var(--text-primary);
font-size: .875rem;
text-decoration: underline;
text-underline-offset: 3px;
}
@media (max-width: 480px) {
.get-app-tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (prefers-reduced-motion: no-preference) {
.get-app-tile { transition: background-color 140ms, border-color 140ms; }
.get-app-guide-enter, .get-app-guide-leave { transition: opacity 140ms, transform 140ms; }
.get-app-guide-hidden { opacity: 0; transform: translateY(-3px); }
}
+18
View File
@@ -0,0 +1,18 @@
<template x-if="$store.user.getAppOpen">
<dialog id="get-app-dialog" class="player-dialog" aria-labelledby="get-app-title" style="--dialog-width: 570px"
x-data x-init="$nextTick(() => { if ($el.isConnected) { $el.showModal(); document.getElementById('get-app-title').focus() } })"
@dismiss-player-dialog.stop="$store.user.closeGetApp($el)"
@cancel.prevent="$store.user.closeGetApp($el)" @click.self="$store.user.closeGetApp($el)" @keydown.space.stop>
<div class="player-dialog-surface">
{% let dialog_head_class = "" %}
{% let dialog_title_id = "get-app-title" %}
{% let dialog_title = t.player_get_app %}
{% let dialog_icon = "M12 3v12m-4-4 4 4 4-4M4 16v4h16v-4" %}
{% let show_version = false %}
{% include "player/dialog_header.html" %}
<div class="get-app-body">
{% include "player/get_app_tui.html" %}
</div>
</div>
</dialog>
</template>
+27
View File
@@ -0,0 +1,27 @@
{% macro tile(guide, label, icon) %}
<button class="get-app-tile" type="button" aria-controls="{{ guide }}"
:aria-expanded="activeGuide === $el.getAttribute('aria-controls')"
@click="const guide = $el.getAttribute('aria-controls'); activeGuide = activeGuide === guide ? null : guide">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="{{ icon }}"/></svg>
{{ label }}
</button>
{% endmacro %}
{% macro guide(id, title, description, command, link, link_label, extra_link, extra_label) %}
<section class="get-app-guide" id="{{ id }}" x-cloak
x-show="activeGuide === $el.id" :inert="activeGuide === $el.id ? null : true"
x-transition:enter="get-app-guide-enter" x-transition:enter-start="get-app-guide-hidden"
x-transition:leave="get-app-guide-leave" x-transition:leave-end="get-app-guide-hidden">
<h4>{{ title }}</h4>
<p>{{ description }}</p>
{% if !command.is_empty() %}
<pre><code>{{ command }}</code></pre>
{% endif %}
<div class="get-app-links">
<a href="{{ link }}" target="_blank" rel="noopener noreferrer">{{ link_label }}</a>
{% if !extra_link.is_empty() %}
<a href="{{ extra_link }}" target="_blank" rel="noopener noreferrer">{{ extra_label }}</a>
{% endif %}
</div>
</section>
{% endmacro %}
+18
View File
@@ -0,0 +1,18 @@
{% import "player/get_app_platform.html" as platform %}
{% let releases = "https://github.com/Furumi-stack/furumi-tui/releases/latest" %}
<section class="get-app-client" aria-labelledby="get-app-tui-title" x-data="{ activeGuide: null }">
<h3 id="get-app-tui-title">Furumi TUI</h3>
<p class="get-app-client-type">{{ t.player_app_terminal_client }}</p>
<div class="get-app-tiles">
{% call platform::tile("get-app-tui-arch", "Arch Linux", "M12 2 9.2 8.6l1.5 1.8-2.1-.6L3 21c2.5-1.5 4.9-2.5 7-2.9-.2-.5-.3-1-.3-1.6 0-1.7 1-3 2.3-3s2.3 1.3 2.3 3c0 .6-.1 1.1-.3 1.6 2.1.4 4.5 1.4 7 2.9l-3.6-7.2-2.5-1.5 1.8.3z") %}{% endcall %}
{% call platform::tile("get-app-tui-macos", "macOS", "M17.1 12.3c0-1.8.9-3.1 2.4-4-1-1.4-2.4-2.1-4.2-2.2-1.7-.1-2.7 1-3.6 1-.9 0-2.2-1-3.6-1C5.6 6.2 3 8.2 3 12c0 2.1.8 4.4 1.9 6 1 1.5 2 3 3.6 3 1.5 0 2-1 3.7-1s2.1 1 3.7 1 2.6-1.4 3.6-2.9c.7-1 1.1-2.1 1.4-2.9-2.2-.9-3.8-2-3.8-3zm-2.6-7.6c.8-1 1.3-2.2 1.2-3.5-1.2.1-2.6.8-3.4 1.8-.8.9-1.4 2.2-1.3 3.4 1.3.1 2.7-.7 3.5-1.7z") %}{% endcall %}
{% call platform::tile("get-app-tui-windows", "Windows", "M3 3h8v8H3zm10 0h8v8h-8zM3 13h8v8H3zm10 0h8v8h-8z") %}{% endcall %}
{% call platform::tile("get-app-tui-binaries", t.player_app_binaries, "M11 3h2v10l3.5-3.5L18 11l-6 6-6-6 1.5-1.5L11 13zm-7 15h2v2h12v-2h2v4H4z") %}{% endcall %}
</div>
<div class="get-app-guides">
{% call platform::guide("get-app-tui-arch", "Arch Linux", t.player_app_arch_guide, "./furumi", releases, t.player_app_latest_release, "https://github.com/house-of-vanity/arch_repo", t.player_app_arch_repo) %}{% endcall %}
{% call platform::guide("get-app-tui-macos", "macOS · Homebrew", t.player_app_macos_guide, "brew install house-of-vanity/tap/furumi\nfurumi", "https://github.com/house-of-vanity/homebrew-tap", "Homebrew tap", "", "") %}{% endcall %}
{% call platform::guide("get-app-tui-windows", "Windows", t.player_app_windows_guide, ".\\furumi.exe", releases, t.player_app_latest_release, "", "") %}{% endcall %}
{% call platform::guide("get-app-tui-binaries", t.player_app_binaries, t.player_app_binary_guide, "", releases, t.player_app_latest_release, "", "") %}{% endcall %}
</div>
</section>
+263
View File
@@ -0,0 +1,263 @@
<template x-if="$store.library.view === 'imports'">
<section class="library-imports" x-data="{ get imports() { return $store.imports } }"
@keydown.space="if ($event.target.closest('button,a,input,select,label')) $event.stopPropagation()">
<header class="import-heading">
<h1 class="section-title">{{ t.player_import_library }}</h1>
<button type="button" class="release-action-btn primary" data-online-only @click="imports.startWizard()"
aria-haspopup="dialog" aria-controls="import-wizard">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
{{ t.player_import_new }}
</button>
</header>
<p class="import-notice" role="status" aria-live="polite" x-show="imports.message" x-text="imports.message"></p>
<div class="import-notice error" role="alert" x-show="imports.error" x-cloak>
<span x-text="imports.error"></span>
<button type="button" class="import-text-action" @click="imports.enter()">{{ t.player_import_retry }}</button>
</div>
<template x-if="!imports.loaded && !imports.error">
<div class="page-skeleton" role="status">
<span class="loading-label">{{ t.player_loading_content }}</span>
<div aria-hidden="true">
<div class="import-source-grid">
<div class="import-source skeleton-card"><i class="skeleton-bar"></i><i class="skeleton-bar"></i></div>
</div>
</div>
{% include "player/skeleton_tracks.html" %}
</div>
</template>
<template x-if="imports.loaded">
<div>
<h2 class="import-subtitle">{{ t.player_import_sources }}</h2>
<div class="import-source-grid">
<template x-for="provider in imports.providers" :key="provider.id">
<button type="button" class="import-source" data-online-only @click="imports.startWizard(provider.id)"
aria-haspopup="dialog" aria-controls="import-wizard">
<strong x-text="provider.name"></strong>
<small x-text="provider.methods.map(method => imports.text(method === 'api' ? 'methodApi' : 'methodFile')).join(' · ')"></small>
</button>
</template>
</div>
<h2 class="import-subtitle">{{ t.player_import_history }}</h2>
<p class="empty-state" x-show="!imports.imports.length">{{ t.player_import_history_empty }}</p>
<ul class="import-history" x-show="imports.imports.length">
<template x-for="record in imports.imports" :key="record.id">
<li class="import-history-row">
<a class="import-history-link" :href="'#imports/' + record.id">
<span class="import-history-title">
<strong x-text="imports.title(record)"></strong>
<small x-text="imports.date(record.created_at)"></small>
</span>
<span class="import-status" :data-status="record.status" x-text="imports.statusText(record)"></span>
<span class="import-history-count"
x-text="imports.text('foundOf', {found: imports.number(imports.found(record)), total: imports.number(imports.stats(record).total)})"></span>
</a>
<div class="import-history-playlists" x-show="imports.playlistLinks(record).length">
<template x-for="link in imports.playlistLinks(record).slice(0, 3)" :key="link.id">
<a :href="'#playlist/' + link.target_playlist_id" x-text="link.title"></a>
</template>
<span x-show="imports.playlistLinks(record).length > 3"
x-text="imports.text('playlistsMore', {count: imports.playlistLinks(record).length - 3})"></span>
</div>
<div class="import-history-actions" data-online-only>
<button type="button" class="import-text-action" x-show="imports.isFinished(record)"
:disabled="imports.busy" @click="imports.retry(record)">{{ t.player_import_retry_unmatched }}</button>
<button type="button" class="import-text-action" x-show="record.status === 'needs_reauth'"
@click="imports.reauthorize(record)">{{ t.player_import_sign_in_again }}</button>
</div>
</li>
</template>
</ul>
</div>
</template>
</section>
</template>
<template x-if="$store.library.view === 'import_detail'">
<section class="library-imports" x-data="{ get imports() { return $store.imports }, get detail() { return $store.imports.detail } }"
@keydown.space="if ($event.target.closest('button,a,input,select,label')) $event.stopPropagation()">
<nav class="breadcrumb" aria-label="{{ t.player_import_library }}">
<a href="#imports">{{ t.player_import_library }}</a>
</nav>
<div class="import-notice error" role="alert" x-show="imports.detailError" x-cloak>
<span x-text="imports.detailError"></span>
<button type="button" class="import-text-action" @click="imports.open(imports.detailId)">{{ t.player_import_retry }}</button>
</div>
<template x-if="!detail && !imports.detailError">
<div class="page-skeleton" role="status">
<span class="loading-label">{{ t.player_loading_content }}</span>
<div aria-hidden="true">
<i class="skeleton-bar skeleton-title"></i>
<i class="skeleton-bar skeleton-byline"></i>
<div class="import-stats import-stats-skeleton">
{% for _ in 0..6 %}<div><i class="skeleton-bar"></i><i class="skeleton-bar"></i></div>{% endfor %}
</div>
</div>
{% include "player/skeleton_tracks.html" %}
</div>
</template>
<template x-if="detail">
<div>
<header class="import-heading">
<div class="import-heading-copy">
<h1 class="section-title" x-text="imports.title(detail)"></h1>
<p>
<span class="import-status" :data-status="detail.status" x-text="imports.statusText(detail)"></span>
<span x-text="imports.date(detail.created_at)"></span>
</p>
</div>
<div class="import-actions" data-online-only>
<button type="button" class="release-action-btn primary" x-show="detail.status === 'needs_reauth'"
@click="imports.reauthorize()">{{ t.player_import_sign_in_again }}</button>
<button type="button" class="release-action-btn secondary" x-show="imports.isFinished(detail)"
:disabled="imports.busy" :aria-expanded="imports.retryPanel" aria-controls="import-retry-panel"
@click="imports.openRetry()">{{ t.player_import_retry_unmatched }}</button>
<button type="button" class="release-action-btn secondary" x-show="imports.isActive(detail) || detail.status === 'needs_reauth'"
:disabled="imports.busy || detail.cancel_requested" @click="imports.cancel()">{{ t.player_import_cancel }}</button>
<button type="button" class="release-action-btn secondary" x-show="!imports.isActive(detail)"
:disabled="imports.busy" @click="imports.remove()">{{ t.player_import_delete_history }}</button>
</div>
</header>
<div id="import-retry-panel" class="import-retry-panel" x-show="imports.retryPanel" x-cloak
x-transition.opacity.duration.140ms>
<div class="import-consent">
<button type="button" role="switch" class="offline-switch-row" :aria-checked="imports.retryFederated"
:disabled="!imports.federatedAvailable" aria-labelledby="import-retry-federated"
aria-describedby="import-retry-consent" @click="imports.retryFederated = !imports.retryFederated">
<span class="offline-switch" aria-hidden="true"></span>
</button>
<span>
<strong id="import-retry-federated">{{ t.player_import_federated }}</strong>
<small id="import-retry-consent" x-text="imports.federatedAvailable ? imports.text('federatedConsent') : imports.text('federatedOff')"></small>
</span>
</div>
<button type="button" class="release-action-btn primary" :disabled="imports.busy"
@click="imports.retry(detail, imports.federatedAvailable ? imports.retryFederated : undefined)">{{ t.player_import_retry }}</button>
</div>
<p class="import-notice" role="status" aria-live="polite" x-show="imports.message || imports.notice"
x-text="imports.message || imports.notice"></p>
<p class="import-notice" x-show="detail.status === 'needs_reauth'">{{ t.player_import_reauth_needed }}</p>
<p class="import-notice error" x-show="detail.error" x-text="detail.error"></p>
<div class="import-progress" x-show="imports.isActive(detail)" x-cloak>
<span x-text="imports.phaseText(detail)"></span>
<template x-if="imports.progress(detail).max">
<progress :max="imports.progress(detail).max" :value="imports.progress(detail).value"
:aria-label="imports.phaseText(detail)"></progress>
</template>
<template x-if="!imports.progress(detail).max">
<progress :aria-label="imports.phaseText(detail)"></progress>
</template>
</div>
<dl class="import-stats">
<div><dt>{{ t.player_import_stat_total }}</dt><dd x-text="imports.number(imports.stats(detail).total)"></dd></div>
<div>
<dt>{{ t.player_import_stat_found }}</dt>
<dd x-text="imports.number(imports.found(detail))"></dd>
<small x-text="imports.text('local') + ' ' + imports.number(imports.stats(detail).matched_local) + ' · ' + imports.text('federation') + ' ' + imports.number(imports.stats(detail).matched_federation)"></small>
</div>
<div><dt>{{ t.player_import_stat_published }}</dt><dd x-text="imports.number(imports.stats(detail).published)"></dd></div>
<div><dt>{{ t.player_import_stat_ambiguous }}</dt><dd x-text="imports.number(imports.stats(detail).ambiguous)"></dd></div>
<div><dt>{{ t.player_import_stat_unmatched }}</dt><dd x-text="imports.number(imports.stats(detail).unmatched)"></dd></div>
<div><dt>{{ t.player_import_stat_unsupported }}</dt><dd x-text="imports.number(imports.stats(detail).unsupported)"></dd></div>
</dl>
<ul class="import-extra-stats" x-show="imports.extraStats().length">
<template x-for="stat in imports.extraStats()" :key="stat.key">
<li><span x-text="stat.label"></span> <strong x-text="imports.number(stat.value)"></strong></li>
</template>
</ul>
<h2 class="import-subtitle">{{ t.player_import_playlists }}</h2>
<ul class="import-playlists">
<template x-for="playlist in detail.source_playlists" :key="playlist.id">
<li class="collection-row">
<template x-if="playlist.target_playlist_id && !playlist.target_deleted">
<a class="collection-link" :href="'#playlist/' + playlist.target_playlist_id">
<span class="collection-art" :class="{likes: playlist.kind === 'favorites'}" aria-hidden="true"
x-text="playlist.kind === 'favorites' ? '♥' : '♫'"></span>
<span><strong x-text="playlist.title"></strong>
<small x-text="imports.text('foundOf', {found: imports.number(playlist.matched), total: imports.number(playlist.total)}) + ' · ' + imports.text('statPublished') + ' ' + imports.number(playlist.published)"></small></span>
</a>
</template>
<template x-if="!playlist.target_playlist_id || playlist.target_deleted">
<div class="collection-link">
<span class="collection-art" aria-hidden="true" x-text="playlist.kind === 'favorites' ? '♥' : '♫'"></span>
<span><strong x-text="playlist.title"></strong>
<small x-text="playlist.target_deleted ? imports.text('playlistDeleted') : imports.text('playlistPending')"></small></span>
</div>
</template>
<button type="button" class="import-text-action" data-online-only x-show="playlist.target_deleted && !imports.isActive(detail)"
:disabled="imports.busy" @click="imports.recreate(playlist)">{{ t.player_import_recreate }}</button>
</li>
</template>
</ul>
<h2 class="import-subtitle">{{ t.player_import_entries }}</h2>
<div class="import-filters">
<div class="collection-tabs" role="group" aria-label="{{ t.player_import_entries }}">
<template x-for="option in imports.statusFilters()" :key="option.status">
<button type="button" :aria-pressed="imports.filter.status === option.status"
@click="imports.setStatus(option.status)"
x-text="option.label + ' ' + imports.number(option.count)"></button>
</template>
</div>
<div class="import-filter-fields">
<select aria-label="{{ t.player_import_playlists }}" x-show="detail.source_playlists.length > 1"
:value="imports.filter.playlist" @change="imports.setPlaylist($event.target.value)">
<option value="">{{ t.player_import_all_playlists }}</option>
<template x-for="playlist in detail.source_playlists" :key="playlist.id">
<option :value="String(playlist.id)" x-text="playlist.title"></option>
</template>
</select>
<input type="search" placeholder="{{ t.player_import_search }}" aria-label="{{ t.player_import_search }}"
maxlength="200" x-model="imports.filter.q" @input="imports.searchChanged()">
</div>
</div>
<template x-if="!imports.itemsLoaded">
<div class="page-skeleton" role="status">
<span class="loading-label">{{ t.player_loading_content }}</span>
{% include "player/skeleton_tracks.html" %}
</div>
</template>
<p class="empty-state" x-show="imports.itemsLoaded && !imports.items.length">{{ t.player_import_no_entries }}</p>
<ol class="import-items" x-show="imports.items.length" :aria-busy="imports.itemsLoading">
<template x-for="item in imports.items" :key="item.id">
<li class="import-item" :data-status="item.resolution_status">
<span class="import-item-position" x-text="item.position + 1"></span>
<div class="import-item-copy">
<strong x-text="imports.meta(item).title || '—'"></strong>
<small x-text="[imports.artists(imports.meta(item).artists), imports.meta(item).album].filter(Boolean).join(' · ')"></small>
<small class="import-item-note" x-show="!imports.filter.playlist && detail.source_playlists.length > 1"
x-text="imports.playlistTitle(item.playlist_id)"></small>
</div>
<span class="import-item-duration" x-text="imports.duration(imports.meta(item).duration_ms)"></span>
<span class="import-item-status">
<span class="import-status" :data-status="item.resolution_status" x-text="imports.resolutionText(item)"></span>
<small x-show="imports.noteText(item) || imports.publicationText(item)"
x-text="imports.noteText(item) || imports.publicationText(item)"></small>
</span>
<template x-if="item.resolution_status === 'ambiguous' && item.candidates?.length">
<div class="import-candidates">
<span class="import-candidates-title">{{ t.player_import_candidates }}</span>
<template x-for="(candidate, index) in item.candidates" :key="index">
<div class="import-candidate">
<div class="import-item-copy">
<strong x-text="candidate.title"></strong>
<small x-text="[imports.artists(candidate.artists), candidate.album].filter(Boolean).join(' · ')"></small>
</div>
<span class="import-item-duration" x-text="candidate.duration_seconds ? formatTime(candidate.duration_seconds) : ''"></span>
<span class="import-origin" x-text="imports.text(candidate.origin === 'federation' ? 'federation' : 'local')"></span>
<button type="button" class="import-text-action" data-online-only
:disabled="!!imports.choosing || imports.isActive(detail)"
@click="imports.choose(item, index)">{{ t.player_import_choose }}</button>
</div>
</template>
</div>
</template>
</li>
</template>
</ol>
<div class="import-more" x-show="imports.itemsNext">
<button type="button" class="release-action-btn secondary" :disabled="imports.itemsLoading"
@click="imports.loadItems(true).catch(error => { imports.message = error.message })"
x-text="imports.itemsLoading ? imports.text('loading') : imports.text('loadMore')"></button>
</div>
</div>
</template>
</section>
</template>
+825
View File
@@ -0,0 +1,825 @@
<script>
document.addEventListener('alpine:init', () => {
const labels = {
title: "{{ t.player_import_library }}",
newImport: "{{ t.player_import_new }}",
sources: "{{ t.player_import_sources }}",
history: "{{ t.player_import_history }}",
historyEmpty: "{{ t.player_import_history_empty }}",
loadFailed: "{{ t.player_import_load_failed }}",
failed: "{{ t.player_import_request_failed }}",
retry: "{{ t.player_import_retry }}",
methodFile: "{{ t.player_import_method_file }}",
methodFileHint: "{{ t.player_import_method_file_hint }}",
methodApi: "{{ t.player_import_method_api }}",
methodApiHint: "{{ t.player_import_method_api_hint }}",
chooseFiles: "{{ t.player_import_choose_files }}",
reading: "{{ t.player_import_reading }}",
filesRead: "{{ t.player_import_files_read }}",
filesSkipped: "{{ t.player_import_files_skipped }}",
noFiles: "{{ t.player_import_no_files }}",
archiveTooLarge: "{{ t.player_import_archive_too_large }}",
zipTooManyEntries: "{{ t.player_import_zip_too_many_entries }}",
zipTooManyFiles: "{{ t.player_import_zip_too_many_files }}",
exportTooLarge: "{{ t.player_import_export_too_large }}",
zipInvalid: "{{ t.player_import_zip_invalid }}",
zipLoadFailed: "{{ t.player_import_zip_load_failed }}",
requestTooLarge: "{{ t.player_import_request_too_large }}",
signIn: "{{ t.player_import_sign_in }}",
signInAgain: "{{ t.player_import_sign_in_again }}",
loadingPlaylists: "{{ t.player_import_loading_playlists }}",
selectPlaylists: "{{ t.player_import_select_playlists }}",
selectAll: "{{ t.player_import_select_all }}",
selectNone: "{{ t.player_import_select_none }}",
selectedCount: "{{ t.player_import_selected_count }}",
favorites: "{{ t.player_import_favorites }}",
unsupportedCount: "{{ t.player_import_unsupported_count }}",
alreadyImported: "{{ t.player_import_already_imported }}",
allImported: "{{ t.player_import_all_imported }}",
similar: "{{ t.player_import_similar }}",
confirmSimilar: "{{ t.player_import_confirm_similar }}",
confirmSimilarNeeded: "{{ t.player_import_confirm_similar_needed }}",
unavailable: "{{ t.player_import_unavailable }}",
federated: "{{ t.player_import_federated }}",
federatedConsent: "{{ t.player_import_federated_consent }}",
federatedOff: "{{ t.player_import_federated_off }}",
start: "{{ t.player_import_start }}",
starting: "{{ t.player_import_starting }}",
back: "{{ t.player_import_back }}",
conflicts: "{{ t.player_import_conflicts }}",
similarConflicts: "{{ t.player_import_similar_conflicts }}",
status_queued: "{{ t.player_import_status_queued }}",
status_running: "{{ t.player_import_status_running }}",
status_done: "{{ t.player_import_status_done }}",
status_cancelled: "{{ t.player_import_status_cancelled }}",
status_failed: "{{ t.player_import_status_failed }}",
status_needs_reauth: "{{ t.player_import_status_needs_reauth }}",
status_cancelling: "{{ t.player_import_status_cancelling }}",
phase_fetching: "{{ t.player_import_phase_fetching }}",
phase_resolve_local: "{{ t.player_import_phase_resolve_local }}",
phase_resolve_federation: "{{ t.player_import_phase_resolve_federation }}",
phase_publish: "{{ t.player_import_phase_publish }}",
phase_waiting: "{{ t.player_import_phase_waiting }}",
foundOf: "{{ t.player_import_found_of }}",
number: "{{ t.player_import_number }}",
playlistsMore: "{{ t.player_import_playlists_more }}",
retryUnmatched: "{{ t.player_import_retry_unmatched }}",
retryStarted: "{{ t.player_import_retry_started }}",
cancel: "{{ t.player_import_cancel }}",
cancelRequested: "{{ t.player_import_cancel_requested }}",
deleteHistory: "{{ t.player_import_delete_history }}",
deleteConfirm: "{{ t.player_import_delete_confirm }}",
deleted: "{{ t.player_import_deleted }}",
reauthNeeded: "{{ t.player_import_reauth_needed }}",
statTotal: "{{ t.player_import_stat_total }}",
statFound: "{{ t.player_import_stat_found }}",
statPublished: "{{ t.player_import_stat_published }}",
statAmbiguous: "{{ t.player_import_stat_ambiguous }}",
statUnmatched: "{{ t.player_import_stat_unmatched }}",
statUnsupported: "{{ t.player_import_stat_unsupported }}",
statFailed: "{{ t.player_import_stat_failed }}",
statDeferred: "{{ t.player_import_stat_deferred }}",
statDuplicate: "{{ t.player_import_stat_duplicate }}",
statAlreadyPresent: "{{ t.player_import_stat_already_present }}",
statPaused: "{{ t.player_import_stat_paused }}",
statNoContent: "{{ t.player_import_stat_no_content }}",
statPublishFailed: "{{ t.player_import_stat_publish_failed }}",
playlists: "{{ t.player_import_playlists }}",
playlistDeleted: "{{ t.player_import_playlist_deleted }}",
playlistPending: "{{ t.player_import_playlist_pending }}",
recreate: "{{ t.player_import_recreate }}",
recreateStarted: "{{ t.player_import_recreate_started }}",
entries: "{{ t.player_import_entries }}",
filterAll: "{{ t.player_import_filter_all }}",
allPlaylists: "{{ t.player_import_all_playlists }}",
search: "{{ t.player_import_search }}",
noEntries: "{{ t.player_import_no_entries }}",
loadMore: "{{ t.player_import_load_more }}",
loading: "{{ t.player_import_loading }}",
candidates: "{{ t.player_import_candidates }}",
choose: "{{ t.player_import_choose }}",
chosen: "{{ t.player_import_chosen }}",
local: "{{ t.player_import_origin_local }}",
federation: "{{ t.player_import_origin_federation }}",
res_pending: "{{ t.player_import_res_pending }}",
res_matched: "{{ t.player_import_res_matched }}",
res_ambiguous: "{{ t.player_import_res_ambiguous }}",
res_unmatched: "{{ t.player_import_res_unmatched }}",
res_unsupported: "{{ t.player_import_res_unsupported }}",
res_failed: "{{ t.player_import_res_failed }}",
pub_pending: "{{ t.player_import_pub_pending }}",
pub_published: "{{ t.player_import_pub_published }}",
pub_duplicate: "{{ t.player_import_pub_duplicate }}",
pub_already_present: "{{ t.player_import_pub_already_present }}",
pub_no_content_id: "{{ t.player_import_pub_no_content_id }}",
pub_deferred_sync_limit: "{{ t.player_import_pub_deferred }}",
pub_paused: "{{ t.player_import_pub_paused }}",
pub_failed: "{{ t.player_import_pub_failed }}",
note_not_found: "{{ t.player_import_note_not_found }}",
note_version_mismatch: "{{ t.player_import_note_version_mismatch }}",
note_duration_mismatch: "{{ t.player_import_note_duration_mismatch }}",
note_federation_error: "{{ t.player_import_note_federation_error }}",
note_federation_budget: "{{ t.player_import_note_federation_budget }}",
note_federation_unavailable: "{{ t.player_import_note_federation_unavailable }}",
note_episode: "{{ t.player_import_note_episode }}",
note_audiobook: "{{ t.player_import_note_audiobook }}",
note_local_file: "{{ t.player_import_note_local_file }}",
note_unknown_kind: "{{ t.player_import_note_unknown_kind }}",
note_missing_title: "{{ t.player_import_note_missing_title }}",
note_failed: "{{ t.player_import_note_failed }}",
oauth_state: "{{ t.player_import_oauth_state }}",
oauth_expired: "{{ t.player_import_oauth_expired }}",
oauth_denied: "{{ t.player_import_oauth_denied }}",
oauth_not_configured: "{{ t.player_import_oauth_not_configured }}",
oauth_exchange: "{{ t.player_import_oauth_exchange }}",
oauth_not_allowed: "{{ t.player_import_oauth_not_allowed }}",
oauth_unavailable: "{{ t.player_import_oauth_unavailable }}",
oauth_not_waiting: "{{ t.player_import_oauth_not_waiting }}",
oauth_account_mismatch: "{{ t.player_import_oauth_account_mismatch }}",
};
const MiB = 1024 * 1024;
// The request limit of /api/imports. The wizard checks it before sending,
// and the archive limits keep a ZIP bomb from filling the browser memory:
// fflate inflates a deflated entry into a buffer of its declared size and
// copies a stored entry by its compressed size, so each extracted file is
// charged the larger of both, and a stored entry must declare equal sizes.
const LIMITS = {archiveBytes: 256 * MiB, entries: 2000, files: 256, exportBytes: 32 * MiB, requestBytes: 32 * MiB};
// Only these files of an export are read; listening history stays in the browser.
const EXPORT_FILES = {spotify: /(^|\/)(Playlist\d*|YourLibrary)\.json$/};
const POLL_MS = 3000;
const ACTIVE = ['queued', 'running'];
const FINISHED = ['done', 'failed', 'cancelled'];
const NOTES_FAILED = ['invalid_metadata', 'resolve_failed', 'write_failed', 'content_id_failed'];
const locale = document.documentElement.lang || 'en';
const numbers = new Intl.NumberFormat(locale);
const dates = new Intl.DateTimeFormat(locale, {dateStyle:'medium', timeStyle:'short'});
const fill = (template, values) => template.replace(/\{(\w+)\}/g, (_, key) => values[key] ?? '');
let fflateLoading = null;
function emptyWizard() {
return {
open: false, step: 'source', provider: '', method: '', busy: false, error: '', notice: '',
files: [], fileNames: [], skipped: 0, preview: null, selected: {}, confirmed: {}, federated: false,
};
}
Alpine.store('imports', {
providers: [], federatedAvailable: false, providersLoaded: false,
imports: [], loaded: false, loading: false, error: '', message: '',
detail: null, detailId: null, detailError: '', notice: '',
items: [], itemsNext: null, itemsLoading: false, itemsLoaded: false,
filter: {status: '', playlist: '', q: ''},
retryPanel: false, retryFederated: false,
busy: false, choosing: null,
wizard: emptyWizard(),
_navigation: 0, _items: 0, _timer: null, _search: null, _opener: null, _signature: '',
text(key, values) {
const label = labels[key] ?? key;
return values ? fill(label, values) : label;
},
number(value) { return numbers.format(Number(value) || 0); },
date(value) {
const date = value ? new Date(value) : null;
return date && !isNaN(date) ? dates.format(date) : '';
},
duration(ms) { return ms ? formatTime(Number(ms) / 1000) : ''; },
stats(record) { return record?.statistics || {}; },
found(record) {
const stats = this.stats(record);
return (stats.matched_local || 0) + (stats.matched_federation || 0);
},
title(record) {
return this.providerName(record?.provider) + ' · ' + this.text('number', {id: record?.id});
},
providerName(id) {
return this.providers.find(provider => provider.id === id)?.name || (id ? id[0].toUpperCase() + id.slice(1) : '');
},
isActive(record) { return ACTIVE.includes(record?.status); },
isFinished(record) { return FINISHED.includes(record?.status); },
statusText(record) {
if (record?.cancel_requested && this.isActive(record)) return this.text('status_cancelling');
return this.text('status_' + record?.status);
},
phaseText(record) {
if (record?.status === 'queued') return this.text('phase_waiting');
return record?.phase ? this.text('phase_' + record.phase) : '';
},
// Progress of the current phase; `null` max means an indeterminate bar.
progress(record) {
const stats = this.stats(record);
if (record?.status !== 'running' || record.phase === 'fetching' || !stats.total) return {value: null, max: null};
if (record.phase === 'publish') {
const done = ['published', 'duplicate', 'already_present', 'no_content_id', 'deferred_sync_limit', 'paused', 'publication_failed']
.reduce((sum, key) => sum + (stats[key] || 0), 0);
const max = done + (stats.publication_pending || 0);
return max ? {value: done, max} : {value: null, max: null};
}
return {value: stats.total - (stats.pending || 0), max: stats.total};
},
noteText(item) {
const note = item?.resolution_note;
if (!note) return '';
if (NOTES_FAILED.includes(note)) return this.text('note_failed');
return labels['note_' + note] || '';
},
resolutionText(item) {
if (item.resolution_status === 'matched') {
return this.text(item.match_origin === 'federation' ? 'federation' : 'local');
}
return this.text('res_' + item.resolution_status);
},
publicationText(item) {
const status = item?.publication_status;
return status && status !== 'not_ready' ? this.text('pub_' + status) : '';
},
meta(item) { return item?.metadata || {}; },
artists(list) { return (list || []).filter(Boolean).join(', '); },
async api(url, options = {}) {
const init = {...options};
if (options.body !== undefined) init.headers = {'Content-Type': 'application/json'};
const response = await fetch(url, init);
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const message = response.status === 413 ? this.text('requestTooLarge') : data.error || this.text('failed');
throw Object.assign(new Error(message), {status: response.status, data});
}
return data;
},
// ---------------------------------------------------------------
// Navigation and polling
// ---------------------------------------------------------------
visible() { return ['imports', 'import_detail'].includes(Alpine.store('library').view); },
navigate(hash, view, options = {}) {
const library = Alpine.store('library');
library._beginNavigation(hash, options);
library.searchQuery = '';
library.searchResults = null;
library.view = view;
library.currentArtist = null;
library.currentRelease = null;
library.currentPlaylist = null;
library._previousView = view;
Alpine.store('mobile')?.closeLibrary();
},
// `#imports`, `#imports?connect=spotify[&error=CODE]` and `#imports/N[?error=CODE]`.
route(id, params, options = {}) {
const query = new URLSearchParams(params || '');
const error = query.get('error');
if (id > 0) return this.open(id, {...options, error});
const connect = query.get('connect');
const entered = this.enter(options);
if (connect) this.returnFromSignIn(connect, error);
return entered;
},
async enter(options = {}) {
const token = ++this._navigation;
clearTimeout(this._search);
this._search = null;
this.navigate('#imports', 'imports', options);
this.detail = null;
this.detailId = null;
this.message = '';
this.error = '';
this.loading = true;
try {
await Promise.all([this.loadProviders(), this.load()]);
} catch (error) {
if (token === this._navigation) this.error = error.message || this.text('loadFailed');
} finally {
if (token === this._navigation) {
this.loading = false;
Alpine.store('library')._afterNavigation(options);
this.schedule();
}
}
},
async open(id, options = {}) {
const token = ++this._navigation;
this.navigate('#imports/' + id, 'import_detail', options);
if (this.detailId !== id) {
clearTimeout(this._search);
this._search = null;
this.detail = null;
this.items = [];
this.itemsLoaded = false;
this.itemsNext = null;
this.filter = {status: '', playlist: '', q: ''};
}
this.detailId = id;
this.detailError = '';
this.message = '';
this.retryPanel = false;
this.notice = options.error ? this.text('oauth_' + options.error) : '';
if (options.error) {
history.replaceState(history.state, '', '#imports/' + id);
Alpine.store('library')._activeHash = '#imports/' + id;
}
try {
if (!this.providersLoaded) this.loadProviders().catch(() => {});
await Promise.all([this.loadDetail(id), this.loadItems()]);
} catch (error) {
if (token === this._navigation) this.detailError = error.status === 404 ? this.text('loadFailed') : error.message;
} finally {
if (token === this._navigation) {
Alpine.store('library')._afterNavigation(options);
this.schedule();
}
}
},
hasActive() {
if (Alpine.store('library').view === 'import_detail') return this.isActive(this.detail);
return this.imports.some(record => this.isActive(record));
},
// Polls every 3 s while the page is open and an import is in progress.
schedule() {
if (this._timer || !this.visible() || !this.hasActive()) return;
this._timer = setTimeout(() => this.tick(), POLL_MS);
},
stopPolling() {
if (this._timer) clearTimeout(this._timer);
this._timer = null;
},
async tick() {
this._timer = null;
if (!this.visible()) return;
const token = this._navigation;
try {
if (Alpine.store('library').view === 'import_detail' && this.detailId) await this.refreshDetail();
else await this.load();
} catch {}
if (token === this._navigation) this.schedule();
},
// ---------------------------------------------------------------
// History
// ---------------------------------------------------------------
async loadProviders() {
const data = await this.api('/api/imports/providers');
this.providers = data.providers || [];
this.federatedAvailable = !!data.federated_search_available;
this.providersLoaded = true;
},
async load() {
const data = await this.api('/api/imports');
const before = this.loaded ? this.published(this.imports) : null;
this.imports = data.imports || [];
this.loaded = true;
if (before !== null && this.published(this.imports) !== before) Alpine.store('playlists')?.reload?.();
},
published(records) {
return records.reduce((sum, record) => sum + (this.stats(record).published || 0), 0);
},
playlistLinks(record) {
return (record?.playlists || []).filter(link => link.target_playlist_id && !link.target_deleted);
},
async retry(record, federated) {
if (this.busy) return;
this.busy = true;
this.message = '';
try {
const body = federated === undefined ? {} : {federated_search: !!federated};
await this.api(`/api/imports/${record.id}/resync`, {method: 'POST', body: JSON.stringify(body)});
this.message = this.text('retryStarted');
this.retryPanel = false;
if (this.detail?.id === record.id) await this.refreshDetail(true);
else await this.load();
} catch (error) {
this.message = error.message;
} finally {
this.busy = false;
this.schedule();
}
},
// ---------------------------------------------------------------
// Details
// ---------------------------------------------------------------
async loadDetail(id) {
const detail = await this.api(`/api/imports/${id}`);
if (this.detailId !== id) return false;
const changed = this._signature !== this.signature(detail);
const published = this.stats(this.detail).published;
this.detail = detail;
this._signature = this.signature(detail);
if (published !== undefined && this.stats(detail).published !== published) Alpine.store('playlists')?.reload?.();
return changed;
},
signature(detail) {
return JSON.stringify([detail?.status, detail?.phase, detail?.statistics]);
},
// A background refresh keeps the entry list; it reloads only an
// unpaginated first page when the counters changed.
async refreshDetail(force = false) {
const id = this.detailId;
const changed = await this.loadDetail(id);
if ((changed || force) && this.detailId === id && this.items.length <= 50 && !this.choosing) await this.loadItems();
},
itemsUrl(after) {
const params = new URLSearchParams();
if (this.filter.status) params.set('status', this.filter.status);
if (this.filter.playlist) params.set('playlist', this.filter.playlist);
if (this.filter.q.trim()) params.set('q', this.filter.q.trim());
if (after) params.set('after', after);
const query = params.toString();
return `/api/imports/${this.detailId}/items` + (query ? '?' + query : '');
},
async loadItems(append = false) {
const id = this.detailId;
if (!id) return;
const token = ++this._items;
this.itemsLoading = true;
try {
const page = await this.api(this.itemsUrl(append ? this.itemsNext : null));
if (token !== this._items || id !== this.detailId) return;
this.items = append ? [...this.items, ...(page.items || [])] : page.items || [];
this.itemsNext = page.next || null;
this.itemsLoaded = true;
} finally {
if (token === this._items) this.itemsLoading = false;
}
},
setStatus(status) {
if (this.filter.status === status) return;
this.filter.status = status;
this.loadItems().catch(error => { this.message = error.message; });
},
setPlaylist(playlist) {
this.filter.playlist = playlist;
this.loadItems().catch(error => { this.message = error.message; });
},
searchChanged() {
clearTimeout(this._search);
this._search = setTimeout(() => this.loadItems().catch(error => { this.message = error.message; }), 300);
},
statusFilters() {
const stats = this.stats(this.detail);
return [
{status: '', label: this.text('filterAll'), count: stats.total},
{status: 'matched', label: this.text('statFound'), count: (stats.matched_local || 0) + (stats.matched_federation || 0)},
{status: 'ambiguous', label: this.text('statAmbiguous'), count: stats.ambiguous},
{status: 'unmatched', label: this.text('statUnmatched'), count: stats.unmatched},
{status: 'unsupported', label: this.text('statUnsupported'), count: stats.unsupported},
{status: 'failed', label: this.text('statFailed'), count: stats.failed},
{status: 'pending', label: this.text('res_pending'), count: stats.pending},
].filter(filter => !filter.status || filter.count || filter.status === this.filter.status);
},
// The secondary counters appear only when they are not zero.
extraStats() {
const stats = this.stats(this.detail);
return [
['deferred_sync_limit', 'statDeferred'], ['duplicate', 'statDuplicate'],
['already_present', 'statAlreadyPresent'], ['paused', 'statPaused'],
['no_content_id', 'statNoContent'], ['publication_failed', 'statPublishFailed'], ['failed', 'statFailed'],
].filter(([key]) => stats[key]).map(([key, label]) => ({key, label: this.text(label), value: stats[key]}));
},
playlistTitle(id) {
return this.detail?.source_playlists?.find(playlist => playlist.id === id)?.title || '';
},
async cancel() {
if (this.busy || !this.detail) return;
this.busy = true;
this.message = '';
try {
const data = await this.api(`/api/imports/${this.detail.id}/cancel`, {method: 'POST', body: '{}'});
this.message = data.status === 'cancelling' ? this.text('cancelRequested') : '';
await this.refreshDetail(true);
} catch (error) {
this.message = error.message;
} finally {
this.busy = false;
this.schedule();
}
},
async remove(record = this.detail) {
if (this.busy || !record || !confirm(this.text('deleteConfirm'))) return;
this.busy = true;
this.message = '';
try {
await this.api(`/api/imports/${record.id}`, {method: 'DELETE'});
this.imports = this.imports.filter(entry => entry.id !== record.id);
if (this.detailId === record.id) {
this.detail = null;
this.detailId = null;
await this.enter();
}
this.message = this.text('deleted');
} catch (error) {
this.message = error.message;
} finally {
this.busy = false;
}
},
async recreate(playlist) {
if (this.busy || !this.detail) return;
this.busy = true;
this.message = '';
try {
await this.api(`/api/imports/${this.detail.id}/playlists/${playlist.id}/recreate`, {method: 'POST', body: '{}'});
this.message = this.text('recreateStarted');
await this.refreshDetail(true);
} catch (error) {
this.message = error.message;
} finally {
this.busy = false;
this.schedule();
}
},
reauthorize(record = this.detail) {
if (!record) return;
location.assign(`/api/imports/providers/${encodeURIComponent(record.provider)}/authorize?import_id=${record.id}`);
},
openRetry() {
this.retryFederated = !!this.detail?.federated_search && this.federatedAvailable;
this.retryPanel = !this.retryPanel;
},
async choose(item, index) {
if (this.choosing || !this.detail) return;
this.choosing = item.id;
this.message = '';
try {
const result = await this.api(`/api/imports/${this.detail.id}/items/${item.id}/match`, {
method: 'POST', body: JSON.stringify({candidate: index}),
});
const candidate = item.candidates?.[index] || {};
Object.assign(item, {
resolution_status: result.resolution_status || 'matched',
publication_status: result.publication_status || item.publication_status,
match_origin: candidate.origin || item.match_origin,
candidates: null,
});
this.message = this.text('chosen');
this.choosing = null;
await this.refreshDetail();
} catch (error) {
this.message = error.message;
} finally {
this.choosing = null;
this.schedule();
}
},
// ---------------------------------------------------------------
// New import wizard
// ---------------------------------------------------------------
startWizard(provider = '') {
Alpine.store('user').menuOpen = false;
this._opener = document.activeElement;
this.wizard = {...emptyWizard(), open: true, provider};
if (!this.providersLoaded) this.loadProviders().catch(error => { this.wizard.error = error.message; });
},
// The dialog leaves the DOM without close(), so focus goes back to the
// button that opened it, unless the wizard closes to navigate.
async closeWizard(dialog, restoreFocus = true) {
const opener = this._opener;
this._opener = null;
const close = () => {
this.wizard = emptyWizard();
if (restoreFocus) Alpine.nextTick(() => {
const target = opener?.isConnected ? opener
: document.querySelector('.library-imports .release-action-btn.primary') || document.querySelector('.library-imports h1');
target?.focus({preventScroll: true});
});
};
if (dialog) await finishPlayerDialog(dialog, close);
else close();
},
// A new step replaces the focused control, so the title takes focus.
focusWizardTitle() {
Alpine.nextTick(() => document.getElementById('import-wizard-title')?.focus());
},
chooseMethod(provider, method) {
this.wizard = {...emptyWizard(), open: true, provider, method, step: method === 'api' ? 'connect' : 'upload'};
this.focusWizardTitle();
// A sign-in from earlier in this session may still be valid.
if (method === 'api') return this.loadApiPlaylists(true);
},
back() {
const {provider} = this.wizard;
this.wizard = {...emptyWizard(), open: true, provider};
this.focusWizardTitle();
},
signIn(provider = this.wizard.provider) {
location.assign(`/api/imports/providers/${encodeURIComponent(provider)}/authorize`);
},
// The browser returns here from the provider's sign-in page.
returnFromSignIn(provider, error) {
history.replaceState(history.state, '', '#imports');
Alpine.store('library')._activeHash = '#imports';
this.wizard = {...emptyWizard(), open: true, provider, method: 'api', step: 'connect'};
if (error) {
this.wizard.error = this.text('oauth_' + error);
return;
}
return this.loadApiPlaylists();
},
async loadApiPlaylists(quiet = false) {
const wizard = this.wizard;
wizard.busy = true;
wizard.error = '';
wizard.notice = this.text('loadingPlaylists');
try {
const preview = await this.api(`/api/imports/providers/${encodeURIComponent(wizard.provider)}/playlists`);
if (this.wizard !== wizard) return;
this.applyPreview(preview);
} catch (error) {
if (this.wizard === wizard && !(quiet && error.status === 409)) wizard.error = error.message;
} finally {
wizard.busy = false;
wizard.notice = '';
}
},
async zipLibrary() {
if (window.fflate) return window.fflate;
fflateLoading ??= new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = '/vendor/fflate-0.8.2.js';
script.onload = () => window.fflate ? resolve(window.fflate) : reject(new Error(this.text('zipLoadFailed')));
script.onerror = () => reject(new Error(this.text('zipLoadFailed')));
document.head.appendChild(script);
}).catch(error => {
fflateLoading = null;
throw error;
});
return fflateLoading;
},
// Extracts only the export's playlist files. Archive entries, files and
// the sizes fflate allocates for them are limited before anything is
// decompressed; unknown methods, duplicates and stored entries whose
// sizes disagree are refused.
async readArchive(file, pattern, budget) {
if (file.size > LIMITS.archiveBytes) throw new Error(this.text('archiveTooLarge'));
const fflate = await this.zipLibrary();
const bytes = new Uint8Array(await file.arrayBuffer());
let entries = 0;
let problem = '';
const names = new Set();
const extracted = await new Promise((resolve, reject) => {
try {
fflate.unzip(bytes, {filter: entry => {
entries += 1;
if (problem) return false;
if (entries > LIMITS.entries) problem = 'zipTooManyEntries';
if (problem || !pattern.test(entry.name)) return false;
const packed = Number(entry.size);
const size = Number(entry.originalSize);
const valid = [packed, size].every(n => Number.isFinite(n) && n >= 0)
&& (entry.compression === 8 || (entry.compression === 0 && packed === size));
if (!valid || names.has(entry.name)) {
problem = 'zipInvalid';
return false;
}
names.add(entry.name);
budget.files += 1;
budget.bytes += Math.max(packed, size);
if (budget.files > LIMITS.files) problem = 'zipTooManyFiles';
else if (budget.bytes > LIMITS.exportBytes) problem = 'exportTooLarge';
return !problem;
}}, (error, files) => error ? reject(error) : resolve(files));
} catch (error) {
reject(error);
}
}).catch(error => {
throw problem ? new Error(this.text(problem)) : new Error(this.text('zipInvalid'));
});
if (problem) throw new Error(this.text(problem));
const decoder = new TextDecoder();
return Object.entries(extracted).map(([name, data]) => ({name, text: decoder.decode(data)}));
},
async readFiles(list) {
const wizard = this.wizard;
const pattern = EXPORT_FILES[wizard.provider];
const files = Array.from(list || []);
if (!pattern || !files.length) return;
wizard.busy = true;
wizard.error = '';
wizard.notice = this.text('reading');
wizard.preview = null;
try {
const budget = {files: 0, bytes: 0};
const read = [];
let skipped = 0;
for (const file of files) {
if (/\.zip$/i.test(file.name) || /zip/.test(file.type || '')) {
read.push(...await this.readArchive(file, pattern, budget));
} else if (pattern.test(file.name)) {
budget.files += 1;
budget.bytes += file.size;
if (budget.files > LIMITS.files) throw new Error(this.text('zipTooManyFiles'));
if (budget.bytes > LIMITS.exportBytes) throw new Error(this.text('exportTooLarge'));
read.push({name: file.name, text: await file.text()});
} else {
skipped += 1;
}
}
if (this.wizard !== wizard) return;
if (!read.length) throw new Error(this.text('noFiles'));
// Parsed JSON is sent compact; text that does not parse goes as is,
// so the server can name the file and line that is broken.
wizard.files = read.map(file => {
const text = file.text.replace(/^/, '');
try {
return {name: file.name, data: JSON.parse(text)};
} catch {
return {name: file.name, data: text};
}
});
wizard.fileNames = read.map(file => file.name.split('/').pop());
wizard.skipped = skipped;
wizard.notice = '';
const preview = await this.api('/api/imports/preview', {method: 'POST', body: this.requestBody({})});
if (this.wizard === wizard) this.applyPreview(preview);
} catch (error) {
if (this.wizard === wizard) {
wizard.error = error.message || this.text('failed');
wizard.files = [];
}
} finally {
wizard.busy = false;
wizard.notice = '';
}
},
requestBody(extra) {
const wizard = this.wizard;
const body = JSON.stringify({provider: wizard.provider, source: wizard.method || 'file',
...(wizard.method === 'api' ? {} : {files: wizard.files}), ...extra});
if (new TextEncoder().encode(body).length > LIMITS.requestBytes) throw new Error(this.text('requestTooLarge'));
return body;
},
applyPreview(preview) {
const wizard = this.wizard;
wizard.preview = preview;
wizard.step = 'select';
wizard.selected = {};
wizard.confirmed = {};
for (const playlist of preview.playlists || []) {
wizard.selected[playlist.source_key] = this.selectable(playlist) && !playlist.similar_to;
}
if (!preview.federated_search_available) wizard.federated = false;
this.federatedAvailable = !!preview.federated_search_available;
this.focusWizardTitle();
},
selectable(playlist) { return playlist.available !== false && !playlist.already_imported_in; },
selectAll(value) {
for (const playlist of this.wizard.preview?.playlists || []) {
if (this.selectable(playlist)) this.wizard.selected[playlist.source_key] = value && !playlist.similar_to;
}
},
selection() {
return (this.wizard.preview?.playlists || [])
.filter(playlist => this.selectable(playlist) && this.wizard.selected[playlist.source_key]);
},
unconfirmed() {
return this.selection().filter(playlist => playlist.similar_to && !this.wizard.confirmed[playlist.source_key]);
},
canStart() {
return !this.wizard.busy && this.selection().length > 0 && !this.unconfirmed().length;
},
async begin() {
const wizard = this.wizard;
if (!this.canStart()) {
if (this.unconfirmed().length) wizard.error = this.text('confirmSimilarNeeded');
return;
}
wizard.busy = true;
wizard.error = '';
wizard.notice = this.text('starting');
try {
const selection = this.selection();
const result = await this.api('/api/imports', {method: 'POST', body: this.requestBody({
selection: selection.map(playlist => playlist.source_key),
federated_search: wizard.federated && this.federatedAvailable,
confirm_similar: selection.filter(playlist => playlist.similar_to).map(playlist => playlist.source_key),
})});
await this.closeWizard(document.querySelector('.import-wizard[open]'), false);
return this.open(result.id);
} catch (error) {
if (this.wizard !== wizard) return;
this.applyConflicts(error.data || {});
wizard.error = error.data?.conflicts ? this.text('conflicts')
: error.data?.similar ? this.text('similarConflicts') : error.message;
} finally {
wizard.busy = false;
wizard.notice = '';
}
},
// A 409 names playlists imported meanwhile; the wizard marks them.
applyConflicts(data) {
const playlists = this.wizard.preview?.playlists || [];
for (const conflict of data.conflicts || []) {
const playlist = playlists.find(entry => entry.source_key === conflict.source_key);
if (playlist) {
playlist.already_imported_in = conflict.import_id;
this.wizard.selected[playlist.source_key] = false;
}
}
for (const similar of data.similar || []) {
const playlist = playlists.find(entry => entry.source_key === similar.source_key);
if (playlist) playlist.similar_to = {import_id: similar.import_id, target_playlist_id: similar.target_playlist_id};
}
},
});
});
</script>
+139
View File
@@ -0,0 +1,139 @@
<style>
.library-imports { max-width: 1050px; margin: 0 auto; padding: 0 0 24px; }
:where(.library-imports, .import-wizard) :where(button, select, input) { font-family: inherit; }
.library-imports :is(a, button, select, input):focus-visible, .import-wizard :is(a, button, input):focus-visible,
.import-file-button:focus-within { outline: 2px solid var(--accent); outline-offset: 2px; }
.import-heading { display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; }
.import-heading .section-title { margin: 0; }
.import-heading-copy { min-width: 0; }
.import-heading-copy p { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 8px 0 0; color: var(--text-secondary); font-size: 13px; }
.import-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.import-subtitle { margin: 26px 0 12px; font-size: 18px; letter-spacing: -.015em; }
.import-notice { margin: 0 0 12px; color: var(--text-secondary); font-size: 13px; overflow-wrap: anywhere; }
.import-notice.error { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; color: #ffaeab; }
.import-text-action { padding: 6px 10px; border: 1px solid var(--border-color); border-radius: 5px; background: transparent; color: var(--text-secondary); font-size: 13px; cursor: pointer; transition: color 120ms, background-color 120ms; }
.import-text-action:hover:not(:disabled) { color: var(--text-primary); background: var(--bg-elevated); }
.import-text-action:disabled { opacity: .45; cursor: default; }
.import-source-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 12px; }
.import-source, .import-method {
display: grid; gap: 6px; min-width: 0; padding: 14px 16px; border: 1px solid var(--border-color); border-radius: 8px;
background: var(--bg-secondary); color: var(--text-primary); text-align: left; cursor: pointer; transition: background-color 140ms, border-color 140ms;
}
.import-source:hover, .import-method:hover { background: var(--bg-elevated); border-color: var(--bg-active); }
.import-source strong, .import-method strong { font-size: 15px; }
.import-source small, .import-method small { color: var(--text-secondary); font-size: 12px; line-height: 1.4; }
.import-source.skeleton-card { min-height: 46px; cursor: default; }
.import-source.skeleton-card .skeleton-bar:first-child { width: 40%; }
.import-history { list-style: none; margin: 0; padding: 0; }
.import-history-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; padding: 10px 6px; border-bottom: 1px solid var(--border-color); }
.import-history-row:hover, .import-history-row:focus-within { background: var(--bg-elevated); border-radius: 6px; }
.import-history-link, .import-history-playlists { grid-column: 1; }
.import-history-link { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 12px; min-width: 0; color: inherit; text-decoration: none; }
.import-history-title { min-width: 0; }
.import-history-title strong, .import-history-title small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.import-history-title strong { font-size: 14px; }
.import-history-title small, .import-history-count { color: var(--text-subdued); font-size: 12px; }
.import-history-count { font-variant-numeric: tabular-nums; white-space: nowrap; }
.import-history-actions { display: flex; gap: 6px; align-items: center; grid-column: 2; grid-row: 1 / span 2; }
.import-history-playlists { display: flex; flex-wrap: wrap; gap: 4px 10px; min-width: 0; color: var(--text-subdued); font-size: 12px; }
.import-history-playlists a { color: var(--text-secondary); text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 220px; }
.import-history-playlists a:hover { color: var(--text-primary); text-decoration: underline; }
.import-status { display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 10px; background: var(--bg-active); color: var(--text-secondary); font-size: 12px; white-space: nowrap; }
.import-status:is([data-status=done], [data-status=matched]) { background: #183426; color: var(--accent); }
.import-status:is([data-status=running], [data-status=queued], [data-status=pending]) { color: var(--text-primary); }
.import-status:is([data-status=failed], [data-status=needs_reauth]) { background: #3a1f1f; color: #ffaeab; }
.import-status[data-status=ambiguous] { background: #3a321a; color: #f0d58a; }
.import-progress { display: grid; gap: 6px; margin: 0 0 16px; color: var(--text-secondary); font-size: 13px; }
.import-progress progress { width: 100%; height: 6px; accent-color: var(--accent); }
.import-stats { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); margin: 0 0 10px; padding: 16px 0; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); }
.import-stats > div { min-width: 0; padding: 0 clamp(8px, 1.6vw, 18px); }
.import-stats > div + div { border-left: 1px solid var(--border-color); }
.import-stats dt, .import-stats small { color: var(--text-secondary); font-size: 12px; }
.import-stats dd { margin: 6px 0 0; font-size: clamp(18px, 2vw, 26px); font-weight: 650; font-variant-numeric: tabular-nums; }
.import-stats small { display: block; margin-top: 4px; overflow-wrap: anywhere; }
.import-stats-skeleton { margin-top: 18px; }
.import-stats-skeleton .skeleton-bar + .skeleton-bar { width: 50%; margin-top: 10px; height: 16px; }
.import-extra-stats { display: flex; flex-wrap: wrap; gap: 6px 16px; list-style: none; margin: 0; padding: 0; color: var(--text-secondary); font-size: 13px; }
.import-extra-stats strong { color: var(--text-primary); font-variant-numeric: tabular-nums; }
.import-playlists { list-style: none; margin: 0; padding: 0; max-width: 840px; }
.import-filters { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
.import-filters .collection-tabs { margin: 0; }
.import-filters .collection-tabs button { display: inline-flex; align-items: center; min-height: 32px; padding: 6px 12px; border: 0; border-radius: 18px; background: var(--bg-elevated); color: var(--text-secondary); font-size: 13px; cursor: pointer; transition: color 120ms, background-color 120ms; }
.import-filters .collection-tabs button:hover { color: var(--text-primary); }
.import-filters .collection-tabs button[aria-pressed=true] { background: var(--text-primary); color: var(--bg-primary); }
.import-filter-fields { display: flex; flex-wrap: wrap; gap: 8px; }
.import-filter-fields :is(select, input) { min-width: 0; max-width: 260px; padding: 7px 10px; border: 1px solid var(--border-color); border-radius: 6px; background: var(--bg-secondary); color: var(--text-primary); color-scheme: dark; font-size: 13px; }
.import-items { list-style: none; margin: 0; padding: 0; transition: opacity 140ms; }
.import-items[aria-busy=true] { opacity: .7; }
.import-item { display: grid; grid-template-columns: 34px minmax(0, 1fr) 48px minmax(120px, auto); align-items: center; gap: 4px 12px; padding: 8px 6px; border-bottom: 1px solid var(--border-color); }
.import-item-position, .import-item-duration { color: var(--text-subdued); font-size: 12px; font-variant-numeric: tabular-nums; }
.import-item-position { text-align: right; }
.import-item-copy { min-width: 0; }
.import-item-copy strong, .import-item-copy small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.import-item-copy strong { font-size: 14px; font-weight: 600; }
.import-item-copy small { margin-top: 2px; color: var(--text-subdued); font-size: 12px; }
.import-item-status { display: grid; justify-items: end; gap: 3px; text-align: right; }
.import-item-status small { color: var(--text-subdued); font-size: 12px; }
.import-candidates { grid-column: 2 / -1; display: grid; gap: 4px; margin-top: 4px; padding: 8px 10px; border-radius: 6px; background: var(--bg-secondary); }
.import-candidates-title { color: var(--text-secondary); font-size: 12px; }
.import-candidate { display: grid; grid-template-columns: minmax(0, 1fr) 48px auto auto; align-items: center; gap: 10px; }
.import-origin { color: var(--text-secondary); font-size: 12px; }
.import-more { display: flex; justify-content: center; margin-top: 14px; }
.import-retry-panel { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; margin: 0 0 14px; padding: 12px 14px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); }
.import-consent { display: flex; align-items: flex-start; gap: 10px; min-width: 0; flex: 1; }
.import-consent .offline-switch-row { flex: none; min-height: 22px; border: 0; background: none; cursor: pointer; }
.import-consent strong, .import-consent small { display: block; }
.import-consent strong { font-size: 14px; }
.import-consent small { margin-top: 3px; color: var(--text-secondary); font-size: 12px; line-height: 1.4; }
.import-wizard-body { display: grid; gap: 14px; padding: 16px var(--dialog-gutter) var(--dialog-gutter); }
.import-wizard-body .import-notice { margin: 0; }
.import-step { display: grid; gap: 14px; min-width: 0; }
.import-provider h3 { margin: 0 0 10px; font-size: 15px; }
.import-methods { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; }
.import-help, .import-privacy { margin: 0; color: var(--text-secondary); font-size: 13px; line-height: 1.5; }
.import-privacy { color: var(--text-subdued); font-size: 12px; }
.import-file-button { position: relative; justify-self: start; }
.import-file-button.disabled { opacity: .45; pointer-events: none; }
.import-file-input { position: absolute; width: 1px; height: 1px; opacity: 0; overflow: hidden; clip-path: inset(50%); }
.import-select-head { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px; font-size: 13px; }
.import-select-head span { display: flex; gap: 6px; }
.import-select-list { list-style: none; max-height: min(46vh, 420px); margin: 0; padding: 0; overflow: auto; overscroll-behavior: contain; border: 1px solid var(--border-color); border-radius: 8px; scrollbar-width: thin; }
.import-select-list li { padding: 8px 12px; border-bottom: 1px solid var(--border-color); }
.import-select-list li:last-child { border-bottom: 0; }
.import-select-list li.disabled .import-select-copy { opacity: .55; }
.import-select-row { display: flex; align-items: center; gap: 10px; min-width: 0; cursor: pointer; }
.import-select-row input, .import-select-note input { flex: none; width: 16px; height: 16px; accent-color: var(--accent); }
.import-select-copy { min-width: 0; }
.import-select-copy strong, .import-select-copy small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.import-select-copy strong { font-size: 14px; font-weight: 600; }
.import-select-copy small { color: var(--text-subdued); font-size: 12px; }
.import-select-note { display: grid; gap: 6px; margin: 6px 0 0 26px; color: var(--text-secondary); font-size: 12px; }
.import-select-note a { color: var(--text-secondary); }
.import-select-note.warning > span { color: #f0d58a; }
.import-select-note label { display: flex; align-items: center; gap: 8px; color: var(--text-primary); cursor: pointer; }
.import-wizard-footer { display: flex; justify-content: space-between; gap: 10px; padding-top: 4px; }
@media (max-width: 760px) {
.import-stats { grid-template-columns: repeat(3, minmax(0, 1fr)); row-gap: 14px; }
.import-stats > div:nth-child(3n + 1) { border-left: 0; }
}
@media (max-width: 600px) {
.import-history-row { grid-template-columns: minmax(0, 1fr); }
.import-history-link { grid-template-columns: minmax(0, 1fr) auto; }
.import-history-count { grid-column: 1 / -1; }
.import-history-actions { grid-column: 1; grid-row: auto; }
.import-item { grid-template-columns: 26px minmax(0, 1fr) auto; }
.import-item-duration { display: none; }
.import-item-status { grid-column: 2 / -1; justify-items: start; text-align: left; }
.import-candidates { grid-column: 1 / -1; }
.import-candidate { grid-template-columns: minmax(0, 1fr) auto; }
.import-candidate .import-origin { grid-column: 1; }
.import-candidate .import-text-action { grid-column: 2; grid-row: 1 / span 2; min-height: 36px; }
.import-filter-fields, .import-filter-fields :is(select, input) { flex: 1; max-width: none; }
.import-text-action, .import-filters .collection-tabs button { min-height: 36px; }
.import-actions .release-action-btn { flex: 1; justify-content: center; }
}
@media (prefers-reduced-motion: reduce) {
.import-source, .import-method, .import-text-action, .import-items, .import-filters .collection-tabs button { transition: none; }
.import-retry-panel, .import-select-note label { transition-duration: 0s !important; }
}
</style>
+134
View File
@@ -0,0 +1,134 @@
<template x-if="$store.imports.wizard.open">
<dialog id="import-wizard" class="player-dialog import-wizard" aria-labelledby="import-wizard-title" style="--dialog-width: 640px"
x-data="{ get imports() { return $store.imports }, get wizard() { return $store.imports.wizard } }"
x-init="$nextTick(() => { if ($el.isConnected) { $el.showModal(); document.getElementById('import-wizard-title').focus() } })"
@dismiss-player-dialog.stop="imports.closeWizard($el)"
@cancel.prevent="imports.closeWizard($el)" @click.self="imports.closeWizard($el)" @keydown.space.stop>
<div class="player-dialog-surface">
{% let dialog_head_class = "" %}
{% let dialog_title_id = "import-wizard-title" %}
{% let dialog_title = t.player_import_new %}
{% let dialog_icon = "M12 3v12m-4-4 4 4 4-4M5 21h14" %}
{% let show_version = false %}
{% include "player/dialog_header.html" %}
<div class="import-wizard-body" :aria-busy="wizard.busy">
<p class="import-notice error" role="alert" x-show="wizard.error" x-text="wizard.error"></p>
<p class="import-notice" role="status" aria-live="polite" x-show="wizard.notice" x-text="wizard.notice"></p>
<template x-if="wizard.step === 'source'">
<div class="import-step">
<template x-if="!imports.providersLoaded && !wizard.error">
<div class="page-skeleton" role="status">
<span class="loading-label">{{ t.player_loading_content }}</span>
<div class="import-source skeleton-card" aria-hidden="true"><i class="skeleton-bar"></i><i class="skeleton-bar"></i></div>
</div>
</template>
<template x-for="provider in imports.providers.filter(entry => !wizard.provider || entry.id === wizard.provider)" :key="provider.id">
<section class="import-provider">
<h3 x-text="provider.name"></h3>
<div class="import-methods">
<button type="button" class="import-method" x-show="provider.methods.includes('file')"
@click="imports.chooseMethod(provider.id, 'file')">
<strong>{{ t.player_import_method_file }}</strong>
<small>{{ t.player_import_method_file_hint }}</small>
</button>
<button type="button" class="import-method" x-show="provider.methods.includes('api')"
@click="imports.chooseMethod(provider.id, 'api')">
<strong>{{ t.player_import_method_api }}</strong>
<small>{{ t.player_import_method_api_hint }}</small>
</button>
</div>
</section>
</template>
</div>
</template>
<template x-if="wizard.step === 'upload'">
<div class="import-step">
<p class="import-help">{{ t.player_import_upload_help }}</p>
<label class="release-action-btn primary import-file-button" :class="{disabled: wizard.busy}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M12 16V4m-4 4 4-4 4 4M5 20h14"/></svg>
<span>{{ t.player_import_choose_files }}</span>
<input type="file" class="import-file-input" multiple accept=".zip,.json,application/zip,application/json"
:disabled="wizard.busy" @change="imports.readFiles($event.target.files); $event.target.value = ''">
</label>
<p class="import-privacy">{{ t.player_import_privacy }}</p>
</div>
</template>
<template x-if="wizard.step === 'connect'">
<div class="import-step">
<p class="import-help">{{ t.player_import_api_help }}</p>
<button type="button" class="release-action-btn primary" :disabled="wizard.busy" @click="imports.signIn()">
{{ t.player_import_sign_in }}
</button>
</div>
</template>
<template x-if="wizard.step === 'select' && wizard.preview">
<div class="import-step">
<p class="import-help" x-show="wizard.fileNames.length"
x-text="imports.text('filesRead', {count: wizard.fileNames.length}) + (wizard.skipped ? ' ' + imports.text('filesSkipped', {count: wizard.skipped}) : '')"></p>
<p class="import-notice" x-show="wizard.preview.all_imported">{{ t.player_import_all_imported }}</p>
<div class="import-select-head">
<strong x-text="imports.text('selectedCount', {count: imports.selection().length, total: wizard.preview.playlists.length})"></strong>
<span>
<button type="button" class="import-text-action" @click="imports.selectAll(true)">{{ t.player_import_select_all }}</button>
<button type="button" class="import-text-action" @click="imports.selectAll(false)">{{ t.player_import_select_none }}</button>
</span>
</div>
<ul class="import-select-list" aria-label="{{ t.player_import_select_playlists }}">
<template x-for="playlist in wizard.preview.playlists" :key="playlist.source_key">
<li :class="{disabled: !imports.selectable(playlist)}">
<label class="import-select-row">
<input type="checkbox" :disabled="!imports.selectable(playlist)"
x-model="wizard.selected[playlist.source_key]">
<span class="import-select-copy">
<strong x-text="playlist.kind === 'favorites' ? imports.text('favorites') : playlist.title"></strong>
<small x-text="formatArtistCount(playlist.track_count, 'tracks') + (playlist.unsupported_count ? ' · ' + imports.text('unsupportedCount', {count: playlist.unsupported_count}) : '')"></small>
</span>
</label>
<template x-if="playlist.already_imported_in">
<p class="import-select-note">
<a :href="'#imports/' + playlist.already_imported_in" @click="imports.closeWizard($el.closest('dialog'), false)"
x-text="imports.text('alreadyImported', {id: playlist.already_imported_in})"></a>
</p>
</template>
<template x-if="playlist.available === false">
<p class="import-select-note">{{ t.player_import_unavailable }}</p>
</template>
<template x-if="playlist.similar_to && imports.selectable(playlist)">
<div class="import-select-note warning">
<span x-text="imports.text('similar', {id: playlist.similar_to.import_id})"></span>
<label x-show="wizard.selected[playlist.source_key]" x-transition.opacity.duration.120ms>
<input type="checkbox" x-model="wizard.confirmed[playlist.source_key]">
{{ t.player_import_confirm_similar }}
</label>
</div>
</template>
</li>
</template>
</ul>
<div class="import-consent">
<button type="button" role="switch" class="offline-switch-row" :aria-checked="wizard.federated && imports.federatedAvailable"
:disabled="!imports.federatedAvailable" aria-labelledby="import-federated-title"
aria-describedby="import-federated-consent" @click="wizard.federated = !wizard.federated">
<span class="offline-switch" aria-hidden="true"></span>
</button>
<span>
<strong id="import-federated-title">{{ t.player_import_federated }}</strong>
<small id="import-federated-consent" x-text="imports.federatedAvailable ? imports.text('federatedConsent') : imports.text('federatedOff')"></small>
</span>
</div>
</div>
</template>
<footer class="import-wizard-footer" x-show="wizard.step !== 'source'">
<button type="button" class="release-action-btn secondary" :disabled="wizard.busy" @click="imports.back()">{{ t.player_import_back }}</button>
<button type="button" class="release-action-btn primary" x-show="wizard.step === 'select'"
:disabled="!imports.canStart() && !imports.unconfirmed().length" @click="imports.begin()">{{ t.player_import_start }}</button>
</footer>
</div>
</div>
</dialog>
</template>
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more