Files
furumi-web/src/library_import/adapters/mod.rs
T
sanapachandClaude Opus 5.5 ff87d9110d Import Spotify data exports and optionally playlists from the Spotify Web API
Add the Spotify adapter to the library import. The data export path parses
Playlist*.json and YourLibrary.json sent by the browser, tolerates missing
and unexpected keys, keeps the source order and repeats, and stores episodes,
audiobooks, local files and unreadable entries as unsupported instead of
dropping them. The bundled export fixture is synthetic and must be joined by
an anonymized real export before acceptance.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:30:07 +02:00

222 lines
7.1 KiB
Rust

//! File adapters convert exported provider data into [`ImportedLibrary`].
//!
//! Adapters are pure: they receive file names and bytes and never touch the
//! database or the network.
pub mod spotify_export;
use std::collections::HashSet;
use std::fmt;
use sha2::{Digest, Sha256};
use super::model::{ImportedLibrary, ImportedPlaylist, ProviderInfo, SourceType};
/// One uploaded file. Raw files are parsed in memory and never stored.
#[derive(Debug, Clone)]
pub struct InputFile {
pub name: String,
pub data: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdapterError {
/// None of the files belongs to this provider's export.
NoSupportedFiles,
/// A recognised file could not be parsed. The message never contains file contents.
Invalid { file: String, reason: String },
}
impl fmt::Display for AdapterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoSupportedFiles => f.write_str("no supported files in the upload"),
Self::Invalid { file, reason } => write!(f, "{file}: {reason}"),
}
}
}
impl std::error::Error for AdapterError {}
pub trait FileAdapter: Send + Sync {
/// Provider id stored in `furumusic__library_import.provider`.
fn provider(&self) -> &'static str;
/// Name shown in the import wizard.
fn display_name(&self) -> &'static str;
/// Whether a file name belongs to this provider's export.
fn accepts(&self, file_name: &str) -> bool;
fn parse(&self, files: &[InputFile]) -> Result<ImportedLibrary, AdapterError>;
}
/// File adapters available on this instance.
pub fn file_adapters() -> &'static [&'static dyn FileAdapter] {
&[&spotify_export::SpotifyExport]
}
pub fn file_adapter(provider: &str) -> Option<&'static dyn FileAdapter> {
file_adapters()
.iter()
.copied()
.find(|adapter| adapter.provider() == provider)
}
/// The base name of an uploaded path such as `Spotify Account Data/Playlist1.json`.
pub fn base_name(name: &str) -> &str {
name.rsplit(['/', '\\']).next().unwrap_or(name)
}
/// The version marker a title carries, such as `Live` in `Song - Live` or
/// `Remix` in `Song (Remix)`. The matcher makes the final decision.
pub fn version_hint(title: &str) -> Option<String> {
let title = title.trim();
let (base, hint) = if let Some(split) = title.rsplit_once(" - ") {
split
} else {
let (close, open) = match title.chars().last()? {
')' => (')', '('),
']' => (']', '['),
_ => return None,
};
let inner = title.strip_suffix(close)?;
let index = inner.rfind(open)?;
(&inner[..index], &inner[index + 1..])
};
let hint = hint.trim();
(!base.trim().is_empty() && !hint.is_empty()).then(|| hint.to_owned())
}
/// Re-import keys of `library.entries()`, in the same order.
///
/// A provider playlist id is the key when there is one. Otherwise the key is
/// a hash of the kind, the title and the ordered track keys, so the same
/// export gives the same keys while a changed one does not. Equal playlists
/// inside one library get their position appended to stay distinct.
pub fn source_keys(library: &ImportedLibrary) -> Vec<String> {
let mut seen = HashSet::new();
library
.entries()
.enumerate()
.map(|(ordinal, playlist)| {
let key = playlist
.source_id
.clone()
.unwrap_or_else(|| content_key(playlist));
if seen.insert(key.clone()) {
key
} else {
format!("{key}#{ordinal}")
}
})
.collect()
}
fn content_key(playlist: &ImportedPlaylist) -> String {
let mut hash = Sha256::new();
hash.update(playlist.kind.as_str());
hash.update([0]);
hash.update(playlist.title.trim());
for track in &playlist.tracks {
hash.update([0]);
match &track.source_id {
Some(id) => hash.update(id),
None => {
hash.update(track.kind.as_str());
for part in std::iter::once(&track.title)
.chain(&track.artists)
.chain(&track.album)
{
hash.update([1]);
hash.update(music_dht::normalize_name(part));
}
}
}
}
format!("sha256:{:x}", hash.finalize())
}
/// Providers with a file import path. API methods are added by provider integrations.
pub fn file_providers() -> Vec<ProviderInfo> {
file_adapters()
.iter()
.map(|adapter| ProviderInfo {
id: adapter.provider(),
name: adapter.display_name(),
methods: vec![SourceType::File],
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::library_import::model::{ImportedTrack, PlaylistKind};
#[test]
fn version_hints_come_from_suffixes_and_brackets() {
for (title, hint) in [
("Wonderwall - Remastered 2014", Some("Remastered 2014")),
("Song (Live at Wembley)", Some("Live at Wembley")),
("Song [Demo]", Some("Demo")),
("Song", None),
("(Untitled)", None),
("Song ()", None),
] {
assert_eq!(version_hint(title).as_deref(), hint, "{title}");
}
}
#[test]
fn base_names_drop_archive_folders() {
assert_eq!(
base_name("Spotify Account Data/Playlist1.json"),
"Playlist1.json"
);
assert_eq!(
base_name("my_spotify_data\\YourLibrary.json"),
"YourLibrary.json"
);
assert_eq!(base_name("Playlist2.json"), "Playlist2.json");
}
fn playlist(title: &str, ids: &[&str]) -> ImportedPlaylist {
ImportedPlaylist {
kind: PlaylistKind::Playlist,
title: title.into(),
tracks: ids
.iter()
.enumerate()
.map(|(position, id)| ImportedTrack {
source_id: Some((*id).into()),
position: position as u32,
title: (*id).into(),
..ImportedTrack::default()
})
.collect(),
..ImportedPlaylist::default()
}
}
#[test]
fn source_keys_follow_contents_and_stay_unique() {
let library = ImportedLibrary {
playlists: vec![
playlist("Mix", &["a", "b"]),
playlist("Mix", &["a", "b"]),
playlist("Mix", &["b", "a"]),
ImportedPlaylist {
source_id: Some("spotify:playlist:1".into()),
..playlist("Mix", &["a", "b"])
},
],
..ImportedLibrary::default()
};
let keys = source_keys(&library);
assert!(keys[0].starts_with("sha256:"));
assert_eq!(keys[1], format!("{}#1", keys[0]));
assert_ne!(keys[2], keys[0], "order is part of the key");
assert_eq!(keys[3], "spotify:playlist:1");
// The same export gives the same keys.
assert_eq!(source_keys(&library.clone()), keys);
}
}