//! Music out: the tree Navidrome, Jellyfin, Plex and Kodi read, playlists //! they import, and listens in ListenBrainz' import shape. //! //! ```text //! Music/ //! // //! NN Title. the song file as stored (D-NN on a many-disc album) //! cover. the album's cover as stored //! playlists/.m3u8 #EXTM3U with #EXTINF, paths relative to the list //! listens.jsonl one ListenBrainz listen per line //! ``` //! //! A listen is exported only when it counts as a scrobble (the Last.fm rule //! ListenBrainz follows): it finished, or it lasted half the song or four //! minutes, whichever is less. use std::collections::{BTreeMap, BTreeSet}; use chrono::{DateTime, NaiveDate}; use serde_json::{json, Value as JsonValue}; use super::{by_id, component, extension, number, refuse, text, unique, Out, Result, Row, LISTS, LIST_MEMBERS}; /// Four minutes: a listen this long counts whatever the song's length. const SCROBBLE_SECONDS: f64 = 240.0; pub(super) fn write(out: &mut Out) -> Result<()> { let songs = out.rows("song"); let albums = out.rows("music_album"); let artists = out.rows("artist"); let albums_by_id = by_id(&albums); let artists_by_id = by_id(&artists); // Each album's folder: songs linked to an album row gather under it, the // rest by their artist and album title. struct Folder<'a> { artist: String, album: String, cover: Option<&'a str>, many_discs: bool, songs: Vec<&'a Row>, } let mut folders: BTreeMap = BTreeMap::new(); for song in &songs { if text(song, "file").is_none() { continue; } let album = text(song, "album").and_then(|id| albums_by_id.get(id).copied()); let artist = album .and_then(|album| { text(album, "artist_name") .or_else(|| text(album, "artist").and_then(|id| artists_by_id.get(id)).and_then(|artist| text(artist, "name"))) }) .or_else(|| text(song, "artist_name")) .or_else(|| text(song, "artist").and_then(|id| artists_by_id.get(id)).and_then(|artist| text(artist, "name"))); let title = album.and_then(|album| text(album, "title")).or_else(|| text(song, "album_title")); let artist = component(artist, "Unknown Artist"); let title = component(title, "Unknown Album"); let key = album .and_then(|album| text(album, "id")) .map(|id| format!("album:{id}")) .unwrap_or_else(|| format!("named:{}\u{0}{}", artist.to_lowercase(), title.to_lowercase())); let folder = folders.entry(key).or_insert_with(|| Folder { artist, album: title, cover: album.and_then(|album| text(album, "cover")), many_discs: album.and_then(|album| number(album, "discs")).is_some_and(|discs| discs > 1.0), songs: Vec::new(), }); folder.cover = folder.cover.or_else(|| text(song, "cover")); folder.many_discs |= number(song, "disc_number").is_some_and(|disc| disc > 1.0); folder.songs.push(song); } // Folders in artist and album order, each spelled once case-insensitively. let mut ordered: Vec = folders.into_values().collect(); ordered.sort_by_key(|folder| (folder.artist.to_lowercase(), folder.album.to_lowercase())); let mut artist_spelling: BTreeMap = BTreeMap::new(); let mut albums_taken: BTreeMap> = BTreeMap::new(); // Where each song's file landed, relative to `Music/`. let mut landed: BTreeMap = BTreeMap::new(); for folder in &mut ordered { let artist = artist_spelling.entry(folder.artist.to_lowercase()).or_insert_with(|| folder.artist.clone()).clone(); let album = unique(albums_taken.entry(artist.to_lowercase()).or_default(), &folder.album); let path = format!("{artist}/{album}"); folder.songs.sort_by(|a, b| { let at = |row: &Row, column: &str| number(row, column).unwrap_or(f64::MAX); at(a, "disc_number") .total_cmp(&at(b, "disc_number")) .then_with(|| at(a, "track_number").total_cmp(&at(b, "track_number"))) .then_with(|| text(a, "title").cmp(&text(b, "title"))) .then_with(|| text(a, "id").cmp(&text(b, "id"))) }); let mut names = BTreeSet::new(); for song in &folder.songs { let Some(key) = text(song, "file") else { continue }; let ext = extension(key).or_else(|| text(song, "format").map(str::to_string)).unwrap_or_else(|| "bin".into()); let title = component(text(song, "title"), "Untitled"); let track = number(song, "track_number").filter(|n| *n >= 1.0).map(|n| n as u32); let disc = number(song, "disc_number").filter(|n| *n >= 1.0).map(|n| n as u32).unwrap_or(1); let stem = match (track, folder.many_discs) { (Some(track), true) => format!("{disc}-{track:02} {title}"), (Some(track), false) => format!("{track:02} {title}"), (None, _) => title, }; let stem = unique(&mut names, &stem); let relative = format!("{path}/{stem}.{ext}"); if out.copy(key, &format!("Music/{relative}")) { landed.insert(text(song, "id").unwrap_or_default().to_string(), relative); } } if let Some(cover) = folder.cover { let name = format!("cover.{}", extension(cover).unwrap_or_else(|| "jpg".into())); out.copy(cover, &format!("Music/{path}/{name}")); } } write_playlists(out, &songs, &landed); write_listens(out, &songs, &albums_by_id, &artists_by_id)?; Ok(()) } /// One `.m3u8` per list of songs, in the list's order: a song whose file is /// not in the bundle is left out of it. fn write_playlists(out: &mut Out, songs: &[Row], landed: &BTreeMap) { let groups = out.rows(LISTS); let members = out.rows(LIST_MEMBERS); let songs_by_id = by_id(songs); let mut lists: Vec<&Row> = groups.iter().filter(|group| text(group, "table_id") == Some("song")).collect(); lists.sort_by(|a, b| { let position = |row: &Row| number(row, "position").unwrap_or(f64::MAX); position(a) .total_cmp(&position(b)) .then_with(|| text(a, "name").cmp(&text(b, "name"))) .then_with(|| text(a, "id").cmp(&text(b, "id"))) }); let mut names = BTreeSet::new(); for list in lists { let id = text(list, "id").unwrap_or_default(); let mut entries: Vec<&Row> = members.iter().filter(|member| text(member, "group") == Some(id)).collect(); entries.sort_by(|a, b| { let place = |row: &Row| number(row, "place").unwrap_or(f64::MAX); place(a).total_cmp(&place(b)).then_with(|| text(a, "id").cmp(&text(b, "id"))) }); let name = text(list, "name").unwrap_or("Playlist"); let mut body = format!("#EXTM3U\n#PLAYLIST:{}\n", one_line(name)); for entry in entries { let Some(song_id) = text(entry, "record_id") else { continue }; let (Some(song), Some(path)) = (songs_by_id.get(song_id), landed.get(song_id)) else { continue }; let seconds = number(song, "duration").map(|d| d.round() as i64).unwrap_or(-1); let shown = match (text(song, "artist_name"), text(song, "title")) { (Some(artist), Some(title)) => format!("{artist} - {title}"), (None, Some(title)) => title.to_string(), (_, None) => path.rsplit('/').next().unwrap_or_default().to_string(), }; body.push_str(&format!("#EXTINF:{seconds},{}\n../{path}\n", one_line(&shown))); } let file = unique(&mut names, &component(Some(name), "Playlist")); out.write(&format!("Music/playlists/{file}.m3u8"), body); } } /// A name on one line of a playlist. fn one_line(text: &str) -> String { text.replace(['\r', '\n'], " ") } /// Seconds since the epoch of an instant or a day as the kit stores one. fn unix_seconds(value: &str) -> Option { DateTime::parse_from_rfc3339(value) .map(|instant| instant.timestamp()) .ok() .or_else(|| NaiveDate::parse_from_str(value.get(..10)?, "%Y-%m-%d").ok()?.and_hms_opt(0, 0, 0).map(|at| at.and_utc().timestamp())) } /// The listens that count, oldest first, one ListenBrainz listen per line. fn write_listens( out: &mut Out, songs: &[Row], albums: &BTreeMap, artists: &BTreeMap, ) -> Result<()> { let listens = out.rows("listen"); let songs_by_id = by_id(songs); let mut counted: Vec<(i64, &str, JsonValue)> = Vec::new(); for listen in &listens { let song = text(listen, "song").and_then(|id| songs_by_id.get(id).copied()); let duration = song.and_then(|song| number(song, "duration")).filter(|d| *d > 0.0); let finished = text(listen, "ended") == Some("finished"); let seconds = number(listen, "seconds").unwrap_or(0.0); let enough = duration.map_or(SCROBBLE_SECONDS, |d| (d / 2.0).min(SCROBBLE_SECONDS)); if !finished && seconds < enough { continue; } let Some(at) = text(listen, "played_at").and_then(unix_seconds) else { continue }; let artist_name = text(listen, "artist_name").or_else(|| song.and_then(|song| text(song, "artist_name"))); let track_name = text(listen, "title").or_else(|| song.and_then(|song| text(song, "title"))); let (Some(artist_name), Some(track_name)) = (artist_name, track_name) else { continue }; let album = song.and_then(|song| text(song, "album")).and_then(|id| albums.get(id).copied()); let mut info = serde_json::Map::new(); if let Some(recording) = song.and_then(|song| text(song, "mb_recording")) { info.insert("recording_mbid".into(), json!(recording)); } if let Some(release) = album.and_then(|album| text(album, "mb_release")) { info.insert("release_mbid".into(), json!(release)); } if let Some(artist) = song.and_then(|song| text(song, "artist")).and_then(|id| artists.get(id)).and_then(|a| text(a, "mb_artist")) { info.insert("artist_mbids".into(), json!([artist])); } if let Some(isrc) = song.and_then(|song| text(song, "isrc")) { info.insert("isrc".into(), json!(isrc)); } if let Some(duration) = duration { info.insert("duration_ms".into(), json!((duration * 1000.0).round() as i64)); } info.insert("media_player".into(), json!("Cotton")); info.insert("submission_client".into(), json!("Cotton")); let mut metadata = serde_json::Map::new(); metadata.insert("artist_name".into(), json!(artist_name)); metadata.insert("track_name".into(), json!(track_name)); if let Some(release) = album.and_then(|album| text(album, "title")).or_else(|| song.and_then(|song| text(song, "album_title"))) { metadata.insert("release_name".into(), json!(release)); } metadata.insert("additional_info".into(), JsonValue::Object(info)); counted.push((at, text(listen, "id").unwrap_or_default(), json!({ "listened_at": at, "track_metadata": metadata }))); } counted.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1))); let mut body = String::new(); for (_, _, line) in counted { body.push_str(&serde_json::to_string(&line).map_err(|error| refuse(error.to_string()))?); body.push('\n'); } out.write("Music/listens.jsonl", body); Ok(()) }