Compare commits
21
Commits
No files matched your search
@@ -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
|
||||
|
||||
+1
-1
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -552,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)]
|
||||
@@ -624,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)]
|
||||
@@ -680,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 {
|
||||
@@ -1331,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 = [
|
||||
@@ -1412,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);
|
||||
@@ -1760,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(),
|
||||
@@ -1798,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(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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!(
|
||||
|
||||
@@ -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
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -759,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
@@ -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
|
||||
|
||||
@@ -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": []
|
||||
}
|
||||
@@ -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
@@ -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"),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
);
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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"));
|
||||
}
|
||||
+25
@@ -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),
|
||||
|
||||
@@ -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());
|
||||
|
||||
+142
-13
@@ -7292,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,
|
||||
@@ -7511,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,
|
||||
@@ -7525,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,
|
||||
@@ -10670,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",
|
||||
),
|
||||
|
||||
+1
@@ -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
|
||||
Vendored
+21
@@ -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.
|
||||
@@ -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); }
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
|
||||
+41
-2
@@ -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">
|
||||
@@ -2233,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,
|
||||
@@ -3106,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';
|
||||
|
||||
@@ -26,6 +26,7 @@ if ('serviceWorker' in navigator) {
|
||||
<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>
|
||||
@@ -39,11 +40,18 @@ if ('serviceWorker' in navigator) {
|
||||
{% block body %}
|
||||
{% include "player/shell.html" %}
|
||||
{% include "player/modals.html" %}
|
||||
{% if !guest %}{% include "player/get_app.html" %}{% endif %}
|
||||
{% 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" %}
|
||||
|
||||
@@ -38,6 +38,10 @@
|
||||
<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 }}
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -2852,7 +2852,7 @@ document.addEventListener('alpine:init', () => {
|
||||
if (GUEST) return;
|
||||
if (this._hashNav) return;
|
||||
const hash = location.hash || '#artists';
|
||||
if (playerOffline() && (/^#(?:listening|podcasts?|artistfed|releasefed|similar|share)(?:[/?]|$)/.test(hash) ||
|
||||
if (playerOffline() && (/^#(?:listening|podcasts?|imports|artistfed|releasefed|similar|share)(?:[/?]|$)/.test(hash) ||
|
||||
(hash.startsWith('#search?') && new URLSearchParams(hash.slice(8)).get('mode') === 'lyrics'))) {
|
||||
return this.openCollectionView('offline_unavailable', hash, options);
|
||||
}
|
||||
@@ -2877,6 +2877,8 @@ document.addEventListener('alpine:init', () => {
|
||||
return this._navigateFromHash({...options, fromHash:true});
|
||||
} else if (view === 'followed') {
|
||||
this.openCollectionView('followed', '#followed', options);
|
||||
} else if (view === 'imports') {
|
||||
Alpine.store('imports').route(id, params, options);
|
||||
} else if (view === 'artists' && new URLSearchParams(params).get('tab') === 'playlists') {
|
||||
this.openCollectionView('playlists', '#artists?tab=playlists', options);
|
||||
} else if (view === 'artists' && !id) {
|
||||
@@ -6109,19 +6111,29 @@ document.addEventListener('alpine:init', () => {
|
||||
const playlist = this.currentPlaylist();
|
||||
const playlistId = Number(playlist.id);
|
||||
const playlistTrackId = Number(track.playlist_track_id || 0);
|
||||
// Federated tracks have no playlist row; they are removed by content id.
|
||||
const contentId = playlistTrackId ? '' : String(track.content_id || '');
|
||||
const previous = (playlist.tracks || []).slice();
|
||||
if (!playlistTrackId) return;
|
||||
if (!playlistTrackId && !contentId) return;
|
||||
|
||||
const finish = this._startTrackChange(playlistId);
|
||||
playlist.tracks = previous.filter(item => Number(item.playlist_track_id || 0) !== playlistTrackId);
|
||||
playlist.tracks = previous.filter(item => playlistTrackId
|
||||
? Number(item.playlist_track_id || 0) !== playlistTrackId
|
||||
: item.playlist_track_id || item.content_id !== contentId);
|
||||
this._updateListTrackCount(playlistId, playlist.tracks.length);
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/player/playlists/${playlistId}/tracks`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ playlist_track_id: playlistTrackId }),
|
||||
});
|
||||
const res = playlistTrackId
|
||||
? await fetch(`/api/player/playlists/${playlistId}/tracks`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ playlist_track_id: playlistTrackId }),
|
||||
})
|
||||
: await fetch('/api/player/tracks/content/playlist', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ playlist_id: playlistId, content_id: contentId }),
|
||||
});
|
||||
if (!res.ok) throw new Error('remove failed');
|
||||
await this._refreshAfterTrackChange(playlist, res);
|
||||
} catch (err) {
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
{% include "player/podcasts.html" %}
|
||||
{% if !guest %}
|
||||
{% include "player/collection.html" %}
|
||||
{% include "player/imports.html" %}
|
||||
{% endif %}
|
||||
{% include "player/listening.html" %}
|
||||
<template x-if="$store.library.pendingDetail">
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
// Run only against a fresh disposable instance: federation disabled, no Spotify client id,
|
||||
// FURU_AGENT_STORAGE_DIR equal to FURU_TEST_STORAGE_DIR. The test seeds the library over psql
|
||||
// and writes small media files into the storage directory.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');
|
||||
const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs'),path=require('node:path');
|
||||
const {spawnSync}=require('node:child_process');
|
||||
const fflate=require('../src/player/vendor/fflate-0.8.2.min.js');
|
||||
const base=process.env.FURU_TEST_URL||'http://127.0.0.1:3020';
|
||||
const container=process.env.FURU_TEST_PG_CONTAINER||'furumi-libimport-test-pg';
|
||||
const database=process.env.FURU_TEST_DATABASE||'furumi_libimport_live';
|
||||
const storage=process.env.FURU_TEST_STORAGE_DIR;
|
||||
const shots=process.env.FURU_SCREENSHOT_DIR||path.resolve(__dirname,'../target');
|
||||
assert.ok(storage&&path.isAbsolute(storage),'FURU_TEST_STORAGE_DIR must be the absolute FURU_AGENT_STORAGE_DIR of the instance');
|
||||
|
||||
function sql(statement) {
|
||||
const result=spawnSync('docker',['exec','-i',container,'psql','-U','postgres','-d',database,'-At','-v','ON_ERROR_STOP=1'],{input:statement,encoding:'utf8'});
|
||||
assert.equal(result.status,0,result.stderr);return result.stdout.trim();
|
||||
}
|
||||
const quote=value=>`'${String(value).replace(/'/g,"''")}'`;
|
||||
const stamp="'2026-11-26T00:00:00Z'";
|
||||
// One library track with its artist, release and audio file in the storage directory.
|
||||
function seedTrack({artist,release,title,duration}) {
|
||||
const file=`library-import-live/${title.replace(/\W+/g,'-').toLowerCase()}.flac`;
|
||||
fs.mkdirSync(path.join(storage,'library-import-live'),{recursive:true});
|
||||
fs.writeFileSync(path.join(storage,file),`live import fixture: ${artist} - ${title}`);
|
||||
return sql(`WITH a AS (
|
||||
INSERT INTO furumusic__artist (name,name_sort,is_hidden,created_at,updated_at)
|
||||
SELECT ${quote(artist)},${quote(artist.toLowerCase())},false,${stamp},${stamp}
|
||||
WHERE NOT EXISTS (SELECT 1 FROM furumusic__artist WHERE name=${quote(artist)}) RETURNING id),
|
||||
artist AS (SELECT id FROM a UNION ALL SELECT id FROM furumusic__artist WHERE name=${quote(artist)}),
|
||||
r AS (INSERT INTO furumusic__release (title,title_sort,release_type,is_hidden,created_at,updated_at)
|
||||
VALUES (${quote(release)},${quote(release.toLowerCase())},'album',false,${stamp},${stamp}) RETURNING id),
|
||||
ra AS (INSERT INTO furumusic__release_artist (release_id,artist_id,position) SELECT r.id,artist.id,0 FROM r,artist),
|
||||
m AS (INSERT INTO furumusic__media_file (file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at)
|
||||
VALUES ('audio',${quote(file)},${quote(path.basename(file))},'audio/flac',64,${quote('live-'+file)},${stamp}) RETURNING id),
|
||||
t AS (INSERT INTO furumusic__track (title,title_sort,release_id,duration_seconds,audio_file_id,is_hidden,created_at,updated_at)
|
||||
SELECT ${quote(title)},${quote(title.toLowerCase())},r.id,${duration},m.id,false,${stamp},${stamp} FROM r,m RETURNING id),
|
||||
ta AS (INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) SELECT t.id,artist.id,'main',0 FROM t,artist)
|
||||
SELECT id FROM t;`);
|
||||
}
|
||||
|
||||
const track=(trackName,artistName,albumName)=>({track:{trackName,artistName,albumName,trackUri:'spotify:track:'+Buffer.from(trackName).toString('hex').slice(0,22)},
|
||||
episode:null,audiobook:null,localTrack:null,addedDate:'2026-11-01'});
|
||||
const exportFiles={
|
||||
'Spotify Account Data/Playlist1.json':{playlists:[
|
||||
{name:'Road trip',lastModifiedDate:'2026-11-01',collaborators:[],items:[
|
||||
track('Paranoid Android','Radiohead','OK Computer'),
|
||||
track('Come Together - Remastered 2009','The Beatles','Abbey Road (Remastered)'),
|
||||
{track:null,episode:{episodeName:'Episode 12: Tour stories',showName:'Example Music Podcast',episodeUri:'spotify:episode:4rOoJ6Egrf8K2IrywzwOMk'},audiobook:null,localTrack:null,addedDate:'2026-11-02'},
|
||||
track('Teardrop','Massive Attack','Mezzanine'),
|
||||
track('A track nobody has','Unknown Artist','Nowhere'),
|
||||
{track:null,episode:null,audiobook:null,localTrack:{uri:'spotify:local:My+Band:Garage+Tapes:Demo+Song:215'},addedDate:'2026-11-03'},
|
||||
track('Paranoid Android','Radiohead','OK Computer'),
|
||||
]},
|
||||
{name:'Rainy day',lastModifiedDate:'2026-11-01',collaborators:[],items:[
|
||||
track('Late Arrival','Night Owls','Moonlight'),
|
||||
track('Teardrop','Massive Attack','Mezzanine'),
|
||||
]},
|
||||
]},
|
||||
'Spotify Account Data/YourLibrary.json':{tracks:[
|
||||
{artist:'Björk',album:'Homogenic',track:'Jóga',uri:'spotify:track:4eeeeeeeeeeeeeeeeeeeee'},
|
||||
{artist:'Кино',album:'Группа крови',track:'Группа крови',uri:'spotify:track:5fffffffffffffffffffff'},
|
||||
],albums:[],shows:[],episodes:[],bannedTracks:[],artists:[],bannedArtists:[],other:[]},
|
||||
'Spotify Account Data/StreamingHistory0.json':[{endTime:'2026-11-01 10:00',artistName:'Private Artist',trackName:'Private listening history entry',msPlayed:1000}],
|
||||
};
|
||||
const exportZip=Buffer.from(fflate.zipSync(Object.fromEntries(Object.entries(exportFiles)
|
||||
.map(([name,value])=>[name,Buffer.from(JSON.stringify(value,null,2))]))));
|
||||
|
||||
(async()=>{
|
||||
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_PATH||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||
try{
|
||||
const context=await browser.newContext({viewport:{width:1440,height:1000},locale:'en-US'});
|
||||
const page=await context.newPage();const errors=[];page.on('pageerror',error=>errors.push(error.message));
|
||||
const posts=[];
|
||||
page.on('request',request=>{if(request.method()==='POST'&&new URL(request.url()).pathname.startsWith('/api/imports'))
|
||||
posts.push({path:new URL(request.url()).pathname,body:request.postData()});});
|
||||
const api=async(url,options)=>{const response=await context.request.fetch(base+url,options);
|
||||
assert.ok(response.ok(),`${url}: ${response.status()} ${await response.text()}`);return response.json();};
|
||||
const view=name=>page.waitForFunction(value=>window.Alpine?.store('library')?.view===value,name);
|
||||
const waitDone=async id=>{
|
||||
for(let attempt=0;attempt<120;attempt++){
|
||||
const record=await api(`/api/imports/${id}`);
|
||||
if(record.status==='done'&&record.statistics.pending===0&&record.statistics.publication_pending===0)return record;
|
||||
assert.ok(['queued','running','done'].includes(record.status),JSON.stringify(record));
|
||||
await new Promise(resolve=>setTimeout(resolve,500));
|
||||
}
|
||||
throw new Error(`import ${id} did not finish`);
|
||||
};
|
||||
const playlistTitles=async id=>(await api(`/api/player/playlists/${id}`)).tracks.map(entry=>entry.title);
|
||||
const noHorizontalScroll=()=>page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth);
|
||||
|
||||
// Administrator and library: exact matches, a remaster-only-on-one-side doubt, the rest missing.
|
||||
await page.goto(base+'/admin/setup');
|
||||
assert.equal(await page.locator('[name=confirm_password]').count(),1,'the instance already has an administrator; start a fresh one');
|
||||
await page.locator('[name=username]').fill('importer');
|
||||
await page.locator('[name=password]').fill('library-import-password');
|
||||
await page.locator('[name=confirm_password]').fill('library-import-password');
|
||||
await page.locator('form button[type=submit]').click();await page.waitForURL('**/admin/v2');
|
||||
const paranoid=seedTrack({artist:'Radiohead',release:'OK Computer',title:'Paranoid Android',duration:387});
|
||||
const together=seedTrack({artist:'The Beatles',release:'Abbey Road',title:'Come Together',duration:259});
|
||||
const teardrop=seedTrack({artist:'Massive Attack',release:'Mezzanine',title:'Teardrop',duration:330});
|
||||
const joga=seedTrack({artist:'Björk',release:'Homogenic',title:'Jóga',duration:305});
|
||||
assert.ok([paranoid,together,teardrop,joga].every(id=>Number(id)>0));
|
||||
|
||||
// The account menu leads to the page: Followed, Import library, Settings.
|
||||
await page.goto(base+'/');await page.waitForFunction(()=>window.Alpine?.store('library'));
|
||||
await page.locator('.sidebar-account-trigger').click();
|
||||
const labels=(await page.locator('#sidebar-account-actions .account-action-list > *').allInnerTexts()).map(text=>text.trim());
|
||||
const at=label=>labels.indexOf(label);
|
||||
assert.ok(at('Followed')>=0&&at('Import library')===at('Followed')+1&&at('Settings')===at('Import library')+1,JSON.stringify(labels));
|
||||
await page.locator('#sidebar-account-actions').getByRole('link',{name:'Import library'}).click();
|
||||
await view('imports');assert.ok(page.url().endsWith('#imports'));
|
||||
await page.getByText('No imports yet. Start with New import.').waitFor();
|
||||
|
||||
// Wizard: Spotify data export; only Playlist*.json and YourLibrary.json leave the browser.
|
||||
const upload=async()=>{
|
||||
await page.getByRole('button',{name:'New import'}).click();
|
||||
const dialog=page.locator('dialog#import-wizard');await dialog.waitFor();
|
||||
await dialog.getByRole('button',{name:/Data export/}).click();
|
||||
await dialog.locator('input[type=file]').setInputFiles({name:'my_spotify_data.zip',mimeType:'application/zip',buffer:exportZip});
|
||||
await dialog.locator('.import-select-list li').nth(2).waitFor();
|
||||
return dialog;
|
||||
};
|
||||
const dialog=await upload();
|
||||
const previews=posts.filter(post=>post.path==='/api/imports/preview');
|
||||
assert.equal(previews.length,1);
|
||||
const preview=JSON.parse(previews[0].body);
|
||||
assert.deepEqual(preview.files.map(file=>file.name).sort(),['Spotify Account Data/Playlist1.json','Spotify Account Data/YourLibrary.json']);
|
||||
assert.ok(!previews[0].body.includes('Private listening history'),'listening history reached the server');
|
||||
await dialog.getByText('Files read: 2.',{exact:true}).waitFor();
|
||||
const rows=dialog.locator('.import-select-list li');
|
||||
assert.deepEqual((await rows.locator('.import-select-copy strong').allInnerTexts()).map(text=>text.trim()),['Liked Songs','Road trip','Rainy day']);
|
||||
const boxes=rows.locator('input[type=checkbox]');
|
||||
for(let index=0;index<3;index++)assert.equal(await boxes.nth(index).isChecked(),true);
|
||||
await dialog.getByText('not supported: 2').waitFor();
|
||||
assert.equal(await dialog.getByRole('switch').isDisabled(),true,'federation is off on this server');
|
||||
await dialog.getByText('Federation is turned off on this server.').waitFor();
|
||||
await page.screenshot({path:path.join(shots,'library-import-live-wizard.png')});
|
||||
await dialog.getByRole('button',{name:'Start import'}).click();
|
||||
await view('import_detail');await dialog.waitFor({state:'detached'});
|
||||
const start=posts.find(post=>post.path==='/api/imports');
|
||||
const started=JSON.parse(start.body);
|
||||
assert.equal(started.selection.length,3);assert.equal(started.federated_search,false);
|
||||
assert.ok(!start.body.includes('Private listening history'));
|
||||
const id=Number(page.url().match(/#imports\/(\d+)$/)[1]);assert.ok(id>0);
|
||||
|
||||
// The real worker resolves and publishes; the page shows the statistics.
|
||||
const record=await waitDone(id);
|
||||
const stats=record.statistics;
|
||||
assert.deepEqual({total:stats.total,matched_local:stats.matched_local,matched_federation:stats.matched_federation,ambiguous:stats.ambiguous,
|
||||
unmatched:stats.unmatched,unsupported:stats.unsupported,failed:stats.failed,published:stats.published,duplicate:stats.duplicate},
|
||||
{total:11,matched_local:5,matched_federation:0,ambiguous:1,unmatched:3,unsupported:2,failed:0,published:4,duplicate:1},JSON.stringify(stats));
|
||||
await page.locator('.import-heading .import-status',{hasText:'Done'}).waitFor({timeout:10000});
|
||||
const shown=async()=>(await page.locator('.import-stats dd').allInnerTexts()).map(text=>text.trim());
|
||||
await page.waitForFunction(()=>document.querySelector('.import-stats dd')?.textContent.trim()==='11');
|
||||
assert.deepEqual(await shown(),['11','5','4','1','3','2']);
|
||||
|
||||
// Private playlists in source order without repeats, in the API and the sidebar.
|
||||
const detail=await api(`/api/imports/${id}`);
|
||||
const targets=Object.fromEntries(detail.source_playlists.map(playlist=>[playlist.title,playlist.target_playlist_id]));
|
||||
assert.deepEqual(Object.keys(targets).sort(),['Liked Songs','Rainy day','Road trip']);
|
||||
assert.ok(Object.values(targets).every(target=>target>0));
|
||||
const own=await api('/api/player/playlists');
|
||||
const names={'Road trip':'Road trip','Rainy day':'Rainy day','Liked Songs':'Liked Songs (Spotify)'};
|
||||
for(const [title,target] of Object.entries(targets)){
|
||||
const playlist=own.find(entry=>entry.id===target);
|
||||
assert.ok(playlist,`${title} is not among the user's playlists`);
|
||||
assert.equal(playlist.title,names[title]);assert.equal(playlist.is_public,false,JSON.stringify(playlist));
|
||||
}
|
||||
assert.deepEqual(await playlistTitles(targets['Road trip']),['Paranoid Android','Teardrop']);
|
||||
assert.deepEqual(await playlistTitles(targets['Rainy day']),['Teardrop']);
|
||||
assert.deepEqual(await playlistTitles(targets['Liked Songs']),['Jóga']);
|
||||
await page.reload();await view('import_detail');
|
||||
for(const title of Object.values(names))await page.locator('.sidebar-left').getByText(title,{exact:true}).first().waitFor();
|
||||
await page.locator('.import-item').first().waitFor();
|
||||
await page.screenshot({path:path.join(shots,'library-import-live-detail.png'),fullPage:true});
|
||||
// The detail page links to the playlist, which the player shows in source order.
|
||||
await page.locator('.import-playlists a',{hasText:'Road trip'}).click();
|
||||
await view('playlist_detail');assert.ok(page.url().endsWith(`#playlist/${targets['Road trip']}`));
|
||||
await page.waitForFunction(()=>Alpine.store('library').currentPlaylist?.tracks?.length===2);
|
||||
const rowTitles=page.locator('.playlist-track-row .track-title');
|
||||
assert.deepEqual((await rowTitles.allInnerTexts()).map(text=>text.trim()),['Paranoid Android','Teardrop']);
|
||||
await page.goBack();await view('import_detail');await page.locator('.import-item').first().waitFor();
|
||||
|
||||
// Filters list the unmatched and unsupported entries.
|
||||
const filter=async(label,count)=>{
|
||||
await page.locator('.import-filters button',{hasText:label}).click();
|
||||
await page.waitForFunction(n=>{const store=Alpine.store('imports');return store.itemsLoaded&&!store.itemsLoading&&store.items.length===n;},count);
|
||||
return (await page.locator('.import-item > .import-item-copy > strong').allInnerTexts()).map(text=>text.trim());
|
||||
};
|
||||
assert.deepEqual((await filter('Not found',3)).sort(),['A track nobody has','Late Arrival','Группа крови'].sort());
|
||||
assert.deepEqual(await filter('Not supported',2),['Episode 12: Tour stories','Demo Song']);
|
||||
await page.locator('.import-item',{hasText:'Podcast episode'}).waitFor();
|
||||
await page.locator('.import-item',{hasText:'Local file'}).waitFor();
|
||||
assert.equal((await filter('All',11)).length,11);
|
||||
|
||||
// A manual choice for the remaster doubt is published by the next pass.
|
||||
assert.deepEqual(await filter('Needs a choice',1),['Come Together - Remastered 2009']);
|
||||
const candidate=page.locator('.import-candidate',{hasText:'Come Together'}).first();
|
||||
await candidate.getByText('Abbey Road',{exact:false}).waitFor();
|
||||
await candidate.getByRole('button',{name:'Choose'}).click();
|
||||
await page.getByRole('status').filter({hasText:'The track will be added to the playlist.'}).waitFor();
|
||||
const chosen=posts.find(post=>/\/items\/\d+\/match$/.test(post.path));assert.deepEqual(JSON.parse(chosen.body),{candidate:0});
|
||||
const afterChoice=(await waitDone(id)).statistics;
|
||||
assert.equal(afterChoice.ambiguous,0);assert.equal(afterChoice.matched_local,6);assert.equal(afterChoice.published,5);
|
||||
assert.deepEqual(await playlistTitles(targets['Road trip']),['Paranoid Android','Teardrop','Come Together']);
|
||||
const choice=(await api(`/api/imports/${id}/items?status=matched&q=Come`)).items;
|
||||
assert.equal(choice.length,1);assert.equal(choice[0].publication_status,'published');
|
||||
|
||||
// Importing the same export again: every playlist is flagged as already imported.
|
||||
await page.goto(base+'/#imports');await view('imports');
|
||||
await page.locator('.import-history-row').first().waitFor();
|
||||
const again=await upload();
|
||||
await again.getByText('This export was already imported.').waitFor();
|
||||
assert.equal(await again.getByText(`Already imported in #${id}`).count(),3);
|
||||
for(let index=0;index<3;index++)assert.equal(await again.locator('.import-select-list li input[type=checkbox]').nth(index).isDisabled(),true);
|
||||
assert.equal(await again.getByRole('button',{name:'Start import'}).isDisabled(),true);
|
||||
await page.screenshot({path:path.join(shots,'library-import-live-again.png')});
|
||||
await again.locator('.player-dialog-close').click();await again.waitFor({state:'detached'});
|
||||
|
||||
// Retry unmatched finds a track added to the library meanwhile and appends it.
|
||||
seedTrack({artist:'Night Owls',release:'Moonlight',title:'Late Arrival',duration:200});
|
||||
await page.goto(`${base}/#imports/${id}`);await view('import_detail');
|
||||
await page.locator('.import-heading .import-status',{hasText:'Done'}).waitFor();
|
||||
await page.getByRole('button',{name:'Retry unmatched'}).click();
|
||||
const panel=page.locator('#import-retry-panel');await panel.waitFor();
|
||||
assert.equal(await panel.getByRole('switch').isDisabled(),true);
|
||||
await panel.getByRole('button',{name:'Retry',exact:true}).click();
|
||||
await page.getByRole('status').filter({hasText:'Unmatched tracks will be searched again.'}).waitFor();
|
||||
const retry=posts.find(post=>post.path===`/api/imports/${id}/resync`);assert.ok(retry,'Retry unmatched was not sent');
|
||||
const afterRetry=(await waitDone(id)).statistics;
|
||||
assert.equal(afterRetry.unmatched,2);assert.equal(afterRetry.matched_local,7);assert.equal(afterRetry.published,6);
|
||||
assert.deepEqual(await playlistTitles(targets['Rainy day']),['Teardrop','Late Arrival']);
|
||||
await page.waitForFunction(()=>document.querySelector('.import-stats dd')?.textContent.trim()==='11'
|
||||
&&document.querySelectorAll('.import-stats dd')[2]?.textContent.trim()==='6',null,{timeout:10000});
|
||||
|
||||
// Mobile: the history and the details fit the screen.
|
||||
await page.setViewportSize({width:390,height:844});
|
||||
await page.goto(base+'/#imports');await view('imports');await page.locator('.import-history-row').first().waitFor();
|
||||
assert.equal(await noHorizontalScroll(),true,'the import history scrolls horizontally');
|
||||
await page.screenshot({path:path.join(shots,'library-import-live-mobile.png')});
|
||||
await page.goto(`${base}/#imports/${id}`);await view('import_detail');await page.locator('.import-item').first().waitFor();
|
||||
assert.equal(await noHorizontalScroll(),true,'the import details scroll horizontally');
|
||||
await page.screenshot({path:path.join(shots,'library-import-live-mobile-detail.png'),fullPage:true});
|
||||
await page.setViewportSize({width:1440,height:1000});
|
||||
|
||||
// Delete history keeps the created playlists and their tracks.
|
||||
page.once('dialog',prompt=>{assert.match(prompt.message(),/Created playlists stay/);prompt.accept();});
|
||||
await page.getByRole('button',{name:'Delete history'}).click();
|
||||
await view('imports');
|
||||
await page.getByText('No imports yet. Start with New import.').waitFor();
|
||||
assert.deepEqual((await api('/api/imports')).imports,[]);
|
||||
assert.equal((await context.request.get(`${base}/api/imports/${id}`)).status(),404);
|
||||
assert.deepEqual(await playlistTitles(targets['Road trip']),['Paranoid Android','Teardrop','Come Together']);
|
||||
assert.deepEqual(await playlistTitles(targets['Rainy day']),['Teardrop','Late Arrival']);
|
||||
assert.deepEqual(await playlistTitles(targets['Liked Songs']),['Jóga']);
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: menu order, ZIP with playlist files only, real worker, statistics, private playlists in source order, filters, manual choice, already imported, Retry unmatched, Delete history, mobile');
|
||||
} finally {await browser.close();}
|
||||
})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
@@ -0,0 +1,241 @@
|
||||
// Render first: FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1 cargo test library_import::tests::web
|
||||
// Uses the real rendered player with isolated API fixtures; no service or user data.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');
|
||||
const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
|
||||
const root=path.resolve(__dirname,'..');
|
||||
const fflate=require('../src/player/vendor/fflate-0.8.2.min.js');
|
||||
const html=fs.readFileSync(path.join(root,'target/library-import-player-fixture.html'),'utf8');
|
||||
const zipReader=fs.readFileSync(path.join(root,'src/player/vendor/fflate-0.8.2.min.js'),'utf8');
|
||||
const shots=process.env.FURU_SCREENSHOT_DIR||path.join(root,'target');
|
||||
const host='http://library-import.test';
|
||||
|
||||
const stats=(extra={})=>({total:6,pending:0,matched_local:2,matched_federation:1,ambiguous:1,unmatched:1,unsupported:1,failed:0,
|
||||
published:3,publication_pending:0,duplicate:0,already_present:0,no_content_id:0,deferred_sync_limit:0,paused:0,publication_failed:0,catalog_errors:0,...extra});
|
||||
const history=[
|
||||
{id:4,provider:'spotify',source_type:'file',status:'running',phase:'resolve_local',federated_search:false,cancel_requested:false,
|
||||
statistics:stats({pending:3,published:0}),error:null,created_at:'2026-11-26T10:00:00Z',updated_at:'2026-11-26T10:00:00Z',last_resync_at:null,playlists:[]},
|
||||
{id:3,provider:'spotify',source_type:'api',status:'needs_reauth',phase:'fetching',federated_search:false,cancel_requested:false,
|
||||
statistics:stats({total:0,matched_local:0,matched_federation:0,ambiguous:0,unmatched:0,unsupported:0,published:0}),error:null,
|
||||
created_at:'2026-11-25T10:00:00Z',updated_at:'2026-11-25T10:00:00Z',last_resync_at:null,playlists:[]},
|
||||
{id:2,provider:'spotify',source_type:'file',status:'done',phase:null,federated_search:false,cancel_requested:false,statistics:stats(),error:null,
|
||||
created_at:'2026-11-24T10:00:00Z',updated_at:'2026-11-24T10:00:00Z',last_resync_at:null,
|
||||
playlists:[{id:20,title:'Road trip',target_playlist_id:500,target_deleted:false},{id:21,title:'Liked Songs (Spotify)',target_playlist_id:501,target_deleted:false}]},
|
||||
];
|
||||
const detail=id=>({...history.find(record=>record.id===id),source_playlists:[
|
||||
{id:20,kind:'playlist',ordinal:0,title:'Road trip',description:null,target_playlist_id:500,target_created_at:null,target_deleted:false,publication_paused:false,total:4,matched:2,published:2},
|
||||
{id:21,kind:'favorites',ordinal:1,title:'Liked Songs (Spotify)',description:null,target_playlist_id:501,target_created_at:null,target_deleted:true,publication_paused:true,total:2,matched:1,published:1},
|
||||
],attempt:null});
|
||||
const items=[
|
||||
{id:90,playlist_id:20,position:0,metadata:{kind:'track',title:'Northern Lights',artists:['Aurora Band'],album:'Skies',duration_ms:215000},
|
||||
resolution_status:'matched',resolution_note:null,match_origin:'local',publication_status:'published',candidates:null},
|
||||
{id:91,playlist_id:20,position:1,metadata:{kind:'track',title:'Harbour (Live)',artists:['Sea Choir'],album:'Live at the Pier',duration_ms:301000},
|
||||
resolution_status:'ambiguous',resolution_note:null,match_origin:null,publication_status:'not_ready',
|
||||
candidates:[{origin:'local',title:'Harbour',artists:['Sea Choir'],album:'Pier',duration_seconds:300,content_id:null,track_id:7},
|
||||
{origin:'federation',title:'Harbour (Live)',artists:['Sea Choir'],album:'Live at the Pier',duration_seconds:302,content_id:'b3:'+'1'.repeat(64)}]},
|
||||
{id:92,playlist_id:20,position:2,metadata:{kind:'track',title:'A track nobody has',artists:['Unknown Artist']},
|
||||
resolution_status:'unmatched',resolution_note:'not_found',publication_status:'not_ready',candidates:null},
|
||||
{id:93,playlist_id:21,position:0,metadata:{kind:'episode',title:'A podcast episode',artists:[]},
|
||||
resolution_status:'unsupported',resolution_note:'episode',publication_status:'not_ready',candidates:null},
|
||||
];
|
||||
const exportZip=Buffer.from(fflate.zipSync({
|
||||
'Spotify Account Data/Playlist1.json':Buffer.from(JSON.stringify({playlists:[{name:'Road trip',items:[{track:{trackName:'Northern Lights',artistName:'Aurora Band'}}]}]},null,2)),
|
||||
'Spotify Account Data/YourLibrary.json':Buffer.from(JSON.stringify({tracks:[{artist:'Sea Choir',track:'Harbour',album:'Pier'}]})),
|
||||
'Spotify Account Data/StreamingHistory_music_0.json':Buffer.from(JSON.stringify([{trackName:'Private listening history entry'}])),
|
||||
'Spotify Account Data/Userdata.json':Buffer.from(JSON.stringify({email:'listener@example.test'})),
|
||||
}));
|
||||
const fedTrack={content_id:'b3:'+'2'.repeat(64),position:1,federation:{content_id:'b3:'+'2'.repeat(64),owner:'peer-a',item_id:'item-2',
|
||||
title:'Peer song',artist_names:['Peer Artist'],featured_artist_names:[],duration_seconds:200,release_title:'Peer album'}};
|
||||
|
||||
(async()=>{
|
||||
const browser=await chromium.launch({headless:true,...(process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
|
||||
try{
|
||||
const requests=[],errors=[];
|
||||
const context=await browser.newContext({viewport:{width:1440,height:1000}});
|
||||
const fixture=async route=>{
|
||||
const request=route.request(),url=new URL(request.url()),method=request.method();
|
||||
if(url.origin!==host)return route.fulfill({status:404,body:''});
|
||||
if(url.pathname==='/')return route.fulfill({contentType:'text/html',body:html});
|
||||
if(url.pathname==='/vendor/fflate-0.8.2.js'){requests.push({method,path:url.pathname});return route.fulfill({contentType:'text/javascript',body:zipReader});}
|
||||
if(!url.pathname.startsWith('/api/'))return route.fulfill({status:404,body:''});
|
||||
const body=request.postData()?JSON.parse(request.postData()):undefined;
|
||||
requests.push({method,path:url.pathname,search:url.search,body});
|
||||
const json=data=>route.fulfill({json:data});
|
||||
if(url.pathname==='/api/player/me')return json({id:1,name:'Listener',username:'listener',role:'user'});
|
||||
if(url.pathname==='/api/imports/providers')return json({providers:[{id:'spotify',name:'Spotify',methods:['file','api']}],federated_search_available:true});
|
||||
if(url.pathname==='/api/imports'&&method==='GET')return json({imports:history});
|
||||
if(url.pathname==='/api/imports/preview')return json({provider:'spotify',source:'file',all_imported:false,federated_search_available:true,playlists:[
|
||||
{source_key:'sha256:road',kind:'playlist',title:'Road trip',description:null,track_count:1,unsupported_count:0,available:true,already_imported_in:null,similar_to:null},
|
||||
{source_key:'sha256:old',kind:'playlist',title:'Old mix',description:null,track_count:12,unsupported_count:0,available:true,already_imported_in:2,similar_to:null},
|
||||
{source_key:'sha256:gym',kind:'playlist',title:'Gym',description:null,track_count:40,unsupported_count:2,available:true,already_imported_in:null,similar_to:{import_id:2,target_playlist_id:500}},
|
||||
{source_key:'sha256:liked',kind:'favorites',title:'Liked Songs',description:null,track_count:1,unsupported_count:0,available:true,already_imported_in:null,similar_to:null},
|
||||
]});
|
||||
if(url.pathname==='/api/imports'&&method==='POST')return json({id:2,status:'queued'});
|
||||
let match=url.pathname.match(/^\/api\/imports\/(\d+)(\/.*)?$/);
|
||||
if(match){
|
||||
const id=Number(match[1]),rest=match[2]||'';
|
||||
if(rest==='/items'){
|
||||
const status=url.searchParams.get('status');
|
||||
return json({items:items.filter(item=>!status||item.resolution_status===status),next:null});
|
||||
}
|
||||
if(rest.endsWith('/match'))return json({resolution_status:'matched',publication_status:'pending'});
|
||||
if(rest==='/resync')return json({status:'queued'});
|
||||
if(rest==='/cancel')return json({status:'cancelling'});
|
||||
if(rest.endsWith('/recreate'))return json({status:'requested'});
|
||||
if(method==='DELETE')return json({ok:true});
|
||||
return json(detail(id));
|
||||
}
|
||||
if(url.pathname.startsWith('/api/imports/providers/spotify/authorize'))return route.fulfill({contentType:'text/html',body:'<p>Spotify sign-in</p>'});
|
||||
if(url.pathname==='/api/player/playlists/500')return json({id:500,title:'Road trip',kind:'user',is_own:true,is_public:false,owner_name:'Listener',tracks:[
|
||||
{id:7,playlist_track_id:70,content_id:'b3:'+'3'.repeat(64),title:'Northern Lights',artists:[{id:1,name:'Aurora Band'}],featured_artists:[],duration_seconds:215,release_title:'Skies',stream_url:'/api/player/stream/7'}]});
|
||||
if(url.pathname==='/api/player/playlists/500/federation-tracks')return json([fedTrack]);
|
||||
if(url.pathname==='/api/player/tracks/content/playlist')return json({ok:true});
|
||||
if(url.pathname==='/api/player/playlists')return json([{id:500,title:'Road trip',kind:'user',is_own:true,track_count:2}]);
|
||||
return json([]);
|
||||
};
|
||||
await context.route('**/*',fixture);
|
||||
const page=await context.newPage();
|
||||
page.on('pageerror',error=>errors.push(error.message));
|
||||
if(process.env.DEBUG)page.on('console',message=>console.log('console:',message.text()));
|
||||
const view=async name=>page.waitForFunction(v=>window.Alpine?.store('library')?.view===v,name);
|
||||
|
||||
// The menu entry sits between Followed and Settings and opens the page.
|
||||
await page.goto(host+'/#artists');await view('artists');
|
||||
await page.locator('.sidebar-account-trigger').click();
|
||||
const labels=await page.locator('#sidebar-account-actions .account-action-list > *').allInnerTexts();
|
||||
const at=label=>labels.findIndex(text=>text.trim()===label);
|
||||
assert.ok(at('Followed')>=0&&at('Import library')===at('Followed')+1&&at('Settings')===at('Import library')+1,JSON.stringify(labels));
|
||||
await page.locator('#sidebar-account-actions').getByRole('link',{name:'Import library'}).click();
|
||||
await view('imports');assert.ok(page.url().endsWith('#imports'));
|
||||
await page.getByRole('heading',{name:'Import library',level:1}).waitFor();
|
||||
await page.locator('.import-history-row').nth(2).waitFor();
|
||||
assert.equal(await page.locator('#sidebar-account-actions a[href="#imports"]').getAttribute('aria-current'),'page');
|
||||
assert.equal(await page.locator('.import-history-row').count(),3);
|
||||
assert.equal(await page.locator('.import-history-row').first().locator('.import-status').innerText(),'Running');
|
||||
assert.equal(await page.locator('.import-history-playlists a').first().getAttribute('href'),'#playlist/500');
|
||||
await page.screenshot({path:path.join(shots,'library-import-history.png')});
|
||||
// The running import is polled every 3 seconds.
|
||||
const lists=()=>requests.filter(r=>r.path==='/api/imports'&&r.method==='GET').length;
|
||||
const before=lists();await page.waitForTimeout(3400);assert.ok(lists()>before,'history was not polled');
|
||||
|
||||
// Wizard: Data export ZIP; only playlist files reach the server.
|
||||
await page.getByRole('button',{name:'New import'}).click();
|
||||
const dialog=page.locator('dialog#import-wizard');await dialog.waitFor();
|
||||
assert.equal(await dialog.evaluate(element=>element.open&&element.matches('.player-dialog')),true);
|
||||
assert.equal(requests.filter(r=>r.path==='/vendor/fflate-0.8.2.js').length,0,'the ZIP reader must load lazily');
|
||||
await dialog.getByRole('button',{name:/Data export/}).click();
|
||||
await dialog.locator('input[type=file]').setInputFiles({name:'my_spotify_data.zip',mimeType:'application/zip',buffer:exportZip});
|
||||
await dialog.locator('.import-select-list li').nth(3).waitFor();
|
||||
const preview=requests.find(r=>r.path==='/api/imports/preview');
|
||||
assert.deepEqual(preview.body.files.map(file=>file.name).sort(),['Spotify Account Data/Playlist1.json','Spotify Account Data/YourLibrary.json']);
|
||||
assert.ok(!JSON.stringify(preview.body).includes('Private listening history'));
|
||||
assert.ok(!JSON.stringify(preview.body).includes('listener@example.test'));
|
||||
assert.equal(requests.filter(r=>r.path==='/vendor/fflate-0.8.2.js').length,1);
|
||||
const boxes=dialog.locator('.import-select-list li input[type=checkbox]');
|
||||
assert.equal(await boxes.nth(0).isChecked(),true);
|
||||
assert.equal(await boxes.nth(1).isDisabled(),true);
|
||||
assert.equal(await boxes.nth(2).isChecked(),false);
|
||||
await dialog.getByText('Already imported in #2').waitFor();
|
||||
await boxes.nth(2).check();
|
||||
await dialog.getByText('Create a new playlist').waitFor();
|
||||
const consent=dialog.getByRole('switch');
|
||||
assert.equal(await consent.getAttribute('aria-checked'),'false');
|
||||
await dialog.getByText('Participants receive only artist names.',{exact:false}).waitFor();
|
||||
await page.screenshot({path:path.join(shots,'library-import-wizard.png')});
|
||||
await dialog.getByRole('button',{name:'Start import'}).click();
|
||||
await dialog.getByText('Confirm creating new playlists',{exact:false}).waitFor();
|
||||
assert.equal(requests.filter(r=>r.path==='/api/imports'&&r.method==='POST').length,0);
|
||||
await dialog.locator('.import-select-note label input').check();
|
||||
await consent.click();assert.equal(await consent.getAttribute('aria-checked'),'true');
|
||||
await dialog.getByRole('button',{name:'Start import'}).click();
|
||||
await view('import_detail');await dialog.waitFor({state:'detached'});
|
||||
const created=requests.find(r=>r.path==='/api/imports'&&r.method==='POST');
|
||||
assert.deepEqual(created.body.selection,['sha256:road','sha256:gym','sha256:liked']);
|
||||
assert.deepEqual(created.body.confirm_similar,['sha256:gym']);
|
||||
assert.equal(created.body.federated_search,true);
|
||||
assert.equal(created.body.files.length,2);
|
||||
assert.ok(page.url().endsWith('#imports/2'));
|
||||
|
||||
// Details: statistics, playlists, filters, a manual choice and Retry with consent.
|
||||
await page.locator('.import-item').nth(3).waitFor();
|
||||
assert.equal(await page.locator('.import-stats dd').first().innerText(),'6');
|
||||
await page.getByText('The playlist was deleted').waitFor();
|
||||
await page.getByRole('button',{name:'Create again'}).click();
|
||||
await page.waitForFunction(()=>Alpine.store('imports').message==='The playlist will be created again.');
|
||||
assert.ok(requests.some(r=>r.path==='/api/imports/2/playlists/21/recreate'&&r.method==='POST'));
|
||||
await page.screenshot({path:path.join(shots,'library-import-detail.png'),fullPage:true});
|
||||
await page.locator('.import-filters button',{hasText:'Needs a choice'}).click();
|
||||
await page.waitForFunction(()=>Alpine.store('imports').items.length===1);
|
||||
assert.ok(requests.some(r=>r.path==='/api/imports/2/items'&&r.search==='?status=ambiguous'));
|
||||
await page.locator('.import-candidate').nth(1).getByRole('button',{name:'Choose'}).click();
|
||||
await page.waitForFunction(()=>Alpine.store('imports').message==='The track will be added to the playlist.'||Alpine.store('imports').items.every(item=>item.resolution_status!=='ambiguous'));
|
||||
assert.deepEqual(requests.find(r=>r.path==='/api/imports/2/items/91/match').body,{candidate:1});
|
||||
await page.getByRole('button',{name:'Retry unmatched'}).click();
|
||||
const panel=page.locator('#import-retry-panel');await panel.waitFor();
|
||||
await panel.getByRole('switch').click();
|
||||
await panel.getByRole('button',{name:'Retry'}).click();
|
||||
await page.waitForFunction(()=>Alpine.store('imports').message==='Unmatched tracks will be searched again.');
|
||||
assert.deepEqual(requests.find(r=>r.path==='/api/imports/2/resync').body,{federated_search:true});
|
||||
|
||||
// Delete history keeps playlists; the page returns to the list.
|
||||
page.once('dialog',prompt=>{assert.match(prompt.message(),/Created playlists stay/);prompt.accept();});
|
||||
await page.getByRole('button',{name:'Delete history'}).click();
|
||||
await view('imports');
|
||||
assert.ok(requests.some(r=>r.path==='/api/imports/2'&&r.method==='DELETE'));
|
||||
|
||||
// A Spotify import waiting for a sign-in continues through the provider.
|
||||
await page.goto(host+'/#imports/3?error=account_mismatch');await view('import_detail');
|
||||
await page.getByText('Sign in with the Spotify account used for this import.').waitFor();
|
||||
assert.ok(page.url().endsWith('#imports/3'));
|
||||
await Promise.all([page.waitForURL('**/api/imports/providers/spotify/authorize?import_id=3'),
|
||||
page.getByRole('button',{name:'Sign in to Spotify again'}).click()]);
|
||||
|
||||
// A federated track can be removed from the playlist in edit mode.
|
||||
await page.goto(host+'/#playlist/500');await view('playlist_detail');
|
||||
await page.waitForFunction(()=>Alpine.store('library').currentPlaylist?.tracks?.length===2);
|
||||
await page.evaluate(()=>Alpine.store('playlists').toggleEditCurrent());
|
||||
await page.locator('.playlist-track-row').nth(1).locator('.playlist-track-remove').click();
|
||||
await page.waitForFunction(()=>Alpine.store('library').currentPlaylist.tracks.length===1);
|
||||
assert.deepEqual(requests.find(r=>r.path==='/api/player/tracks/content/playlist'&&r.method==='DELETE').body,
|
||||
{playlist_id:500,content_id:fedTrack.content_id});
|
||||
|
||||
// Mobile: the popover menu, the page and the wizard fit the screen.
|
||||
await page.setViewportSize({width:390,height:844});
|
||||
await page.goto(host+'/#artists');await view('artists');
|
||||
await page.locator('.mobile-account-chip').click();
|
||||
const mobileMenu=page.locator('#mobile-account-actions');
|
||||
await mobileMenu.getByRole('link',{name:'Import library'}).waitFor({state:'visible'});
|
||||
const mobileLabels=await mobileMenu.locator('.account-action-list > *').allInnerTexts();
|
||||
assert.equal(mobileLabels.findIndex(text=>text.trim()==='Import library'),mobileLabels.findIndex(text=>text.trim()==='Followed')+1);
|
||||
await page.waitForTimeout(250);await page.screenshot({path:path.join(shots,'library-import-mobile-menu.png')});
|
||||
await mobileMenu.getByRole('link',{name:'Import library'}).click();await view('imports');
|
||||
await page.locator('.import-history-row').first().waitFor();
|
||||
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
|
||||
await page.waitForTimeout(250);await page.screenshot({path:path.join(shots,'library-import-mobile.png')});
|
||||
await page.goto(host+'/#imports/2');await view('import_detail');await page.locator('.import-item').first().waitFor();
|
||||
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
|
||||
await page.screenshot({path:path.join(shots,'library-import-mobile-detail.png'),fullPage:true});
|
||||
await page.evaluate(()=>Alpine.store('imports').startWizard('spotify'));
|
||||
await page.locator('dialog#import-wizard').waitFor();
|
||||
const surface=await page.locator('dialog#import-wizard .player-dialog-surface').boundingBox();
|
||||
assert.ok(surface.width<=390,'the wizard fits the mobile screen');
|
||||
await page.waitForTimeout(200);await page.screenshot({path:path.join(shots,'library-import-mobile-wizard.png')});
|
||||
await page.locator('dialog#import-wizard .player-dialog-close').click();
|
||||
await page.locator('dialog#import-wizard').waitFor({state:'detached'});
|
||||
await page.close();
|
||||
|
||||
// With reduced motion the wizard opens and closes without animations.
|
||||
const still=await browser.newContext({viewport:{width:1024,height:800},reducedMotion:'reduce'});
|
||||
await still.route('**/*',fixture);
|
||||
const calm=await still.newPage();calm.on('pageerror',error=>errors.push(error.message));
|
||||
await calm.goto(host+'/#imports');
|
||||
await calm.waitForFunction(()=>Alpine.store('library').view==='imports'&&Alpine.store('imports').loaded);
|
||||
await calm.getByRole('button',{name:'New import'}).click();
|
||||
const calmDialog=calm.locator('dialog#import-wizard');await calmDialog.waitFor();
|
||||
assert.equal(await calmDialog.locator('.player-dialog-surface').evaluate(element=>getComputedStyle(element).animationName),'none');
|
||||
await calm.keyboard.press('Escape');
|
||||
await calmDialog.waitFor({state:'detached',timeout:500});
|
||||
await still.close();
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: menu order, history polling, lazy ZIP reader with playlist files only, similar confirmation and consent, details, manual choice, Retry, Delete, Spotify sign-in continuation, federated track removal, mobile');
|
||||
} finally {await browser.close();}
|
||||
})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
@@ -0,0 +1,467 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const {readFileSync} = require('node:fs');
|
||||
const {test} = require('node:test');
|
||||
const vm = require('node:vm');
|
||||
const fflate = require('../src/player/vendor/fflate-0.8.2.min.js');
|
||||
|
||||
// Labels render as their phrase keys, so assertions name the message.
|
||||
const source = readFileSync(`${__dirname}/../templates/player/imports_scripts.html`, 'utf8')
|
||||
.replace(/<\/?script>/g, '').replace(/\{\{ t\.(\w+) \}\}/g, '$1');
|
||||
const MiB = 1024 * 1024;
|
||||
// Values from the script's realm are compared by structure.
|
||||
const same = (actual, expected) => assert.deepEqual(JSON.parse(JSON.stringify(actual ?? null)), expected ?? null);
|
||||
|
||||
function setup(responder = () => ({json: {}}), elements = {}) {
|
||||
const calls = [], timers = [], assigned = [], replaced = [];
|
||||
const stores = {
|
||||
library: {view: 'artists', _activeHash: '', _beginNavigation(hash) { this._activeHash = hash; }, _afterNavigation() {}},
|
||||
mobile: {closeLibrary() {}},
|
||||
user: {menuOpen: true},
|
||||
playlists: {reloads: 0, reload() { this.reloads += 1; }},
|
||||
};
|
||||
const context = {
|
||||
document: {documentElement: {lang: 'en'}, addEventListener(_, fn) { fn(); },
|
||||
querySelector: selector => elements[selector] || null, getElementById: id => elements['#' + id] || null,
|
||||
get activeElement() { return elements.active || null; }},
|
||||
Alpine: {store(name, value) { if (value) stores[name] = value; return stores[name]; }, nextTick: fn => fn()},
|
||||
fetch: async (url, options = {}) => {
|
||||
const call = {url, method: options.method || 'GET', body: options.body === undefined ? undefined : JSON.parse(options.body)};
|
||||
calls.push(call);
|
||||
const {status = 200, json = {}} = responder(call) || {};
|
||||
return {ok: status < 400, status, json: async () => json};
|
||||
},
|
||||
window: {fflate}, setTimeout: (fn, ms) => { timers.push({fn, ms}); return timers.length; },
|
||||
clearTimeout: () => {}, confirm: () => true,
|
||||
location: {assign: url => assigned.push(url)},
|
||||
history: {state: null, replaceState: (_, __, hash) => replaced.push(hash)},
|
||||
formatTime: seconds => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, '0')}`,
|
||||
formatArtistCount: count => `${count} tracks`,
|
||||
finishPlayerDialog: async (_, close) => close(),
|
||||
Uint8Array, TextEncoder, TextDecoder, URLSearchParams,
|
||||
};
|
||||
vm.runInNewContext(source, context);
|
||||
return {store: stores.imports, stores, calls, timers, assigned, replaced};
|
||||
}
|
||||
|
||||
const exportFiles = {
|
||||
'Spotify Account Data/Playlist1.json': {playlists: [{name: 'Road trip', items: [{track: {trackName: 'Song', artistName: 'Artist'}}]}]},
|
||||
'Spotify Account Data/YourLibrary.json': {tracks: [{artist: 'Artist', track: 'Liked', album: 'Album'}]},
|
||||
'Spotify Account Data/StreamingHistory_music_0.json': [{trackName: 'Private listening history'}],
|
||||
'Spotify Account Data/Userdata.json': {email: 'person@example.test'},
|
||||
'Spotify Account Data/Read Me First.pdf': 'not json',
|
||||
};
|
||||
function zipFile(entries, name = 'my_spotify_data.zip') {
|
||||
const data = Object.fromEntries(Object.entries(entries).map(([path, value]) =>
|
||||
[path, Buffer.from(typeof value === 'string' ? value : JSON.stringify(value, null, 2))]));
|
||||
return new File([fflate.zipSync(data)], name, {type: 'application/zip'});
|
||||
}
|
||||
const preview = playlists => ({json: {provider: 'spotify', source: 'file', playlists, all_imported: false, federated_search_available: true}});
|
||||
const playlist = (key, extra = {}) => ({source_key: key, kind: 'playlist', title: key, track_count: 2, available: true,
|
||||
already_imported_in: null, similar_to: null, ...extra});
|
||||
|
||||
test('the browser unzips only playlist files and leaves listening history and account data behind', async () => {
|
||||
const {store, calls} = setup(call => call.url === '/api/imports/preview' ? preview([playlist('a')]) : {json: {id: 7}});
|
||||
store.chooseMethod('spotify', 'file');
|
||||
await store.readFiles([zipFile(exportFiles)]);
|
||||
assert.equal(store.wizard.error, '');
|
||||
assert.equal(calls.length, 1);
|
||||
const sent = calls[0].body;
|
||||
assert.equal(sent.provider, 'spotify');
|
||||
assert.equal(sent.source, 'file');
|
||||
same(sent.files.map(file => file.name).sort(),
|
||||
['Spotify Account Data/Playlist1.json', 'Spotify Account Data/YourLibrary.json']);
|
||||
assert.equal(sent.files[0].data.playlists[0].name, 'Road trip');
|
||||
assert.ok(!JSON.stringify(sent).includes('Private listening history'));
|
||||
assert.ok(!JSON.stringify(sent).includes('person@example.test'));
|
||||
assert.equal(store.wizard.step, 'select');
|
||||
same(store.wizard.fileNames.sort(), ['Playlist1.json', 'YourLibrary.json']);
|
||||
});
|
||||
|
||||
test('archive, entry, file and declared size limits stop a ZIP before anything is sent', async () => {
|
||||
const {store, calls} = setup();
|
||||
store.chooseMethod('spotify', 'file');
|
||||
let read = false;
|
||||
await store.readFiles([{name: 'huge.zip', type: 'application/zip', size: 257 * MiB, arrayBuffer: async () => { read = true; }}]);
|
||||
assert.equal(store.wizard.error, 'player_import_archive_too_large');
|
||||
assert.equal(read, false);
|
||||
|
||||
const entries = Object.fromEntries(Array.from({length: 2001}, (_, i) => [`misc/file${i}.txt`, 'x']));
|
||||
await store.readFiles([zipFile(entries)]);
|
||||
assert.equal(store.wizard.error, 'player_import_zip_too_many_entries');
|
||||
|
||||
const playlists = Object.fromEntries(Array.from({length: 257}, (_, i) => [`Playlist${i + 1}.json`, {playlists: []}]));
|
||||
await store.readFiles([zipFile(playlists)]);
|
||||
assert.equal(store.wizard.error, 'player_import_zip_too_many_files');
|
||||
|
||||
// A bomb declares a huge size; the declared sizes are checked before inflating.
|
||||
const bomb = fflate.zipSync({'Playlist1.json': new Uint8Array(64 * 1024).fill(32)});
|
||||
const view = new DataView(bomb.buffer);
|
||||
for (let i = 0; i < bomb.length - 4; i++) {
|
||||
if (view.getUint32(i, true) === 0x02014b50) view.setUint32(i + 24, 40 * MiB, true);
|
||||
}
|
||||
await store.readFiles([new File([bomb], 'bomb.zip')]);
|
||||
assert.equal(store.wizard.error, 'player_import_export_too_large');
|
||||
|
||||
await store.readFiles([new File([Buffer.from('not a zip')], 'broken.zip')]);
|
||||
assert.equal(store.wizard.error, 'player_import_zip_invalid');
|
||||
await store.readFiles([new File(['{}'], 'StreamingHistory0.json')]);
|
||||
assert.equal(store.wizard.error, 'player_import_no_files');
|
||||
assert.equal(calls.length, 0);
|
||||
same(store.wizard.files, []);
|
||||
});
|
||||
|
||||
// A stored entry whose central directory records may all point at the one
|
||||
// local header, each with its own name and declared sizes.
|
||||
function storedZip(data, records) {
|
||||
const local = Buffer.alloc(30 + 14);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt32LE(data.length, 18);
|
||||
local.writeUInt32LE(data.length, 22);
|
||||
local.writeUInt16LE(14, 26);
|
||||
local.write('Playlist1.json', 30);
|
||||
const central = records.map(({name, size = data.length, originalSize = data.length, compression = 0}) => {
|
||||
const record = Buffer.alloc(46 + name.length);
|
||||
record.writeUInt32LE(0x02014b50, 0);
|
||||
record.writeUInt16LE(20, 4);
|
||||
record.writeUInt16LE(20, 6);
|
||||
record.writeUInt16LE(compression, 10);
|
||||
record.writeUInt32LE(size, 20);
|
||||
record.writeUInt32LE(originalSize, 24);
|
||||
record.writeUInt16LE(name.length, 28);
|
||||
record.write(name, 46);
|
||||
return record;
|
||||
});
|
||||
const directory = Buffer.concat(central);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(records.length, 8);
|
||||
end.writeUInt16LE(records.length, 10);
|
||||
end.writeUInt32LE(directory.length, 12);
|
||||
end.writeUInt32LE(local.length + data.length, 16);
|
||||
return new File([Buffer.concat([local, data, directory, end])], 'stored.zip', {type: 'application/zip'});
|
||||
}
|
||||
|
||||
test('stored and overlapping entries are charged what fflate copies for them', async () => {
|
||||
const {store, calls} = setup(() => preview([playlist('a')]));
|
||||
store.chooseMethod('spotify', 'file');
|
||||
const data = Buffer.from(JSON.stringify({playlists: []}).padEnd(MiB, ' '));
|
||||
// A stored entry is copied by its compressed size, whatever it declares.
|
||||
await store.readFiles([storedZip(data, [{name: 'Playlist1.json', originalSize: 0}])]);
|
||||
assert.equal(store.wizard.error, 'player_import_zip_invalid');
|
||||
// Many records of one stored entry, each declaring nothing, are a bomb.
|
||||
const names = Array.from({length: 10}, (_, i) => ({name: `Playlist${i + 1}.json`, originalSize: 0}));
|
||||
await store.readFiles([storedZip(data, names)]);
|
||||
assert.equal(store.wizard.error, 'player_import_zip_invalid');
|
||||
// Honest records of one entry still add up against the export limit.
|
||||
const honest = Array.from({length: 40}, (_, i) => ({name: `Playlist${i + 1}.json`}));
|
||||
await store.readFiles([storedZip(data, honest)]);
|
||||
assert.equal(store.wizard.error, 'player_import_export_too_large');
|
||||
// Duplicate names and unknown methods are refused.
|
||||
await store.readFiles([storedZip(data, [{name: 'Playlist1.json'}, {name: 'Playlist1.json'}])]);
|
||||
assert.equal(store.wizard.error, 'player_import_zip_invalid');
|
||||
await store.readFiles([storedZip(data, [{name: 'Playlist1.json', compression: 12}])]);
|
||||
assert.equal(store.wizard.error, 'player_import_zip_invalid');
|
||||
assert.equal(calls.length, 0);
|
||||
// A valid stored entry is read.
|
||||
await store.readFiles([storedZip(data, [{name: 'Playlist1.json'}])]);
|
||||
assert.equal(store.wizard.error, '');
|
||||
assert.equal(calls.length, 1);
|
||||
same(calls[0].body.files.map(file => file.name), ['Playlist1.json']);
|
||||
});
|
||||
|
||||
test('unzipped JSON files are accepted and an oversized request is refused in the browser', async () => {
|
||||
const {store, calls} = setup(() => preview([playlist('a')]));
|
||||
store.chooseMethod('spotify', 'file');
|
||||
await store.readFiles([new File(['' + JSON.stringify(exportFiles['Spotify Account Data/Playlist1.json'])], 'Playlist1.json'),
|
||||
new File(['[]'], 'StreamingHistory_music_0.json')]);
|
||||
assert.equal(calls.length, 1);
|
||||
same(calls[0].body.files.map(file => file.name), ['Playlist1.json']);
|
||||
assert.equal(store.wizard.skipped, 1);
|
||||
// Text that does not parse is sent as text; escaping can push it past the limit.
|
||||
await store.readFiles([new File(['"'.repeat(20 * MiB)], 'Playlist1.json')]);
|
||||
assert.equal(store.wizard.error, 'player_import_request_too_large');
|
||||
assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
test('imported, unavailable and similar playlists need the right selection and confirmation', async () => {
|
||||
const {store, calls, stores} = setup(call => call.url === '/api/imports'
|
||||
? {json: {id: 12, status: 'queued'}}
|
||||
: call.url.startsWith('/api/imports/12') ? {json: call.url.includes('items') ? {items: [], next: null} : {id: 12, status: 'queued', statistics: {}}} : {json: {}});
|
||||
store.chooseMethod('spotify', 'file');
|
||||
store.wizard.files = [{name: 'Playlist1.json', data: {}}];
|
||||
store.applyPreview(preview([
|
||||
playlist('fresh'), playlist('done', {already_imported_in: 3}),
|
||||
playlist('similar', {similar_to: {import_id: 4, target_playlist_id: 40}}), playlist('locked', {available: false}),
|
||||
]).json);
|
||||
same(store.selection().map(p => p.source_key), ['fresh']);
|
||||
store.selectAll(true);
|
||||
same(store.selection().map(p => p.source_key), ['fresh']);
|
||||
store.wizard.selected.done = true;
|
||||
store.wizard.selected.locked = true;
|
||||
same(store.selection().map(p => p.source_key), ['fresh']);
|
||||
store.wizard.selected.similar = true;
|
||||
assert.equal(store.canStart(), false);
|
||||
await store.begin();
|
||||
assert.equal(store.wizard.error, 'player_import_confirm_similar_needed');
|
||||
assert.equal(calls.length, 0);
|
||||
store.wizard.confirmed.similar = true;
|
||||
store.wizard.federated = true;
|
||||
await store.begin();
|
||||
same(calls[0].body.selection, ['fresh', 'similar']);
|
||||
same(calls[0].body.confirm_similar, ['similar']);
|
||||
assert.equal(calls[0].body.federated_search, true);
|
||||
assert.equal(calls[0].body.files.length, 1);
|
||||
assert.equal(store.wizard.open, false);
|
||||
same(store.wizard.files, []);
|
||||
assert.equal(stores.library.view, 'import_detail');
|
||||
assert.equal(stores.library._activeHash, '#imports/12');
|
||||
});
|
||||
|
||||
test('federated search is never requested when the server has it turned off', async () => {
|
||||
const {store, calls} = setup(() => ({json: {id: 1}}));
|
||||
store.chooseMethod('spotify', 'file');
|
||||
store.applyPreview({...preview([playlist('a')]).json, federated_search_available: false});
|
||||
store.wizard.federated = true;
|
||||
await store.begin();
|
||||
assert.equal(calls[0].body.federated_search, false);
|
||||
});
|
||||
|
||||
test('a conflict from the server marks playlists imported meanwhile', async () => {
|
||||
const {store} = setup(() => ({status: 409, json: {error: 'some playlists were already imported',
|
||||
conflicts: [{source_key: 'a', import_id: 9}]}}));
|
||||
store.chooseMethod('spotify', 'file');
|
||||
store.applyPreview(preview([playlist('a'), playlist('b')]).json);
|
||||
await store.begin();
|
||||
assert.equal(store.wizard.open, true);
|
||||
assert.equal(store.wizard.error, 'player_import_conflicts');
|
||||
assert.equal(store.wizard.preview.playlists[0].already_imported_in, 9);
|
||||
same(store.selection().map(p => p.source_key), ['b']);
|
||||
});
|
||||
|
||||
test('the history polls every 3 seconds only while an import is running', async () => {
|
||||
let imports = [{id: 1, provider: 'spotify', status: 'running', statistics: {total: 4, published: 0}}];
|
||||
const {store, stores, timers} = setup(call => call.url === '/api/imports/providers'
|
||||
? {json: {providers: [{id: 'spotify', name: 'Spotify', methods: ['file', 'api']}], federated_search_available: true}}
|
||||
: {json: {imports}});
|
||||
await store.route(null, '', {fromHash: true});
|
||||
assert.equal(stores.library.view, 'imports');
|
||||
assert.equal(store.providerName('spotify'), 'Spotify');
|
||||
assert.equal(timers.length, 1);
|
||||
assert.equal(timers[0].ms, 3000);
|
||||
imports = [{...imports[0], status: 'done', statistics: {total: 4, published: 3}}];
|
||||
await timers[0].fn();
|
||||
assert.equal(store.imports[0].status, 'done');
|
||||
assert.equal(stores.playlists.reloads, 1);
|
||||
assert.equal(timers.length, 1);
|
||||
// Leaving the page stops polling.
|
||||
imports = [{...imports[0], status: 'running'}];
|
||||
store.schedule();
|
||||
stores.library.view = 'artists';
|
||||
const before = timers.length;
|
||||
await timers.at(-1).fn();
|
||||
assert.equal(timers.length, before);
|
||||
});
|
||||
|
||||
test('details filter entries, choose candidates and retry with a new federated consent', async () => {
|
||||
let detail = {id: 5, provider: 'spotify', status: 'done', federated_search: false, statistics: {total: 3, ambiguous: 1, unmatched: 1},
|
||||
source_playlists: [{id: 50, title: 'Road trip', target_playlist_id: 500, target_deleted: false}]};
|
||||
const item = {id: 80, playlist_id: 50, position: 0, metadata: {title: 'Song', artists: ['A']}, resolution_status: 'ambiguous',
|
||||
candidates: [{origin: 'local', title: 'Song'}, {origin: 'federation', title: 'Song (Live)'}], publication_status: 'not_ready'};
|
||||
const {store, calls, timers} = setup(call => {
|
||||
if (call.url === '/api/imports/providers') return {json: {providers: [], federated_search_available: true}};
|
||||
if (call.url.includes('/items/80/match')) return {json: {resolution_status: 'matched', publication_status: 'pending'}};
|
||||
if (call.url.includes('/items')) return {json: {items: [item], next: null}};
|
||||
if (call.url.endsWith('/resync')) { detail = {...detail, status: 'queued'}; return {json: {status: 'queued'}}; }
|
||||
return {json: detail};
|
||||
});
|
||||
await store.route(5, '', {fromHash: true});
|
||||
assert.equal(store.detail.id, 5);
|
||||
assert.equal(store.items.length, 1);
|
||||
same(store.statusFilters().map(f => f.status), ['', 'ambiguous', 'unmatched']);
|
||||
store.setStatus('ambiguous');
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.ok(calls.some(call => call.url === '/api/imports/5/items?status=ambiguous'));
|
||||
await store.choose(item, 1);
|
||||
const chosen = calls.find(call => call.url === '/api/imports/5/items/80/match');
|
||||
same(chosen.body, {candidate: 1});
|
||||
assert.equal(item.match_origin, 'federation');
|
||||
store.openRetry();
|
||||
assert.equal(store.retryFederated, false);
|
||||
store.retryFederated = true;
|
||||
await store.retry(store.detail, store.retryFederated);
|
||||
same(calls.find(call => call.url === '/api/imports/5/resync').body, {federated_search: true});
|
||||
assert.equal(store.detail.status, 'queued');
|
||||
assert.equal(store.message, 'player_import_retry_started');
|
||||
assert.ok(timers.length >= 1);
|
||||
});
|
||||
|
||||
test('history retry keeps the consent, and cancel and delete call the import endpoints', async () => {
|
||||
const {store, calls} = setup(call => call.url === '/api/imports' ? {json: {imports: []}}
|
||||
: call.url === '/api/imports/providers' ? {json: {providers: []}}
|
||||
: call.url.endsWith('/cancel') ? {json: {status: 'cancelling'}} : {json: {id: 6, status: 'running', statistics: {}}});
|
||||
await store.retry({id: 6});
|
||||
same(calls[0], {url: '/api/imports/6/resync', method: 'POST', body: {}});
|
||||
store.detailId = 6;
|
||||
store.detail = {id: 6, status: 'running', statistics: {}};
|
||||
await store.cancel();
|
||||
assert.ok(calls.some(call => call.url === '/api/imports/6/cancel' && call.method === 'POST'));
|
||||
assert.equal(store.message, 'player_import_cancel_requested');
|
||||
await store.remove({id: 6, status: 'done'});
|
||||
assert.ok(calls.some(call => call.url === '/api/imports/6' && call.method === 'DELETE'));
|
||||
assert.equal(store.message, 'player_import_deleted');
|
||||
});
|
||||
|
||||
test('the Spotify sign-in returns to the wizard or continues the waiting import', async () => {
|
||||
const {store, calls, assigned, replaced} = setup(call => {
|
||||
if (call.url === '/api/imports/providers/spotify/playlists') {
|
||||
return {json: {provider: 'spotify', source: 'api', federated_search_available: true,
|
||||
playlists: [playlist('spotify:playlist:1'), playlist('spotify:playlist:2', {available: false})]}};
|
||||
}
|
||||
if (call.url === '/api/imports') return {json: call.method === 'POST' ? {id: 3} : {imports: []}};
|
||||
if (call.url === '/api/imports/providers') return {json: {providers: [{id: 'spotify', name: 'Spotify', methods: ['file', 'api']}]}};
|
||||
if (call.url.includes('/items')) return {json: {items: [], next: null}};
|
||||
return {json: {id: 3, provider: 'spotify', status: 'needs_reauth', statistics: {}}};
|
||||
});
|
||||
await store.route(null, 'connect=spotify', {fromHash: true});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
same(replaced, ['#imports']);
|
||||
assert.equal(store.wizard.method, 'api');
|
||||
assert.equal(store.wizard.step, 'select');
|
||||
same(store.selection().map(p => p.source_key), ['spotify:playlist:1']);
|
||||
await store.begin();
|
||||
const created = calls.find(call => call.url === '/api/imports' && call.method === 'POST');
|
||||
assert.equal(created.body.source, 'api');
|
||||
assert.equal(created.body.files, undefined);
|
||||
|
||||
await store.route(null, 'connect=spotify&error=not_allowed', {fromHash: true});
|
||||
assert.equal(store.wizard.error, 'player_import_oauth_not_allowed');
|
||||
|
||||
await store.route(3, 'error=account_mismatch', {fromHash: true});
|
||||
assert.equal(store.notice, 'player_import_oauth_account_mismatch');
|
||||
assert.equal(replaced.at(-1), '#imports/3');
|
||||
assert.equal(store.hasActive(), false);
|
||||
store.reauthorize();
|
||||
same(assigned, ['/api/imports/providers/spotify/authorize?import_id=3']);
|
||||
});
|
||||
|
||||
test('a sign-in from earlier in the session is used without asking again', async () => {
|
||||
const {store} = setup(call => call.url.endsWith('/playlists')
|
||||
? {status: 409, json: {error: 'sign in to Spotify first'}} : {json: {}});
|
||||
await store.chooseMethod('spotify', 'api');
|
||||
assert.equal(store.wizard.step, 'connect');
|
||||
assert.equal(store.wizard.error, '');
|
||||
});
|
||||
|
||||
test('focus returns to the opener when the wizard closes and moves to the title on a new step', async () => {
|
||||
const focused = [];
|
||||
const element = name => ({isConnected: true, focus() { focused.push(name); }});
|
||||
const elements = {active: element('opener'), '#import-wizard-title': element('title'),
|
||||
'.library-imports .release-action-btn.primary': element('new import')};
|
||||
const {store} = setup(() => preview([playlist('a')]), elements);
|
||||
store.startWizard();
|
||||
store.chooseMethod('spotify', 'file');
|
||||
store.back();
|
||||
store.applyPreview(preview([playlist('a')]).json);
|
||||
same(focused, ['title', 'title', 'title']);
|
||||
await store.closeWizard({});
|
||||
assert.equal(store.wizard.open, false);
|
||||
same(focused.at(-1), 'opener');
|
||||
// An opener that left the page gives way to the New import button.
|
||||
elements.active = {...element('gone'), isConnected: false};
|
||||
store.startWizard();
|
||||
await store.closeWizard({});
|
||||
same(focused.at(-1), 'new import');
|
||||
// Closing to navigate leaves focus to the navigation.
|
||||
store.startWizard();
|
||||
await store.closeWizard({}, false);
|
||||
same(focused.at(-1), 'new import');
|
||||
assert.equal(focused.length, 5);
|
||||
});
|
||||
|
||||
test('a pending search does not load entries after leaving the details', async () => {
|
||||
const {store, calls, timers} = setup(call => call.url === '/api/imports'
|
||||
? {json: {imports: []}} : call.url === '/api/imports/providers' ? {json: {providers: []}}
|
||||
: call.url.includes('/items') ? {json: {items: [], next: null}} : {json: {id: 5, status: 'done', statistics: {}}});
|
||||
await store.route(5, '', {fromHash: true});
|
||||
store.filter.q = 'song';
|
||||
store.searchChanged();
|
||||
const search = timers.at(-1);
|
||||
assert.equal(search.ms, 300);
|
||||
await store.route(null, '', {fromHash: true});
|
||||
assert.equal(store.detailId, null);
|
||||
const before = calls.length;
|
||||
await search.fn();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(calls.length, before);
|
||||
assert.ok(!calls.some(call => call.url.includes('/null/')));
|
||||
assert.equal(store.message, '');
|
||||
});
|
||||
|
||||
test('progress follows the phase of a running import', () => {
|
||||
const {store} = setup();
|
||||
same(store.progress({status: 'running', phase: 'resolve_local', statistics: {total: 10, pending: 4}}), {value: 6, max: 10});
|
||||
same(store.progress({status: 'running', phase: 'publish', statistics: {total: 10, published: 3, duplicate: 1, publication_pending: 4}}), {value: 4, max: 8});
|
||||
same(store.progress({status: 'running', phase: 'fetching', statistics: {total: 0}}), {value: null, max: null});
|
||||
assert.equal(store.statusText({status: 'running', cancel_requested: true}), 'player_import_status_cancelling');
|
||||
assert.equal(store.noteText({resolution_note: 'write_failed'}), 'player_import_note_failed');
|
||||
assert.equal(store.noteText({resolution_note: 'unknown_code'}), '');
|
||||
assert.equal(store.text('foundOf', {found: 3, total: 9}), 'player_import_found_of');
|
||||
});
|
||||
|
||||
const scripts = readFileSync(`${__dirname}/../templates/player/scripts.html`, 'utf8');
|
||||
function playlistsStore(responder) {
|
||||
const start = scripts.indexOf(" Alpine.store('playlists', {");
|
||||
const end = scripts.indexOf('\n });\n', start) + '\n });\n'.length;
|
||||
const calls = [];
|
||||
const stores = {library: {currentPlaylist: null}, playlistHeader: {busy: false, reset() {}}, pins: {reload: async () => {}}};
|
||||
vm.runInNewContext(scripts.slice(start, end), {
|
||||
Alpine: {store: (name, value) => value ? (stores[name] = value) : stores[name]},
|
||||
GUEST: false, T: new Proxy({}, {get: (_, key) => key}), console: {warn() {}},
|
||||
fetch: async (url, options = {}) => {
|
||||
calls.push({url, method: options.method || 'GET', body: options.body && JSON.parse(options.body)});
|
||||
return responder(url);
|
||||
},
|
||||
});
|
||||
return {store: stores.playlists, stores, calls};
|
||||
}
|
||||
|
||||
test('a federated track is removed from a playlist by its content id', async () => {
|
||||
const {store, stores, calls} = playlistsStore(url => ({ok: true, json: async () => url === '/api/player/playlists' ? [] : {ok: true}}));
|
||||
const federated = {id: 'fed:b3:1', content_id: 'b3:1', federation_pending: true};
|
||||
const local = {id: 4, playlist_track_id: 40, content_id: 'b3:4'};
|
||||
stores.library.currentPlaylist = {id: 12, kind: 'user', is_own: true, tracks: [local, federated]};
|
||||
store.editingPlaylistId = 12;
|
||||
await store.removeCurrentTrack(federated, 1);
|
||||
same(calls[0], {url: '/api/player/tracks/content/playlist', method: 'DELETE', body: {playlist_id: 12, content_id: 'b3:1'}});
|
||||
same(stores.library.currentPlaylist.tracks, [local]);
|
||||
await store.removeCurrentTrack(local, 0);
|
||||
assert.equal(calls.filter(call => call.method === 'DELETE')[1].url, '/api/player/playlists/12/tracks');
|
||||
});
|
||||
|
||||
test('a failed federated removal restores the track', async () => {
|
||||
const {store, stores} = playlistsStore(() => ({ok: false, json: async () => ({})}));
|
||||
const federated = {id: 'fed:b3:1', content_id: 'b3:1', federation_pending: true};
|
||||
stores.library.currentPlaylist = {id: 12, kind: 'user', is_own: true, tracks: [federated]};
|
||||
store.editingPlaylistId = 12;
|
||||
await store.removeCurrentTrack(federated, 0);
|
||||
same(stores.library.currentPlaylist.tracks, [federated]);
|
||||
});
|
||||
|
||||
test('import templates parse without a browser', () => {
|
||||
for (const file of ['templates/player/imports_scripts.html']) {
|
||||
const html = readFileSync(`${__dirname}/../${file}`, 'utf8');
|
||||
for (const match of html.matchAll(/<script>([\s\S]*?)<\/script>/g)) new vm.Script(match[1]);
|
||||
}
|
||||
});
|
||||
|
||||
test('the statistics skeleton has as many cells as the statistics', () => {
|
||||
const page = readFileSync(`${__dirname}/../templates/player/imports.html`, 'utf8');
|
||||
const skeleton = page.match(/import-stats-skeleton">\s*\{% for _ in 0\.\.(\d+) %\}/);
|
||||
const stats = page.match(/<dl class="import-stats">([\s\S]*?)<\/dl>/)[1];
|
||||
const cells = stats.split('\n').filter(line => /^\s{20}<div>/.test(line)).length;
|
||||
assert.equal(cells, 6);
|
||||
assert.equal(Number(skeleton[1]), cells);
|
||||
const styles = readFileSync(`${__dirname}/../templates/player/imports_styles.html`, 'utf8');
|
||||
assert.doesNotMatch(styles, /\.import-stats-skeleton \{[^}]*grid-template-columns/);
|
||||
});
|
||||
Reference in new issue
Block a user