Cotton code
236 lines · 9.4 KB · RustRaw
//! A folder's songs, as the phone's `MusicIntake` finds them//! (`apps/cotton/Sources/CottonKit/Music/MusicIntake.swift`): every song file//! under it, deepest too, hidden ones skipped, each named by its path under//! the folder's own name and the one above it (`Artist/Album (Year)/01//! Title.flac`, whichever of the two was given), in the Finder's order; a//! `.lrc` beside a file and its folder's cover read too.use std::cmp::Ordering;use std::path::{Path, PathBuf};use super::read::{looks_timed, read_song};use cotton_core::music::m3u::is_list_file;use cotton_core::music::Tags;/// The extensions a song file ends in, as the intake picks them out of a folder.pub const SONG_FILE_EXTENSIONS: [&str; 9] = ["mp3", "m4a", "flac", "ogg", "oga", "opus", "wav", "aif", "aiff"];/// The names a folder's cover goes by, in the order they are looked for.pub const FOLDER_COVER_NAMES: [&str; 8] = ["cover", "folder", "front", "album", "Cover", "Folder", "Front", "AlbumArt"];pub const FOLDER_COVER_EXTENSIONS: [&str; 3] = ["jpg", "jpeg", "png"];/// One song file found: where it is, and the path it came in as.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Found {    pub path: PathBuf,    pub source_path: String,}/// Where an album's picture comes from, read only when an album wants one.#[derive(Debug, Clone, PartialEq, Eq)]pub enum CoverFrom {    /// The song file's own picture.    Embedded(PathBuf),    /// A cover file in its folder.    Folder(PathBuf),}/// One file read, as the phone hands it to `music.capture`.#[derive(Debug, Clone, PartialEq)]pub struct SongIn {    pub path: PathBuf,    pub source_path: String,    pub tags: Tags,    pub cover: Option<CoverFrom>,}/// A given folder's name as the intake reads it: the folder above it and its/// own (`Artist/Album (Year)`), so the path facts read the artist whether the/// artist's folder or one album's was given.pub fn picked_name(folder: &Path) -> String {    let own = folder.file_name().map(|name| name.to_string_lossy().to_string()).unwrap_or_default();    let above = folder.parent().and_then(Path::file_name).map(|name| name.to_string_lossy().to_string()).unwrap_or_default();    if above.is_empty() {        own    } else {        format!("{above}/{own}")    }}fn hidden(name: &std::ffi::OsStr) -> bool {    name.to_string_lossy().starts_with('.')}/// Whether a file's name is a song's.pub fn is_song_file(path: &Path) -> bool {    path.extension()        .and_then(|ext| ext.to_str())        .is_some_and(|ext| SONG_FILE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))}/// Every song file under `folder`, hidden files and folders skipped, a/// linked folder not followed (a link back up would never end), sorted as/// the Finder sorts names.pub fn songs_in(folder: &Path) -> std::io::Result<Vec<Found>> {    files_in(folder, is_song_file)}/// Every playlist file (`.m3u`, `.m3u8`) under `folder`, walked as its songs/// are, each named by its path as theirs are.pub fn lists_in(folder: &Path) -> std::io::Result<Vec<Found>> {    files_in(folder, |path| is_list_file(&path.to_string_lossy()))}fn files_in(folder: &Path, wanted: fn(&Path) -> bool) -> std::io::Result<Vec<Found>> {    let name = picked_name(folder);    let mut found = Vec::new();    let mut pending = vec![folder.to_path_buf()];    while let Some(dir) = pending.pop() {        for entry in std::fs::read_dir(&dir)? {            let entry = entry?;            if hidden(&entry.file_name()) {                continue;            }            let path = entry.path();            let kind = entry.file_type()?;            if kind.is_dir() {                pending.push(path);                continue;            }            // A linked file is read through its link; a linked folder is not walked.            let is_file = kind.is_file() || (kind.is_symlink() && std::fs::metadata(&path).is_ok_and(|meta| meta.is_file()));            if !is_file || !wanted(&path) {                continue;            }            let below = path.strip_prefix(folder).unwrap_or(&path).to_string_lossy().replace('\\', "/");            let source_path = [name.as_str(), below.as_str()]                .iter()                .map(|part| part.trim_matches('/'))                .filter(|part| !part.is_empty())                .collect::<Vec<_>>()                .join("/");            found.push(Found { path, source_path });        }    }    found.sort_by(|a, b| natural_cmp(&a.source_path, &b.source_path));    Ok(found)}/// Names compared as the Finder does: case aside, runs of digits by their value.pub fn natural_cmp(a: &str, b: &str) -> Ordering {    let mut a = a.chars().peekable();    let mut b = b.chars().peekable();    loop {        match (a.peek().copied(), b.peek().copied()) {            (None, None) => return Ordering::Equal,            (None, Some(_)) => return Ordering::Less,            (Some(_), None) => return Ordering::Greater,            (Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {                let take = |chars: &mut std::iter::Peekable<std::str::Chars<'_>>| {                    let mut digits = String::new();                    while let Some(c) = chars.peek().copied().filter(char::is_ascii_digit) {                        digits.push(c);                        chars.next();                    }                    digits                };                let (x, y) = (take(&mut a), take(&mut b));                let (xs, ys) = (x.trim_start_matches('0'), y.trim_start_matches('0'));                let order = xs.len().cmp(&ys.len()).then_with(|| xs.cmp(ys));                if order != Ordering::Equal {                    return order;                }            }            (Some(x), Some(y)) => {                let order = x.to_lowercase().cmp(y.to_lowercase());                if order != Ordering::Equal {                    return order;                }                a.next();                b.next();            }        }    }}/// The cover file in `folder`, by the names a cover goes by.pub fn folder_cover(folder: &Path) -> Option<PathBuf> {    FOLDER_COVER_NAMES        .iter()        .flat_map(|name| FOLDER_COVER_EXTENSIONS.iter().map(move |ext| folder.join(format!("{name}.{ext}"))))        .find(|path| path.is_file())}/// One file read: its tags, a `.lrc` beside it, its folder's cover.pub fn read(found: &Found) -> SongIn {    let read = read_song(&found.path);    let embedded = read.as_ref().is_some_and(|read| read.embedded_cover);    let mut tags = read.map(|read| read.tags).unwrap_or_default();    if tags.synced_lyrics.is_none() {        let beside = found.path.with_extension("lrc");        if let Ok(lrc) = std::fs::read_to_string(&beside) {            if looks_timed(&lrc) {                tags.synced_lyrics = Some(lrc);                tags.lyrics_beside = Some(true);            }        }    }    let cover = if embedded {        Some(CoverFrom::Embedded(found.path.clone()))    } else {        found.path.parent().and_then(folder_cover).map(CoverFrom::Folder)    };    SongIn { path: found.path.clone(), source_path: found.source_path.clone(), tags, cover }}/// Which write a song goes in: its album artist and album, as near as the/// tags and its folders say (the phone's `MusicIntake.albumKey`). The core/// keys the album itself; this only keeps an album's songs together.pub fn batch_key(tags: &Tags, source_path: &str) -> String {    let parts: Vec<&str> = source_path.split('/').filter(|part| !part.is_empty()).collect();    let folders = &parts[..parts.len().saturating_sub(1)];    let album = tags.album.clone().or(folders.last().map(|f| f.to_string())).unwrap_or_default();    let artist = tags        .album_artist        .clone()        .or_else(|| (tags.compilation == Some(true)).then(|| "various_artists".to_string()))        .or(tags.artist.clone())        .or(folders.len().checked_sub(2).map(|at| folders[at].to_string()))        .unwrap_or_default();    format!("{}\u{1f}{}", artist.to_lowercase(), album.to_lowercase())}/// Songs gathered by album, in the order their albums were first met.pub fn by_album(songs: Vec<SongIn>) -> Vec<Vec<SongIn>> {    let mut order: Vec<String> = Vec::new();    let mut albums: std::collections::HashMap<String, Vec<SongIn>> = std::collections::HashMap::new();    for song in songs {        let key = batch_key(&song.tags, &song.source_path);        if !albums.contains_key(&key) {            order.push(key.clone());        }        albums.entry(key).or_default().push(song);    }    order.into_iter().filter_map(|key| albums.remove(&key)).collect()}#[cfg(test)]mod tests {    use super::*;    #[test]    fn names_sort_as_the_finder_sorts_them() {        let mut names = vec!["b/10 x", "b/2 x", "B/1 x", "a/01 x"];        names.sort_by(|a, b| natural_cmp(a, b));        assert_eq!(names, vec!["a/01 x", "B/1 x", "b/2 x", "b/10 x"]);    }    #[test]    fn an_albums_songs_go_together() {        let tags = |album: Option<&str>, artist: Option<&str>| Tags { album: album.map(str::to_string), artist: artist.map(str::to_string), ..Tags::default() };        assert_eq!(batch_key(&tags(None, None), "Music/Ana/Blue (2001)/01 One.flac"), "ana\u{1f}blue (2001)");        assert_eq!(batch_key(&tags(Some("Blue"), Some("Ana")), "x.mp3"), "ana\u{1f}blue");        let compiled = Tags { album: Some("Hits".into()), artist: Some("Ana".into()), compilation: Some(true), ..Tags::default() };        assert_eq!(batch_key(&compiled, "x.mp3"), "various_artists\u{1f}hits");    }}