2026-11-26 16:05:42 +02:00
|
|
|
//! 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.
|
|
|
|
|
|
2026-11-26 16:30:07 +02:00
|
|
|
pub mod spotify_export;
|
|
|
|
|
|
|
|
|
|
use std::collections::HashSet;
|
2026-11-26 16:05:42 +02:00
|
|
|
use std::fmt;
|
|
|
|
|
|
2026-11-26 16:30:07 +02:00
|
|
|
use sha2::{Digest, Sha256};
|
|
|
|
|
|
|
|
|
|
use super::model::{ImportedLibrary, ImportedPlaylist, ProviderInfo, SourceType};
|
2026-11-26 16:05:42 +02:00
|
|
|
|
|
|
|
|
/// 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] {
|
2026-11-26 16:30:07 +02:00
|
|
|
&[&spotify_export::SpotifyExport]
|
2026-11-26 16:05:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn file_adapter(provider: &str) -> Option<&'static dyn FileAdapter> {
|
|
|
|
|
file_adapters()
|
|
|
|
|
.iter()
|
|
|
|
|
.copied()
|
|
|
|
|
.find(|adapter| adapter.provider() == provider)
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-26 16:30:07 +02:00
|
|
|
/// 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())
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-26 16:05:42 +02:00
|
|
|
/// 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()
|
|
|
|
|
}
|
2026-11-26 16:30:07 +02:00
|
|
|
|
|
|
|
|
#[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);
|
|
|
|
|
}
|
|
|
|
|
}
|