Import Spotify data exports and optionally playlists from the Spotify Web API

Add the Spotify adapter to the library import. The data export path parses
Playlist*.json and YourLibrary.json sent by the browser, tolerates missing
and unexpected keys, keeps the source order and repeats, and stores episodes,
audiobooks, local files and unreadable entries as unsupported instead of
dropping them. The bundled export fixture is synthetic and must be joined by
an anonymized real export before acceptance.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-26 16:30:07 +02:00
1 parent 097812a845
commit ff87d9110d
20 files changed
+4176 -52

No files matched your search

+23
View File
@@ -99,6 +99,29 @@ 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
Spotify playlists and Liked Songs are imported from the account data export
("Download your data") without any server configuration. The browser sends
only `Playlist*.json` and `YourLibrary.json`; the server parses them 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.
## Federation
Federation is optional. Independent Furumusic and Furumi players that use the
+9 -3
View File
@@ -155,6 +155,12 @@ cargo test library_import
FURU_LIBRARY_IMPORT_TEST_DATABASE_URL=postgresql://... cargo test library_import -- --include-ignored
```
The database tests cover per-user isolation, repeated source playlists, exclusive
claims, lease ownership, cancellation, history deletion that keeps target playlists,
and resumption after a worker stops without a server restart once its lease expires.
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, and continuing the same Spotify
API import after the user signs in again.
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.
+33
View File
@@ -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(),
},
}
}
+17
View File
@@ -151,6 +151,8 @@ 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,
}
impl Default for ConfigSources {
@@ -194,6 +196,8 @@ 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,
}
}
}
@@ -414,6 +418,13 @@ 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,
}
impl Default for AppConfig {
@@ -460,6 +471,8 @@ 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(),
}
}
}
@@ -504,6 +517,8 @@ impl_env_overrides!(
torrent_proxy_id,
youtube_proxy_id,
youtube_cookie_id,
spotify_client_id,
spotify_redirect_uri,
);
impl AppConfig {
@@ -649,6 +664,8 @@ 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);
}
pub fn parsed_download_proxies(&self) -> anyhow::Result<Vec<DownloadProxy>> {
@@ -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": []
}
+155 -2
View File
@@ -3,9 +3,14 @@
//! 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 super::model::{ImportedLibrary, ProviderInfo, SourceType};
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)]
@@ -45,7 +50,7 @@ pub trait FileAdapter: Send + Sync {
/// 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> {
@@ -55,6 +60,80 @@ pub fn file_adapter(provider: &str) -> Option<&'static dyn FileAdapter> {
.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()
@@ -66,3 +145,77 @@ pub fn file_providers() -> Vec<ProviderInfo> {
})
.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,614 @@
//! 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.
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use super::{AdapterError, FileAdapter, InputFile, 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()
};
for (_, file) in playlist_files {
let content: PlaylistFile = parse_json(file)?;
library.playlists.extend(
content
.playlists
.into_iter()
.map(|value| playlist(lenient_value(value))),
);
}
let mut favorites = Vec::new();
for file in library_files {
let content: LibraryFile = parse_json(file)?;
favorites.extend(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, value)| saved_track(position, lenient_value(value)))
.collect(),
});
}
Ok(library)
}
}
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<T: DeserializeOwned + Default>(file: &InputFile) -> Result<T, AdapterError> {
let invalid = |reason: String| AdapterError::Invalid {
file: base_name(&file.name).to_owned(),
reason,
};
let value: Value = serde_json::from_slice(&file.data).map_err(|error| {
invalid(format!(
"not valid JSON (line {}, column {})",
error.line(),
error.column()
))
})?;
if !value.is_object() {
return Err(invalid("not a Spotify export file".to_owned()));
}
Ok(lenient_value(value))
}
/// Deserializes `value` as `T`, falling back to `T::default()` when the shape differs.
fn lenient_value<T: DeserializeOwned + Default>(value: Value) -> T {
serde_json::from_value(value).unwrap_or_default()
}
fn lenient<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: DeserializeOwned + Default,
{
Ok(lenient_value(Value::deserialize(deserializer)?))
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct PlaylistFile {
#[serde(deserialize_with = "lenient")]
playlists: Vec<Value>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct LibraryFile {
#[serde(deserialize_with = "lenient")]
tracks: Vec<Value>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct RawPlaylist {
#[serde(deserialize_with = "lenient")]
name: Option<String>,
#[serde(deserialize_with = "lenient")]
description: Option<String>,
#[serde(deserialize_with = "lenient")]
items: Vec<Value>,
}
#[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(raw: RawPlaylist) -> ImportedPlaylist {
ImportedPlaylist {
kind: PlaylistKind::Playlist,
source_id: None,
title: text(raw.name).unwrap_or_default(),
description: text(raw.description),
tracks: raw
.items
.into_iter()
.enumerate()
.map(|(position, value)| playlist_item(position, lenient_value(value)))
.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 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
+103 -5
View File
@@ -14,7 +14,8 @@ use anyhow::Result;
use sqlx::PgPool;
use super::model::Phase;
use super::store::{self, ClaimedImport, Control, FinishOutcome};
use super::providers::{FetchError, LibraryFetcher, ProviderFetchers, TokenVault};
use super::store::{self, ClaimedImport, Control, FinishOutcome, NewItem};
use crate::config::AppConfig;
use crate::scheduler::{Job, JobContext, JobLog, SchedulerHandle};
@@ -74,6 +75,17 @@ pub async fn run_worker(
config: Arc<AppConfig>,
run_id: i64,
log: &mut JobLog,
) -> Result<()> {
run_worker_with(pool, config, run_id, log, Arc::new(ProviderFetchers)).await
}
/// [`run_worker`] with the provider API client 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>,
) -> Result<()> {
let Some(_slot) = WorkerSlot::acquire() else {
log.info("Library import workers are busy; queued imports will be taken by them");
@@ -83,6 +95,7 @@ pub async fn run_worker(
pool: pool.clone(),
config,
run_id,
fetcher,
};
let mut processed = 0usize;
while let Some(import) = store::claim_next(pool, run_id, LEASE).await? {
@@ -104,6 +117,7 @@ struct Worker {
pool: PgPool,
config: Arc<AppConfig>,
run_id: i64,
fetcher: Arc<dyn LibraryFetcher>,
}
/// Renews the lease in the background while the worker owns an import.
@@ -151,6 +165,8 @@ impl Drop for Heartbeat {
enum Stop {
Cancelled,
LeaseLost,
/// The provider token is missing or expired; the user signs in again.
NeedsReauth,
}
impl Worker {
@@ -168,11 +184,21 @@ impl Worker {
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",
@@ -243,7 +269,11 @@ impl Worker {
return Ok(Some(Stop::LeaseLost));
}
match phase {
Phase::Fetching => self.fetch(import, log).await?,
Phase::Fetching => {
if let Some(stop) = self.fetch(import, heartbeat, log).await? {
return Ok(Some(stop));
}
}
Phase::ResolveLocal => self.resolve_local(import, log).await?,
Phase::ResolveFederation => self.resolve_federation(import, log).await?,
Phase::Publish => self.publish(import, log).await?,
@@ -253,9 +283,77 @@ impl Worker {
Ok(None)
}
/// API imports fetch the selected playlists here (provider integrations).
async fn fetch(&self, _import: &ClaimedImport, _log: &mut JobLog) -> Result<()> {
Ok(())
/// 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)
}
/// Matches pending entries against the local library (resolver stage 1–2).
+3 -4
View File
@@ -6,15 +6,14 @@
//! rest of Furumi only when publishing: target playlists, their tracks and the
//! existing Device Sync operations.
// Imports are created by the provider integrations and processed by the
// resolver and publisher; until those are wired in, parts of the model and
// the creation path are used by the tests only.
#[allow(dead_code)]
// 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;
#[allow(dead_code)]
pub mod model;
pub mod providers;
#[allow(dead_code)]
pub mod store;
+170
View File
@@ -43,6 +43,13 @@ pub struct ImportedTrack {
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>) {
@@ -52,6 +59,7 @@ impl ImportedTrack {
}
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")),
}
@@ -141,6 +149,7 @@ text_enum!(
#[default]
Track => "track",
Episode => "episode",
Audiobook => "audiobook",
LocalFile => "local_file",
Unknown => "unknown",
});
@@ -249,6 +258,112 @@ text_enum!(AttemptStatus {
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)]
@@ -497,6 +612,61 @@ mod tests {
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();
+281
View File
@@ -0,0 +1,281 @@
//! Network integrations of providers: OAuth, API clients and the in-memory
//! token vault. File exports do not need anything here.
pub mod spotify_api;
use std::collections::HashMap;
use std::fmt;
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};
use super::model::{ImportedTrack, PlaylistKind};
/// Longest time an access token is kept. Tokens live only in this process:
/// not in the database, not in the session and never on devices.
pub const TOKEN_TTL: Duration = Duration::from_secs(30 * 60);
/// A provider access token. `Debug` never shows the value.
#[derive(Clone, PartialEq, Eq)]
pub struct AccessToken(String);
impl AccessToken {
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
pub fn secret(&self) -> &str {
&self.0
}
}
impl fmt::Debug for AccessToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AccessToken(<redacted>)")
}
}
/// A signed-in provider account, before or after an import was created.
#[derive(Debug, Clone)]
pub struct Connection {
pub provider: String,
pub account_ref: String,
pub token: AccessToken,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum VaultKey {
/// A random handle kept in the user's session until an import is created.
Handle(String),
/// The token an import fetches its playlists with.
Import(i64),
}
#[derive(Debug)]
struct VaultEntry {
user_id: i64,
connection: Connection,
expires_at: Instant,
}
/// Process-wide store of provider access tokens with a short lifetime.
#[derive(Debug, Default)]
pub struct TokenVault {
entries: Mutex<HashMap<VaultKey, VaultEntry>>,
}
impl TokenVault {
pub fn shared() -> &'static Self {
static VAULT: LazyLock<TokenVault> = LazyLock::new(TokenVault::default);
&VAULT
}
fn with_entries<T>(&self, action: impl FnOnce(&mut HashMap<VaultKey, VaultEntry>) -> T) -> T {
let mut entries = self
.entries
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let now = Instant::now();
entries.retain(|_, entry| entry.expires_at > now);
action(&mut entries)
}
fn entry(user_id: i64, connection: Connection, lifetime: Duration) -> VaultEntry {
VaultEntry {
user_id,
connection,
expires_at: Instant::now() + lifetime.min(TOKEN_TTL),
}
}
/// Keeps a fresh sign-in under a new random handle for the user's session.
pub fn connect(&self, user_id: i64, connection: Connection, lifetime: Duration) -> String {
let handle = random_secret();
self.with_entries(|entries| {
entries.insert(
VaultKey::Handle(handle.clone()),
Self::entry(user_id, connection, lifetime),
)
});
handle
}
/// The sign-in behind a session handle, only for the user who made it.
pub fn connection(&self, user_id: i64, handle: &str) -> Option<Connection> {
self.with_entries(|entries| {
entries
.get(&VaultKey::Handle(handle.to_owned()))
.filter(|entry| entry.user_id == user_id)
.map(|entry| entry.connection.clone())
})
}
/// Moves a session sign-in to the import created with it.
pub fn attach(&self, user_id: i64, handle: &str, import_id: i64) -> bool {
self.with_entries(|entries| {
let key = VaultKey::Handle(handle.to_owned());
if entries
.get(&key)
.is_none_or(|entry| entry.user_id != user_id)
{
return false;
}
let entry = entries.remove(&key).expect("checked above");
entries.insert(VaultKey::Import(import_id), entry);
true
})
}
/// Stores the token of a repeated sign-in for an import that waits for it.
pub fn store_for_import(
&self,
user_id: i64,
import_id: i64,
connection: Connection,
lifetime: Duration,
) {
self.with_entries(|entries| {
entries.insert(
VaultKey::Import(import_id),
Self::entry(user_id, connection, lifetime),
)
});
}
pub fn import_token(&self, import_id: i64) -> Option<AccessToken> {
self.with_entries(|entries| {
entries
.get(&VaultKey::Import(import_id))
.map(|entry| entry.connection.token.clone())
})
}
pub fn forget_import(&self, import_id: i64) {
self.with_entries(|entries| entries.remove(&VaultKey::Import(import_id)));
}
pub fn forget_handle(&self, handle: &str) {
self.with_entries(|entries| entries.remove(&VaultKey::Handle(handle.to_owned())));
}
}
/// A random URL-safe secret for OAuth state and session handles.
pub fn random_secret() -> String {
openidconnect::CsrfToken::new_random().secret().clone()
}
/// A stored source playlist whose entries an API import still has to fetch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchTarget {
pub kind: PlaylistKind,
pub source_playlist_id: Option<String>,
}
/// Why a provider request did not return data. Never carries response bodies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchError {
/// The token expired or was revoked: the user signs in again.
Unauthorized,
/// The provider refuses this playlist (Spotify Development Mode).
Forbidden,
NotFound,
/// Rate limits did not clear in time.
RateLimited,
Failed(String),
}
impl fmt::Display for FetchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unauthorized => f.write_str("provider authorization expired"),
Self::Forbidden => f.write_str("provider refused access"),
Self::NotFound => f.write_str("provider resource not found"),
Self::RateLimited => f.write_str("provider rate limit"),
Self::Failed(reason) => write!(f, "provider request failed: {reason}"),
}
}
}
impl std::error::Error for FetchError {}
/// Reads the entries of one stored playlist from its provider.
#[async_trait::async_trait]
pub trait LibraryFetcher: Send + Sync {
async fn fetch_playlist(
&self,
provider: &str,
token: &AccessToken,
target: &FetchTarget,
) -> Result<Vec<ImportedTrack>, FetchError>;
}
/// The fetcher used by the background job.
pub struct ProviderFetchers;
#[async_trait::async_trait]
impl LibraryFetcher for ProviderFetchers {
async fn fetch_playlist(
&self,
provider: &str,
token: &AccessToken,
target: &FetchTarget,
) -> Result<Vec<ImportedTrack>, FetchError> {
match provider {
spotify_api::PROVIDER => {
spotify_api::SpotifyClient::new()?
.tracks(token, target)
.await
}
_ => Err(FetchError::Failed(
"provider has no API integration".to_owned(),
)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn connection(token: &str) -> Connection {
Connection {
provider: "spotify".into(),
account_ref: "account".into(),
token: AccessToken::new(token),
}
}
#[test]
fn tokens_are_redacted_in_debug_output() {
let text = format!("{:?}", connection("BQD-secret"));
assert!(!text.contains("BQD-secret"), "{text}");
}
#[test]
fn handles_belong_to_their_user_and_move_to_the_import() {
let vault = TokenVault::default();
let handle = vault.connect(1, connection("t1"), TOKEN_TTL);
assert!(vault.connection(2, &handle).is_none());
assert!(!vault.attach(2, &handle, 10));
assert_eq!(
vault.connection(1, &handle).unwrap().token,
AccessToken::new("t1")
);
assert!(vault.attach(1, &handle, 10));
assert!(vault.connection(1, &handle).is_none());
assert_eq!(vault.import_token(10), Some(AccessToken::new("t1")));
vault.forget_import(10);
assert_eq!(vault.import_token(10), None);
}
#[test]
fn expired_tokens_are_dropped() {
let vault = TokenVault::default();
vault.store_for_import(1, 5, connection("t"), Duration::ZERO);
assert_eq!(vault.import_token(5), None);
let handle = vault.connect(1, connection("t"), Duration::from_secs(24 * 3600));
// Lifetimes are capped by the vault TTL.
let expires_at =
vault.with_entries(|entries| entries[&VaultKey::Handle(handle.clone())].expires_at);
assert!(expires_at <= Instant::now() + TOKEN_TTL);
}
}
+704
View File
@@ -0,0 +1,704 @@
//! Optional Spotify Web API integration (plan §4.3).
//!
//! The administrator sets `spotify_client_id` (and, behind a proxy,
//! `spotify_redirect_uri`). Sign-in is Authorization Code with PKCE, so no
//! client secret exists. The OAuth state, the PKCE verifier and the import a
//! repeated sign-in belongs to are one record in the session; the access
//! token lives only in [`TokenVault`](super::TokenVault).
//!
//! Development Mode applications read items only of the user's own and
//! collaborative playlists; other playlists are offered through the data
//! export. Requests run one at a time, honor `Retry-After` and back off on
//! server errors. Tokens, codes, states and verifiers are never logged.
use std::sync::LazyLock;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{AccessToken, FetchError, FetchTarget, random_secret};
use crate::config::AppConfig;
use crate::library_import::adapters::spotify_export::FAVORITES_TITLE;
use crate::library_import::adapters::version_hint;
use crate::library_import::model::{ImportedTrack, PlaylistKind, PreviewPlaylist, TrackKind};
pub const PROVIDER: &str = "spotify";
pub const CALLBACK_PATH: &str = "/api/imports/providers/spotify/callback";
pub const SCOPES: &str = "playlist-read-private playlist-read-collaborative user-library-read";
/// Session record of a sign-in in progress.
pub const SESSION_AUTH: &str = "library_import_spotify_auth";
/// Session handle of the signed-in account in the vault.
pub const SESSION_HANDLE: &str = "library_import_spotify_handle";
const AUTHORIZE_URL: &str = "https://accounts.spotify.com/authorize";
const TOKEN_URL: &str = "https://accounts.spotify.com/api/token";
const API_BASE: &str = "https://api.spotify.com/v1";
/// How long the user may stay on the Spotify consent page.
const STATE_TTL_SECONDS: i64 = 10 * 60;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
const MAX_RATE_LIMIT_RETRIES: u32 = 6;
const MAX_SERVER_ERROR_RETRIES: u32 = 5;
/// Longer waits (daily quotas) fail the request instead of holding the worker.
const MAX_RETRY_AFTER: Duration = Duration::from_secs(300);
const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(5);
const PAGE_LIMIT: usize = 50;
/// Upper bound of followed `next` links: 100 000 entries per list.
const MAX_PAGES: usize = 2000;
/// Whether the administrator enabled the API path.
pub fn is_configured(config: &AppConfig) -> bool {
!config.spotify_client_id.trim().is_empty()
}
/// The configured redirect URI, or the callback on the request origin.
pub fn redirect_uri(config: &AppConfig, origin: &str) -> String {
let configured = config.spotify_redirect_uri.trim();
if configured.is_empty() {
format!("{}{CALLBACK_PATH}", origin.trim_end_matches('/'))
} else {
configured.to_owned()
}
}
/// Spotify accepts HTTPS redirect URIs and plain HTTP only for loopback IPs.
pub fn validate_redirect_uri(uri: &str) -> Result<(), &'static str> {
if uri.is_empty() {
return Ok(());
}
let parsed =
reqwest::Url::parse(uri).map_err(|_| "Spotify redirect URI must be an absolute URL")?;
let loopback = matches!(parsed.host_str(), Some("127.0.0.1" | "[::1]"));
match parsed.scheme() {
"https" if parsed.host_str().is_some_and(|host| host != "localhost") => {}
"http" if loopback => {}
_ => {
return Err(
"Spotify redirect URI must use HTTPS (HTTP only for 127.0.0.1 or [::1]), not localhost",
);
}
}
if parsed.fragment().is_some() {
return Err("Spotify redirect URI must not contain a fragment");
}
Ok(())
}
/// A sign-in in progress, stored in the session. The import id binds a
/// repeated sign-in to the import that waits for it; the callback takes it
/// from here, never from the URL.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthState {
state: String,
verifier: String,
redirect_uri: String,
created_at: i64,
import_id: Option<i64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthStateError {
Mismatch,
Expired,
}
impl AuthState {
/// Starts a sign-in and returns the record with the authorization URL.
pub fn begin(
client_id: &str,
redirect_uri: String,
import_id: Option<i64>,
now: i64,
) -> (Self, String) {
let (challenge, verifier) = openidconnect::PkceCodeChallenge::new_random_sha256();
let state = random_secret();
let mut url = reqwest::Url::parse(AUTHORIZE_URL).expect("valid authorize URL");
url.query_pairs_mut()
.append_pair("client_id", client_id)
.append_pair("response_type", "code")
.append_pair("redirect_uri", &redirect_uri)
.append_pair("code_challenge_method", "S256")
.append_pair("code_challenge", challenge.as_str())
.append_pair("state", &state)
.append_pair("scope", SCOPES);
(
Self {
state,
verifier: verifier.secret().clone(),
redirect_uri,
created_at: now,
import_id,
},
url.into(),
)
}
/// Checks the returned state; the record is single-use and removed by the caller.
pub fn verify(&self, state: &str, now: i64) -> Result<(), AuthStateError> {
if state.is_empty() || state != self.state {
return Err(AuthStateError::Mismatch);
}
if now - self.created_at > STATE_TTL_SECONDS || now < self.created_at {
return Err(AuthStateError::Expired);
}
Ok(())
}
pub fn import_id(&self) -> Option<i64> {
self.import_id
}
pub fn redirect_uri(&self) -> &str {
&self.redirect_uri
}
pub fn verifier(&self) -> &str {
&self.verifier
}
}
/// What to do after a failed response.
fn retry_delay(status: u16, retry_after: Option<&str>, attempt: u32) -> Option<Duration> {
match status {
429 if attempt < MAX_RATE_LIMIT_RETRIES => {
let delay = retry_after
.and_then(|value| value.trim().parse::<u64>().ok())
.map_or(DEFAULT_RETRY_AFTER, Duration::from_secs);
(delay <= MAX_RETRY_AFTER).then_some(delay.max(Duration::from_secs(1)))
}
500..=599 if attempt < MAX_SERVER_ERROR_RETRIES => {
Some(Duration::from_secs(1u64 << attempt))
}
_ => None,
}
}
fn status_error(status: u16) -> FetchError {
match status {
401 => FetchError::Unauthorized,
403 => FetchError::Forbidden,
404 => FetchError::NotFound,
429 => FetchError::RateLimited,
_ => FetchError::Failed(format!("HTTP {status}")),
}
}
/// A granted access token and its lifetime.
pub struct GrantedToken {
pub token: AccessToken,
pub expires_in: Duration,
}
pub struct SpotifyClient {
http: reqwest::Client,
}
impl SpotifyClient {
pub fn new() -> Result<Self, FetchError> {
static HTTP: LazyLock<Option<reqwest::Client>> = LazyLock::new(|| {
reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.redirect(reqwest::redirect::Policy::none())
.user_agent(concat!("furumi/", env!("CARGO_PKG_VERSION")))
.build()
.ok()
});
HTTP.clone()
.map(|http| Self { http })
.ok_or_else(|| FetchError::Failed("HTTP client unavailable".to_owned()))
}
/// Exchanges the authorization code with the PKCE verifier.
pub async fn exchange_code(
&self,
client_id: &str,
code: &str,
auth: &AuthState,
) -> Result<GrantedToken, FetchError> {
#[derive(Deserialize)]
struct TokenResponse {
access_token: String,
#[serde(default)]
expires_in: Option<u64>,
}
let response = self
.http
.post(TOKEN_URL)
.form(&[
("grant_type", "authorization_code"),
("code", code),
("redirect_uri", auth.redirect_uri()),
("client_id", client_id),
("code_verifier", auth.verifier()),
])
.send()
.await
.map_err(|error| FetchError::Failed(request_failure(&error)))?;
let status = response.status().as_u16();
if !response.status().is_success() {
tracing::warn!(status, "Spotify token exchange failed");
// An invalid or reused code is answered with 400.
return Err(if status == 400 {
FetchError::Unauthorized
} else {
status_error(status)
});
}
let body: TokenResponse = response
.json()
.await
.map_err(|_| FetchError::Failed("invalid token response".to_owned()))?;
Ok(GrantedToken {
token: AccessToken::new(body.access_token),
expires_in: Duration::from_secs(body.expires_in.unwrap_or(3600)),
})
}
/// The Spotify user id of the token's account.
pub async fn account_id(&self, token: &AccessToken) -> Result<String, FetchError> {
let me = self.get(token, &format!("{API_BASE}/me")).await?;
me.get("id")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.map(str::to_owned)
.ok_or_else(|| FetchError::Failed("profile without an id".to_owned()))
}
/// The account's playlists for the wizard, favorites first.
pub async fn playlists(
&self,
token: &AccessToken,
account_id: &str,
) -> Result<Vec<PreviewPlaylist>, FetchError> {
let saved = self
.get(token, &format!("{API_BASE}/me/tracks?limit=1"))
.await?;
let mut playlists = vec![favorites_preview(account_id, total(&saved))];
let url = format!("{API_BASE}/me/playlists?limit={PAGE_LIMIT}");
for item in self.pages(token, url).await? {
if let Some(playlist) = playlist_preview(&item, account_id) {
playlists.push(playlist);
}
}
Ok(playlists)
}
/// All entries of a playlist or of the saved tracks, in source order.
pub async fn tracks(
&self,
token: &AccessToken,
target: &FetchTarget,
) -> Result<Vec<ImportedTrack>, FetchError> {
let url = match target.kind {
PlaylistKind::Favorites => format!("{API_BASE}/me/tracks?limit={PAGE_LIMIT}"),
PlaylistKind::Playlist => {
let id = target
.source_playlist_id
.as_deref()
.and_then(|uri| uri.strip_prefix("spotify:playlist:"))
.filter(|id| id.chars().all(|c| c.is_ascii_alphanumeric()) && !id.is_empty())
.ok_or(FetchError::NotFound)?;
format!(
"{API_BASE}/playlists/{id}/items?limit={PAGE_LIMIT}&additional_types=track,episode"
)
}
};
Ok(self
.pages(token, url)
.await?
.iter()
.enumerate()
.map(|(position, item)| api_track(position, item))
.collect())
}
/// Follows `next` links on the API host and returns every `items` entry.
async fn pages(&self, token: &AccessToken, first: String) -> Result<Vec<Value>, FetchError> {
let mut items = Vec::new();
let mut next = Some(first);
let mut pages = 0;
while let Some(url) = next.take() {
pages += 1;
if pages > MAX_PAGES {
return Err(FetchError::Failed("too many pages".to_owned()));
}
let mut page = self.get(token, &url).await?;
if let Some(Value::Array(page_items)) = page.get_mut("items").map(Value::take) {
items.extend(page_items);
}
next = page
.get("next")
.and_then(Value::as_str)
.filter(|url| url.starts_with(&format!("{API_BASE}/")))
.map(str::to_owned);
}
Ok(items)
}
/// GET with the token, honoring `Retry-After` and retrying server errors.
async fn get(&self, token: &AccessToken, url: &str) -> Result<Value, FetchError> {
let mut attempt = 0;
loop {
let (status, retry_after) =
match self.http.get(url).bearer_auth(token.secret()).send().await {
Ok(response) if response.status().is_success() => {
return response
.json()
.await
.map_err(|_| FetchError::Failed("invalid API response".to_owned()));
}
Ok(response) => (
response.status().as_u16(),
response
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|value| value.to_str().ok())
.map(str::to_owned),
),
// Timeouts and connection errors are retried like server errors.
Err(error) => {
tracing::debug!(reason = request_failure(&error), "Spotify request failed");
(503, None)
}
};
match retry_delay(status, retry_after.as_deref(), attempt) {
Some(delay) => {
tracing::info!(
status,
delay_seconds = delay.as_secs(),
"Spotify request postponed"
);
tokio::time::sleep(delay).await;
attempt += 1;
}
None => {
tracing::warn!(status, "Spotify request failed");
return Err(status_error(status));
}
}
}
}
}
/// Error kind without the URL, which may carry ids.
fn request_failure(error: &reqwest::Error) -> String {
if error.is_timeout() {
"timeout".to_owned()
} else if error.is_connect() {
"connection failed".to_owned()
} else {
"request failed".to_owned()
}
}
fn total(page: &Value) -> usize {
page.get("total")
.and_then(Value::as_u64)
.and_then(|total| usize::try_from(total).ok())
.unwrap_or(0)
}
fn text(value: Option<&Value>) -> Option<String> {
value
.and_then(Value::as_str)
.map(str::trim)
.filter(|text| !text.is_empty())
.map(str::to_owned)
}
/// `source_key` of the saved tracks: Spotify's own URI of the collection.
pub fn favorites_key(account_id: &str) -> String {
format!("spotify:user:{account_id}:collection")
}
fn favorites_preview(account_id: &str, count: usize) -> PreviewPlaylist {
PreviewPlaylist {
source_key: favorites_key(account_id),
kind: PlaylistKind::Favorites,
title: FAVORITES_TITLE.to_owned(),
description: None,
track_count: count,
unsupported_count: None,
available: true,
already_imported_in: None,
similar_to: None,
}
}
/// A playlist from `GET /me/playlists`. Items are readable in Development
/// Mode only for the user's own and collaborative playlists.
fn playlist_preview(item: &Value, account_id: &str) -> Option<PreviewPlaylist> {
let id = text(item.get("id"))?;
let owner = item
.get("owner")
.and_then(|owner| owner.get("id"))
.and_then(Value::as_str);
let collaborative = item
.get("collaborative")
.and_then(Value::as_bool)
.unwrap_or(false);
// The list object was called `tracks` before the 2026 API migration.
let count = item
.get("items")
.or_else(|| item.get("tracks"))
.map_or(0, total);
Some(PreviewPlaylist {
source_key: format!("spotify:playlist:{id}"),
kind: PlaylistKind::Playlist,
title: text(item.get("name")).unwrap_or_default(),
description: text(item.get("description")),
track_count: count,
unsupported_count: None,
available: owner == Some(account_id) || collaborative,
already_imported_in: None,
similar_to: None,
})
}
/// An entry of a playlist (`item`, formerly `track`) or of the saved tracks (`track`).
fn api_track(position: usize, entry: &Value) -> ImportedTrack {
let mut track = ImportedTrack {
kind: TrackKind::Unknown,
position: u32::try_from(position).unwrap_or(u32::MAX),
..ImportedTrack::default()
};
let Some(object) = ["item", "track"]
.iter()
.filter_map(|key| entry.get(*key))
.find(|value| value.is_object())
else {
return track;
};
let uri = text(object.get("uri"));
let is_local = object
.get("is_local")
.and_then(Value::as_bool)
.unwrap_or(false)
|| uri
.as_deref()
.is_some_and(|uri| uri.starts_with("spotify:local:"));
track.title = text(object.get("name")).unwrap_or_default();
track.duration_ms = object.get("duration_ms").and_then(Value::as_u64);
track.album = text(object.get("album").and_then(|album| album.get("name")));
match object.get("type").and_then(Value::as_str) {
_ if is_local => {
track.kind = TrackKind::LocalFile;
track.artists = artist_names(object);
}
Some("episode") => {
track.kind = TrackKind::Episode;
track.artists = text(object.get("show").and_then(|show| show.get("name")))
.into_iter()
.collect();
track.album = None;
track.source_id = uri;
}
Some("track") | None => {
track.kind = TrackKind::Track;
track.artists = artist_names(object);
track.isrc = text(object.get("external_ids").and_then(|ids| ids.get("isrc")));
track.version_hint = version_hint(&track.title);
track.source_id = uri;
}
Some(_) => {}
}
track
}
fn artist_names(object: &Value) -> Vec<String> {
object
.get("artists")
.and_then(Value::as_array)
.map(|artists| {
artists
.iter()
.filter_map(|artist| text(artist.get("name")))
.collect()
})
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::library_import::model::ResolutionStatus;
use serde_json::json;
#[test]
fn redirect_uris_follow_spotify_rules() {
for ok in [
"",
"https://music.example.org/api/imports/providers/spotify/callback",
"http://127.0.0.1:8080/api/imports/providers/spotify/callback",
"http://[::1]:8080/cb",
] {
assert!(validate_redirect_uri(ok).is_ok(), "{ok}");
}
for bad in [
"music.example.org/callback",
"http://music.example.org/callback",
"http://localhost:8080/callback",
"https://localhost/callback",
"https://example.org/cb#x",
"ftp://example.org/cb",
] {
assert!(validate_redirect_uri(bad).is_err(), "{bad}");
}
let mut config = AppConfig::default();
assert_eq!(
redirect_uri(&config, "https://music.example.org/"),
"https://music.example.org/api/imports/providers/spotify/callback"
);
config.spotify_redirect_uri = " https://proxy.example.org/cb ".into();
assert_eq!(
redirect_uri(&config, "http://internal:3000"),
"https://proxy.example.org/cb"
);
}
#[test]
fn sign_in_state_is_single_purpose_and_expires() {
let (auth, url) =
AuthState::begin("client123", "https://a.example/cb".into(), Some(42), 1000);
let url = reqwest::Url::parse(&url).unwrap();
let query: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect();
assert_eq!(url.host_str(), Some("accounts.spotify.com"));
assert_eq!(query["client_id"], "client123");
assert_eq!(query["code_challenge_method"], "S256");
assert_eq!(query["redirect_uri"], "https://a.example/cb");
assert_eq!(query["scope"], SCOPES);
assert_eq!(query["state"], auth.state);
// The verifier stays on the server; only its challenge is sent.
assert!(!url.as_str().contains(&auth.verifier));
assert!(!query.contains_key("import_id"));
assert_eq!(auth.verify(&auth.state.clone(), 1000 + 600), Ok(()));
assert_eq!(auth.import_id(), Some(42));
assert_eq!(auth.verify("forged", 1001), Err(AuthStateError::Mismatch));
assert_eq!(auth.verify("", 1001), Err(AuthStateError::Mismatch));
assert_eq!(
auth.verify(&auth.state.clone(), 1000 + 601),
Err(AuthStateError::Expired)
);
let (other, _) = AuthState::begin("client123", "https://a.example/cb".into(), None, 1000);
assert_ne!(other.state, auth.state);
assert_ne!(other.verifier, auth.verifier);
// The record round-trips through the session store.
let stored: AuthState =
serde_json::from_value(serde_json::to_value(&auth).unwrap()).unwrap();
assert_eq!(stored, auth);
}
#[test]
fn retries_follow_retry_after_and_back_off() {
assert_eq!(retry_delay(429, Some("7"), 0), Some(Duration::from_secs(7)));
assert_eq!(retry_delay(429, Some("0"), 0), Some(Duration::from_secs(1)));
assert_eq!(retry_delay(429, None, 2), Some(DEFAULT_RETRY_AFTER));
assert_eq!(retry_delay(429, Some("soon"), 0), Some(DEFAULT_RETRY_AFTER));
// A daily quota is not waited out by the worker.
assert_eq!(retry_delay(429, Some("86400"), 0), None);
assert_eq!(retry_delay(429, Some("1"), MAX_RATE_LIMIT_RETRIES), None);
assert_eq!(retry_delay(502, None, 0), Some(Duration::from_secs(1)));
assert_eq!(retry_delay(503, None, 3), Some(Duration::from_secs(8)));
assert_eq!(retry_delay(500, None, MAX_SERVER_ERROR_RETRIES), None);
for status in [400, 401, 403, 404] {
assert_eq!(retry_delay(status, Some("1"), 0), None);
}
assert_eq!(status_error(401), FetchError::Unauthorized);
assert_eq!(status_error(403), FetchError::Forbidden);
assert_eq!(status_error(429), FetchError::RateLimited);
assert_eq!(status_error(418), FetchError::Failed("HTTP 418".into()));
}
#[test]
fn api_entries_become_imported_tracks() {
let track = api_track(
3,
&json!({
"added_at": "2026-01-01T00:00:00Z",
"item": {
"type": "track",
"name": "Paranoid Android - Remastered",
"uri": "spotify:track:6LgJvl0Xdtc73RJ1mmpotq",
"duration_ms": 383_000,
"is_local": false,
"artists": [{"name": "Radiohead"}, {"name": " "}, {"id": "x"}],
"album": {"name": "OK Computer"},
"external_ids": {"isrc": "GBAYE9700131"}
}
}),
);
assert_eq!(track.kind, TrackKind::Track);
assert_eq!(track.position, 3);
assert_eq!(track.artists, ["Radiohead"]);
assert_eq!(track.album.as_deref(), Some("OK Computer"));
assert_eq!(track.duration_ms, Some(383_000));
assert_eq!(track.isrc.as_deref(), Some("GBAYE9700131"));
assert_eq!(track.version_hint.as_deref(), Some("Remastered"));
assert_eq!(
track.source_id.as_deref(),
Some("spotify:track:6LgJvl0Xdtc73RJ1mmpotq")
);
// Saved tracks and pre-migration playlist items use `track`.
let saved = api_track(
0,
&json!({"track": {"name": "Teardrop", "artists": [{"name": "Massive Attack"}]}}),
);
assert_eq!(saved.kind, TrackKind::Track);
assert_eq!(saved.title, "Teardrop");
let episode = api_track(
1,
&json!({"item": {"type": "episode", "name": "Ep 1", "show": {"name": "Show"}, "uri": "spotify:episode:1"}}),
);
assert_eq!(episode.kind, TrackKind::Episode);
assert_eq!(episode.artists, ["Show"]);
assert_eq!(
episode.initial_resolution().0,
ResolutionStatus::Unsupported
);
let local = api_track(
2,
&json!({"track": {"type": "track", "is_local": true, "name": "Demo", "uri": "spotify:local:a:b:Demo:10"}}),
);
assert_eq!(local.kind, TrackKind::LocalFile);
assert_eq!(local.source_id, None);
// Removed tracks come back as null and are kept as unsupported entries.
let removed = api_track(4, &json!({"item": null, "track": null}));
assert_eq!(removed.kind, TrackKind::Unknown);
assert_eq!(removed.position, 4);
assert_eq!(api_track(5, &json!("garbage")).kind, TrackKind::Unknown);
}
#[test]
fn playlist_list_marks_unreadable_playlists() {
let own = playlist_preview(
&json!({"id": "abc", "name": "Mine", "owner": {"id": "me"}, "collaborative": false, "items": {"total": 12}}),
"me",
)
.unwrap();
assert_eq!(own.source_key, "spotify:playlist:abc");
assert_eq!(own.track_count, 12);
assert!(own.available);
let shared = playlist_preview(
&json!({"id": "def", "name": "Shared", "owner": {"id": "other"}, "collaborative": true, "tracks": {"total": 3}}),
"me",
)
.unwrap();
assert!(shared.available);
assert_eq!(shared.track_count, 3);
let followed = playlist_preview(
&json!({"id": "ghi", "name": "Editorial", "owner": {"id": "spotify"}}),
"me",
)
.unwrap();
assert!(!followed.available);
assert!(playlist_preview(&json!({"name": "no id"}), "me").is_none());
let favorites = favorites_preview("me", 40);
assert_eq!(favorites.source_key, "spotify:user:me:collection");
assert_eq!(favorites.kind, PlaylistKind::Favorites);
}
}
+253 -20
View File
@@ -10,10 +10,11 @@ use serde_json::Value;
use sqlx::{PgConnection, PgPool, Row};
use super::model::{
AttemptView, ImportDetail, ImportStatistics, ImportStatus, ImportSummary, ImportedTrack,
ItemCursor, ItemView, ItemsPage, Phase, PlaylistKind, PlaylistLink, PlaylistView,
PublicationStatus, ResolutionStatus, SourceType,
self, AttemptView, ImportDetail, ImportStatistics, ImportStatus, ImportSummary, ImportedBefore,
ImportedPlaylist, ImportedTrack, ItemCursor, ItemView, ItemsPage, Phase, PlaylistKind,
PlaylistLink, PlaylistView, PublicationStatus, ResolutionStatus, SourceType,
};
use super::providers::FetchTarget;
/// Rows per `INSERT … SELECT FROM UNNEST` statement.
const INSERT_CHUNK: usize = 1000;
@@ -40,9 +41,34 @@ pub struct NewPlaylist {
pub source_key: String,
pub title: String,
pub description: Option<String>,
/// The user confirmed a new playlist although a similar one was imported before.
pub confirm_similar: bool,
pub items: Vec<NewItem>,
}
impl NewPlaylist {
/// A selected source playlist with all its entries, repeats and unsupported ones included.
pub fn from_imported(
playlist: &ImportedPlaylist,
source_key: String,
confirm_similar: bool,
) -> Self {
Self {
kind: playlist.kind,
source_playlist_id: playlist.source_id.clone(),
source_key,
title: playlist.title.clone(),
description: playlist.description.clone(),
confirm_similar,
items: playlist
.tracks
.iter()
.map(|track| NewItem::from_track(track, model::artist_key(track)))
.collect(),
}
}
}
pub struct NewItem {
pub source_track_id: Option<String>,
pub source_position: i32,
@@ -74,9 +100,18 @@ pub struct ImportConflict {
pub import_id: i64,
}
/// A selected playlist similar to an earlier import that was not confirmed.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct SimilarConflict {
pub source_key: String,
pub import_id: i64,
pub target_playlist_id: Option<i64>,
}
#[derive(Debug)]
pub enum CreateImportError {
AlreadyImported(Vec<ImportConflict>),
Similar(Vec<SimilarConflict>),
Database(sqlx::Error),
}
@@ -94,15 +129,35 @@ pub async fn create_import(pool: &PgPool, new: &NewImport) -> Result<i64, Create
.bind(new.user_id)
.execute(&mut *tx)
.await?;
let keys: Vec<&str> = new
.playlists
.iter()
.map(|playlist| playlist.source_key.as_str())
.collect();
let conflicts = imported_source_keys(&mut tx, new.user_id, &new.provider, &keys).await?;
let history = import_history(&mut tx, new.user_id, &new.provider).await?;
let mut conflicts = Vec::new();
let mut similar = Vec::new();
for playlist in &new.playlists {
let found = model::history_match(
&playlist.source_key,
playlist.kind,
&playlist.title,
&history,
);
if let Some(import_id) = found.already_imported_in {
conflicts.push(ImportConflict {
source_key: playlist.source_key.clone(),
import_id,
});
} else if let Some(before) = found.similar_to.filter(|_| !playlist.confirm_similar) {
similar.push(SimilarConflict {
source_key: playlist.source_key.clone(),
import_id: before.import_id,
target_playlist_id: before.target_playlist_id,
});
}
}
if !conflicts.is_empty() {
return Err(CreateImportError::AlreadyImported(conflicts));
}
if !similar.is_empty() {
return Err(CreateImportError::Similar(similar));
}
let import_id: i64 = sqlx::query_scalar(
"INSERT INTO furumusic__library_import
(user_id, provider, source_type, source_account_ref, federated_search, status)
@@ -137,30 +192,34 @@ pub async fn create_import(pool: &PgPool, new: &NewImport) -> Result<i64, Create
Ok(import_id)
}
/// Source keys of `keys` that this user already imported from `provider`.
pub async fn imported_source_keys(
/// Source playlists this user imported from `provider` before, oldest import first.
pub async fn import_history(
conn: &mut PgConnection,
user_id: i64,
provider: &str,
keys: &[&str],
) -> sqlx::Result<Vec<ImportConflict>> {
) -> sqlx::Result<Vec<ImportedBefore>> {
let rows = sqlx::query(
"SELECT DISTINCT ON (p.source_key) p.source_key, i.id
"SELECT p.source_key, p.kind, p.source_title, i.id, p.target_playlist_id
FROM furumusic__library_import_playlist p
JOIN furumusic__library_import i ON i.id = p.import_id
WHERE i.user_id = $1 AND i.provider = $2 AND p.source_key = ANY($3)
ORDER BY p.source_key, i.id",
WHERE i.user_id = $1 AND i.provider = $2
ORDER BY i.id, p.ordinal",
)
.bind(user_id)
.bind(provider)
.bind(keys)
.fetch_all(conn)
.await?;
Ok(rows
.into_iter()
.map(|row| ImportConflict {
source_key: row.get(0),
import_id: row.get(1),
.filter_map(|row| {
let kind: String = row.get(1);
Some(ImportedBefore {
source_key: row.get(0),
kind: kind.parse().ok()?,
title: row.get(2),
import_id: row.get(3),
target_playlist_id: row.get(4),
})
})
.collect())
}
@@ -542,6 +601,180 @@ async fn close_attempt(
Ok(())
}
// ---------------------------------------------------------------------------
// Worker: API fetching and repeated sign-in
// ---------------------------------------------------------------------------
/// A stored playlist of an API import whose entries are not fetched yet.
#[derive(Debug, Clone)]
pub struct PendingFetch {
pub playlist_id: i64,
pub target: FetchTarget,
}
/// Playlists without `fetched_at`, in import order. Fetched playlists are
/// skipped when an import continues after a repeated sign-in.
pub async fn playlists_to_fetch(pool: &PgPool, import_id: i64) -> sqlx::Result<Vec<PendingFetch>> {
let rows = sqlx::query(
"SELECT id, kind, source_playlist_id FROM furumusic__library_import_playlist
WHERE import_id = $1 AND fetched_at IS NULL ORDER BY ordinal",
)
.bind(import_id)
.fetch_all(pool)
.await?;
rows.into_iter()
.map(|row| {
let kind: String = row.get(1);
Ok(PendingFetch {
playlist_id: row.get(0),
target: FetchTarget {
kind: kind.parse().map_err(|_| {
sqlx::Error::Decode("unknown library import playlist kind".into())
})?,
source_playlist_id: row.get(2),
},
})
})
.collect()
}
/// Stores the fetched entries of one playlist and marks it fetched in one
/// transaction. `false` when the worker no longer owns the import.
pub async fn store_fetched(
pool: &PgPool,
import_id: i64,
run_id: i64,
playlist_id: i64,
items: &[NewItem],
) -> sqlx::Result<bool> {
let mut tx = pool.begin().await?;
let owned: Option<i64> = sqlx::query_scalar(
"SELECT id FROM furumusic__library_import
WHERE id = $1 AND lease_owner = $2 AND status = 'running' FOR SHARE",
)
.bind(import_id)
.bind(run_id)
.fetch_optional(&mut *tx)
.await?;
if owned.is_none() {
return Ok(false);
}
let marked = sqlx::query(
"UPDATE furumusic__library_import_playlist SET fetched_at = now()
WHERE id = $1 AND import_id = $2 AND fetched_at IS NULL",
)
.bind(playlist_id)
.bind(import_id)
.execute(&mut *tx)
.await?
.rows_affected()
== 1;
if marked {
insert_items(&mut tx, playlist_id, items).await?;
refresh_statistics(&mut tx, import_id).await?;
}
tx.commit().await?;
Ok(true)
}
/// Parks an API import until the user signs in again. The phase and the
/// open attempt stay, so the import continues where it stopped.
pub async fn wait_for_reauth(pool: &PgPool, import_id: i64, run_id: i64) -> sqlx::Result<bool> {
Ok(sqlx::query(
"UPDATE furumusic__library_import
SET status = 'needs_reauth', lease_owner = NULL, lease_until = NULL,
updated_at = now()
WHERE id = $1 AND lease_owner = $2 AND status = 'running'",
)
.bind(import_id)
.bind(run_id)
.execute(pool)
.await?
.rows_affected()
== 1)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReauthTarget {
/// The user's API import of this provider waits for a sign-in.
Waiting,
NotWaiting,
NotFound,
}
/// Whether a repeated sign-in may be started for this import.
pub async fn reauth_target(
pool: &PgPool,
user_id: i64,
import_id: i64,
provider: &str,
) -> sqlx::Result<ReauthTarget> {
let status: Option<String> = sqlx::query_scalar(
"SELECT status FROM furumusic__library_import
WHERE id = $1 AND user_id = $2 AND provider = $3 AND source_type = 'api'",
)
.bind(import_id)
.bind(user_id)
.bind(provider)
.fetch_optional(pool)
.await?;
Ok(match status.as_deref() {
None => ReauthTarget::NotFound,
Some("needs_reauth") => ReauthTarget::Waiting,
Some(_) => ReauthTarget::NotWaiting,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReauthOutcome {
/// Queued again; the worker continues the same import.
Resumed,
/// The user signed in with another provider account; nothing changed.
AccountMismatch,
NotWaiting,
NotFound,
}
/// Queues an import that waited for a sign-in, if the account is the one it was created with.
pub async fn resume_after_reauth(
pool: &PgPool,
user_id: i64,
import_id: i64,
account_ref: &str,
) -> sqlx::Result<ReauthOutcome> {
let mut tx = pool.begin().await?;
let row: Option<(String, Option<String>)> = sqlx::query_as(
"SELECT status, source_account_ref FROM furumusic__library_import
WHERE id = $1 AND user_id = $2 AND source_type = 'api' FOR UPDATE",
)
.bind(import_id)
.bind(user_id)
.fetch_optional(&mut *tx)
.await?;
let outcome = match row {
None => ReauthOutcome::NotFound,
Some((status, _)) if status != ImportStatus::NeedsReauth.as_str() => {
ReauthOutcome::NotWaiting
}
Some((_, account)) if account.as_deref() != Some(account_ref) => {
ReauthOutcome::AccountMismatch
}
Some(_) => {
sqlx::query(
"UPDATE furumusic__library_import
SET status = 'queued', error = NULL, updated_at = now()
WHERE id = $1 AND status = 'needs_reauth'",
)
.bind(import_id)
.execute(&mut *tx)
.await?;
ReauthOutcome::Resumed
}
};
tx.commit().await?;
Ok(outcome)
}
// ---------------------------------------------------------------------------
// Owner requests
// ---------------------------------------------------------------------------
+499 -3
View File
@@ -2,15 +2,26 @@
//! creates and drops a unique schema in the disposable database from
//! `FURU_LIBRARY_IMPORT_TEST_DATABASE_URL`.
use std::sync::Arc;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use serde_json::json;
use sqlx::PgPool;
use super::adapters::spotify_export::SpotifyExport;
use super::adapters::{self, FileAdapter, InputFile};
use super::handlers::select_file_playlists;
use super::job;
use super::model::{ImportedTrack, Phase, PlaylistKind, ResolutionStatus, SourceType, TrackKind};
use super::model::{
self as import_model, ImportedLibrary, ImportedTrack, Phase, PlaylistKind, ResolutionStatus,
SourceType, TrackKind,
};
use super::providers::{
AccessToken, Connection, FetchError, FetchTarget, LibraryFetcher, TOKEN_TTL, TokenVault,
};
use super::store::{
self, CancelOutcome, Control, CreateImportError, DeleteOutcome, FinishOutcome, ItemFilter,
NewImport, NewItem, NewPlaylist,
NewImport, NewItem, NewPlaylist, ReauthOutcome, ReauthTarget,
};
use crate::config::AppConfig;
use crate::scheduler::JobLog;
@@ -127,6 +138,8 @@ fn playlist(key: &str, title: &str, tracks: &[ImportedTrack]) -> NewPlaylist {
source_key: key.into(),
title: title.into(),
description: None,
// Several tests reuse one title; similar playlists have their own test.
confirm_similar: true,
items: tracks
.iter()
.map(|track| NewItem::from_track(track, track.artists.first().cloned()))
@@ -705,3 +718,486 @@ async fn library_import_cancel_and_delete_keep_playlists() {
assert_eq!(remaining, 0);
db.drop().await;
}
fn parse_export(files: &[(&str, String)]) -> ImportedLibrary {
let files: Vec<InputFile> = files
.iter()
.map(|(name, data)| InputFile {
name: (*name).into(),
data: data.clone().into_bytes(),
})
.collect();
SpotifyExport.parse(&files).unwrap()
}
fn export_import(
user_id: i64,
library: &ImportedLibrary,
selection: &[String],
confirm: &[String],
) -> NewImport {
NewImport {
user_id,
provider: library.provider.clone(),
source_type: SourceType::File,
source_account_ref: None,
federated_search: false,
playlists: select_file_playlists(library, selection, confirm).unwrap(),
}
}
#[tokio::test]
#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"]
async fn library_import_stores_every_entry_of_a_large_export() {
let _serial = SERIAL.lock().await;
let db = Fixture::new().await;
let pool = &db.pool;
// 5000 entries: every 10th is an episode, every 7th repeats an earlier track.
let items: Vec<serde_json::Value> = (0..5000)
.map(|index| {
if index % 10 == 9 {
json!({"track": null, "episode": {"episodeName": format!("Episode {index}"), "showName": "Show"}, "localTrack": null})
} else {
let track = if index % 7 == 6 { index - 6 } else { index };
json!({"track": {
"trackName": format!("Song {track}"),
"artistName": format!("Artist {}", track % 300),
"albumName": format!("Album {}", track % 900),
"trackUri": format!("spotify:track:{track:022}")
}, "episode": null, "localTrack": null, "addedDate": "2026-01-01"})
}
})
.collect();
let export = json!({"playlists": [{"name": "Everything", "items": items}]}).to_string();
let library = parse_export(&[("Playlist1.json", export)]);
let keys = adapters::source_keys(&library);
let id = store::create_import(pool, &export_import(1, &library, &keys, &[]))
.await
.unwrap();
let (total, positions, unsupported, repeats): (i64, i64, i64, i64) = sqlx::query_as(
"SELECT count(*), count(DISTINCT i.source_position),
count(*) FILTER (WHERE i.resolution_status = 'unsupported'),
count(*) FILTER (WHERE i.resolution_status = 'pending')
- count(DISTINCT i.source_track_id) FILTER (WHERE i.resolution_status = 'pending')
FROM furumusic__library_import_item i
JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id
WHERE p.import_id = $1",
)
.bind(id)
.fetch_one(pool)
.await
.unwrap();
assert_eq!(total, 5000);
assert_eq!(positions, 5000);
assert_eq!(unsupported, 500);
assert!(
repeats > 500,
"repeats are stored as separate entries: {repeats}"
);
let detail = store::get_import(pool, 1, id).await.unwrap().unwrap();
assert_eq!(detail.summary.statistics["total"], 5000);
assert_eq!(detail.summary.statistics["unsupported"], 500);
assert_eq!(detail.summary.status, "queued");
assert_eq!(detail.source_playlists[0].total, 5000);
// Entries keep the normalized main artist for the resolver.
let artist_key: String = db
.scalar(
"SELECT i.artist_key FROM furumusic__library_import_item i
JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id
WHERE p.import_id = $1 AND i.source_position = 0",
id,
)
.await;
assert_eq!(artist_key, "artist 0");
db.drop().await;
}
#[tokio::test]
#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"]
async fn library_import_asks_before_importing_a_changed_export_again() {
let _serial = SERIAL.lock().await;
let db = Fixture::new().await;
let pool = &db.pool;
let fixture = |extra: Option<&str>| {
let mut playlists: serde_json::Value = serde_json::from_str(include_str!(
"adapters/fixtures/spotify_export/Playlist1.json"
))
.unwrap();
if let Some(title) = extra {
playlists["playlists"][0]["items"]
.as_array_mut()
.unwrap()
.push(json!({"track": {"trackName": title, "artistName": "Someone"}}));
}
parse_export(&[
("Playlist1.json", playlists.to_string()),
(
"YourLibrary.json",
include_str!("adapters/fixtures/spotify_export/YourLibrary.json").to_owned(),
),
])
};
let original = fixture(None);
let keys = adapters::source_keys(&original);
// Favorites and "Road trip".
let first = store::create_import(pool, &export_import(1, &original, &keys[..2], &[]))
.await
.unwrap();
sqlx::raw_sql(
"INSERT INTO furumusic__playlist (id, owner_id, title) VALUES (900, 1, 'Road trip');
UPDATE furumusic__library_import_playlist SET target_playlist_id = 900, target_created_at = now()
WHERE source_title = 'Road trip';",
)
.execute(pool)
.await
.unwrap();
// The same export: both playlists are repeats; the others are new.
let history = store::import_history(&mut pool.acquire().await.unwrap(), 1, "spotify")
.await
.unwrap();
let matches: Vec<import_model::HistoryMatch> = original
.entries()
.zip(&keys)
.map(|(playlist, key)| {
import_model::history_match(key, playlist.kind, &playlist.title, &history)
})
.collect();
assert_eq!(matches[0].already_imported_in, Some(first));
assert_eq!(matches[1].already_imported_in, Some(first));
assert_eq!(matches[2], import_model::HistoryMatch::default());
match store::create_import(pool, &export_import(1, &original, &keys[1..3], &[])).await {
Err(CreateImportError::AlreadyImported(conflicts)) => {
assert_eq!(conflicts.len(), 1);
assert_eq!(conflicts[0].source_key, keys[1]);
}
other => panic!("expected a repeat, got {other:?}"),
}
// A changed "Road trip" is similar: refused until the user confirms a new playlist.
let changed = fixture(Some("New song"));
let changed_keys = adapters::source_keys(&changed);
assert_ne!(changed_keys[1], keys[1]);
assert_eq!(changed_keys[2], keys[2]);
let similar = import_model::history_match(
&changed_keys[1],
PlaylistKind::Playlist,
"Road trip",
&history,
);
assert_eq!(similar.already_imported_in, None);
assert_eq!(
similar.similar_to,
Some(import_model::SimilarTo {
import_id: first,
target_playlist_id: Some(900)
})
);
let selection = [changed_keys[1].clone(), changed_keys[2].clone()];
match store::create_import(pool, &export_import(1, &changed, &selection, &[])).await {
Err(CreateImportError::Similar(similar)) => {
assert_eq!(
similar,
[store::SimilarConflict {
source_key: changed_keys[1].clone(),
import_id: first,
target_playlist_id: Some(900),
}]
);
}
other => panic!("expected a similar playlist, got {other:?}"),
}
assert_eq!(store::list_imports(pool, 1).await.unwrap().len(), 1);
let second = store::create_import(
pool,
&export_import(1, &changed, &selection, &[changed_keys[1].clone()]),
)
.await
.unwrap();
let titles: Vec<String> = sqlx::query_scalar(
"SELECT source_title FROM furumusic__library_import_playlist WHERE import_id = $1 ORDER BY ordinal",
)
.bind(second)
.fetch_all(pool)
.await
.unwrap();
assert_eq!(titles, ["Road trip", "Русский рок"]);
// Another user's history does not interfere.
store::create_import(pool, &export_import(2, &original, &keys, &[]))
.await
.unwrap();
db.drop().await;
}
/// A provider API stand-in: records requests and refuses chosen playlists once.
#[derive(Default)]
struct FakeApi {
calls: Mutex<Vec<String>>,
expire_once: Mutex<HashSet<String>>,
}
fn target_name(target: &FetchTarget) -> String {
target
.source_playlist_id
.clone()
.unwrap_or_else(|| target.kind.as_str().to_owned())
}
#[async_trait::async_trait]
impl LibraryFetcher for FakeApi {
async fn fetch_playlist(
&self,
provider: &str,
token: &AccessToken,
target: &FetchTarget,
) -> Result<Vec<ImportedTrack>, FetchError> {
assert_eq!(provider, "spotify");
let name = target_name(target);
self.calls.lock().unwrap().push(name.clone());
if self.expire_once.lock().unwrap().remove(&name) {
return Err(FetchError::Unauthorized);
}
if name.ends_with(":editorial") {
return Err(FetchError::Forbidden);
}
assert_eq!(token.secret(), "token");
Ok(vec![
track(0, &format!("{name} first"), "Artist", "Album"),
track(1, &format!("{name} second"), "Artist", "Album"),
])
}
}
fn api_playlist(kind: PlaylistKind, key: &str, title: &str) -> NewPlaylist {
NewPlaylist {
kind,
source_playlist_id: Some(key.into()),
source_key: key.into(),
title: title.into(),
description: None,
confirm_similar: false,
items: Vec::new(),
}
}
fn token_for(account: &str) -> Connection {
Connection {
provider: "spotify".into(),
account_ref: account.into(),
token: AccessToken::new("token"),
}
}
#[tokio::test]
#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"]
async fn library_import_continues_the_same_api_import_after_signing_in_again() {
let _serial = SERIAL.lock().await;
let db = Fixture::new().await;
let pool = &db.pool;
let vault = TokenVault::shared();
let id = store::create_import(
pool,
&NewImport {
user_id: 1,
provider: "spotify".into(),
source_type: SourceType::Api,
source_account_ref: Some("acc".into()),
federated_search: false,
playlists: vec![
api_playlist(
PlaylistKind::Favorites,
"spotify:user:acc:collection",
"Liked Songs",
),
api_playlist(PlaylistKind::Playlist, "spotify:playlist:a", "A"),
api_playlist(PlaylistKind::Playlist, "spotify:playlist:b", "B"),
api_playlist(
PlaylistKind::Playlist,
"spotify:playlist:editorial",
"Editorial",
),
],
},
)
.await
.unwrap();
let api = Arc::new(FakeApi::default());
let run = |run_id: i64| {
let api = Arc::clone(&api);
async move {
let mut log = crate::scheduler::JobLog::new();
job::run_worker_with(pool, Arc::new(AppConfig::default()), run_id, &mut log, api)
.await
.unwrap();
log.output()
}
};
// After a restart the token is gone: the import waits for a sign-in in the fetching phase.
vault.forget_import(id);
let log = run(401).await;
assert!(log.contains("waiting for the user to sign in"), "{log}");
assert_eq!(db.status(id).await, "needs_reauth");
let phase: Option<String> = db
.scalar(
"SELECT phase FROM furumusic__library_import WHERE id = $1",
id,
)
.await;
assert_eq!(phase.as_deref(), Some("fetching"));
assert!(api.calls.lock().unwrap().is_empty());
assert!(
!job::needs_worker(pool).await.unwrap(),
"nothing to claim while waiting"
);
// A sign-in may be started only for the owner's waiting API import.
assert_eq!(
store::reauth_target(pool, 1, id, "spotify").await.unwrap(),
ReauthTarget::Waiting
);
assert_eq!(
store::reauth_target(pool, 2, id, "spotify").await.unwrap(),
ReauthTarget::NotFound
);
assert_eq!(
store::reauth_target(pool, 1, id, "deezer").await.unwrap(),
ReauthTarget::NotFound
);
// Another Spotify account cannot continue the import.
assert_eq!(
store::resume_after_reauth(pool, 1, id, "other")
.await
.unwrap(),
ReauthOutcome::AccountMismatch
);
assert_eq!(
store::resume_after_reauth(pool, 2, id, "acc")
.await
.unwrap(),
ReauthOutcome::NotFound
);
assert_eq!(db.status(id).await, "needs_reauth");
// The right account continues the same import; B's token expires midway.
api.expire_once
.lock()
.unwrap()
.insert("spotify:playlist:b".into());
vault.store_for_import(1, id, token_for("acc"), TOKEN_TTL);
assert_eq!(
store::resume_after_reauth(pool, 1, id, "acc")
.await
.unwrap(),
ReauthOutcome::Resumed
);
assert_eq!(db.status(id).await, "queued");
let log = run(402).await;
assert!(log.contains("claimed (phase fetching)"), "{log}");
assert_eq!(db.status(id).await, "needs_reauth");
assert_eq!(vault.import_token(id), None, "an expired token is dropped");
let fetched: Vec<(String, bool)> = sqlx::query_as(
"SELECT source_key, fetched_at IS NOT NULL FROM furumusic__library_import_playlist
WHERE import_id = $1 ORDER BY ordinal",
)
.bind(id)
.fetch_all(pool)
.await
.unwrap();
assert_eq!(
fetched,
[
("spotify:user:acc:collection".into(), true),
("spotify:playlist:a".into(), true),
("spotify:playlist:b".into(), false),
("spotify:playlist:editorial".into(), false),
]
);
// Signing in again fetches only what is missing and finishes the same import.
vault.store_for_import(1, id, token_for("acc"), TOKEN_TTL);
assert_eq!(
store::resume_after_reauth(pool, 1, id, "acc")
.await
.unwrap(),
ReauthOutcome::Resumed
);
assert_eq!(
store::resume_after_reauth(pool, 1, id, "acc")
.await
.unwrap(),
ReauthOutcome::NotWaiting
);
let log = run(403).await;
assert!(
log.contains("fetched 2 playlists with 2 entries (1 not readable)"),
"{log}"
);
assert!(log.contains("done"), "{log}");
assert_eq!(db.status(id).await, "done");
assert_eq!(
*api.calls.lock().unwrap(),
[
"spotify:user:acc:collection",
"spotify:playlist:a",
"spotify:playlist:b",
"spotify:playlist:b",
"spotify:playlist:editorial",
]
);
assert_eq!(
vault.import_token(id),
None,
"the token is dropped after fetching"
);
let detail = store::get_import(pool, 1, id).await.unwrap().unwrap();
assert_eq!(detail.summary.statistics["total"], 6);
let totals: Vec<i64> = detail
.source_playlists
.iter()
.map(|playlist| playlist.total)
.collect();
assert_eq!(totals, [2, 2, 2, 0]);
// One attempt spans the interruptions; no new import was created.
let attempts: Vec<(String, String)> = sqlx::query_as(
"SELECT kind, status FROM furumusic__library_import_attempt WHERE import_id = $1",
)
.bind(id)
.fetch_all(pool)
.await
.unwrap();
assert_eq!(attempts, [("initial".into(), "done".into())]);
assert_eq!(store::list_imports(pool, 1).await.unwrap().len(), 1);
assert_eq!(
store::reauth_target(pool, 1, id, "spotify").await.unwrap(),
ReauthTarget::NotWaiting
);
// Cancelling a waiting import is immediate.
let waiting = store::create_import(
pool,
&NewImport {
user_id: 1,
provider: "spotify".into(),
source_type: SourceType::Api,
source_account_ref: Some("acc".into()),
federated_search: false,
playlists: vec![api_playlist(
PlaylistKind::Playlist,
"spotify:playlist:c",
"C",
)],
},
)
.await
.unwrap();
run(404).await;
assert_eq!(db.status(waiting).await, "needs_reauth");
assert_eq!(
store::request_cancel(pool, 1, waiting).await.unwrap(),
CancelOutcome::Cancelled
);
db.drop().await;
}
+4 -1
View File
@@ -628,7 +628,10 @@ impl Project for FuruProject {
"/api/podcasts",
);
apps.register_with_views(
library_import::ImportApp::new(Arc::clone(&self.app_config)),
library_import::ImportApp::new(
Arc::clone(&self.app_config),
Arc::clone(&self.scheduler_handle),
),
"/api/imports",
);
apps.register_with_views(
+1 -1
View File
@@ -70,7 +70,7 @@ html { overscroll-behavior:none; }
.task-form-body { overflow:visible; }
.run-log-body { min-height:300px; overflow:visible; }
.run-log-output { min-height:50dvh; max-height:70dvh; }
.settings-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"access" "oidc" "agent" "agentstatus" "similarity" "similaritystatus" "downloads" "federation" "lastfm" "developer" "lyrics" "actions"; }
.settings-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"access" "oidc" "agent" "agentstatus" "similarity" "similaritystatus" "downloads" "federation" "lastfm" "developer" "spotify" "lyrics" "actions"; }
.settings-federation-body { grid-template-columns:minmax(0,1fr); }
.repair-shell { grid-template-columns:250px minmax(0,1fr); }
}
+2
View File
@@ -867,6 +867,7 @@ tbody tr:hover {
"downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads"
"federation federation federation federation federation federation federation federation federation federation federation federation"
"lastfm lastfm lastfm lastfm lastfm lastfm lastfm lastfm developer developer developer developer"
"spotify spotify spotify spotify spotify spotify spotify spotify spotify spotify spotify spotify"
"lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics"
"actions actions actions actions actions actions actions actions actions actions actions actions";
gap: 16px;
@@ -890,6 +891,7 @@ tbody tr:hover {
.settings-downloads { grid-area: downloads; }
.settings-federation { grid-area: federation; }
.settings-lastfm { grid-area: lastfm; }
.settings-spotify { grid-area: spotify; }
.settings-lyrics { grid-area: lyrics; min-width:0; }
.lyrics-search-status {margin:0 16px 16px;min-width:0}
.lyrics-search-status .probe-row {gap:12px;flex-wrap:wrap}
+41 -2
View File
@@ -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';