Cotton code
250 lines · 11.3 KB · RustRaw
//! What a phone's song intake asks before and after `music.capture` (Cotton//! Music on Android, 12 Nov 2026): the rules iOS's `MusicIntake` keeps in//! Swift, answered by the core so a platform shell only reads files and//! hands them over.//!//! - `music.picked { paths }` → `{ songs: [{ path, lyrics?, cover? }],//!   lists: [path], stage: [path] }`: of every file picked (Add files, by its//!   own name) or under a picked folder (Add a folder, by its path from the//!   folder's name), which are songs (`SONG_EXTENSIONS`), each song's timed//!   lyrics beside it (`<stem>.lrc` in its folder) and its folder's cover//!   ([`COVER_NAMES`] in their order, then `jpg`, `jpeg`, `png`), which are//!   playlists (`.m3u`, `.m3u8`, handed to `music.lists` after the songs),//!   and which files a phone stages to read beside them (the lyrics, the//!   covers and the lists), and no others.//! - `music.gathered { songs: [{ sourcePath, tags, lrc? }] }` → `{ batches://!   [[index]], tags: [tags] }`: the songs read, gathered into the writes//!   `music.capture` takes, one album's songs at a time (its album artist and//!   album, as near as the tags and its folders say, [`MOST_IN_ONE`] at most//!   in one), in the order the albums were first met; and each song's tags as//!   they go in: a lyrics tag written as LRC is its timed lyrics, and an//!   `.lrc` beside it (`lrc`, its text) is its timed lyrics where the tags//!   carry none and most of its lines are timed (`lyricsBeside`).//! - `music.landed { answers, albums }` → `{ said?, landing? }`: what a whole//!   intake came to, from every `music.capture` answer it had: the song the//!   deck then stands on (the last that came in, else the last already//!   here) and what is said — the songs counted (`intake.added_many`) when//!   more than one album or more than one write came in and any song was//!   added, else the last capture's own words.use std::collections::BTreeSet;use serde::Deserialize;use serde_json::{json, Map, Value};use cotton_core::media::keys::SONG_EXTENSIONS;use cotton_core::music::m3u::is_list_file;use cotton_core::music::{fold, Tags, VARIOUS_ARTISTS};use super::songs::{line, MOST_IN_ONE};use crate::methods::MethodError;pub const METHODS: [&str; 3] = ["music.picked", "music.gathered", "music.landed"];/// The names a folder's cover goes by, in the order they are looked for.pub const COVER_NAMES: [&str; 5] = ["cover", "folder", "front", "album", "albumart"];/// The picture kinds a folder's cover is, in the order they are looked for.pub const COVER_EXTENSIONS: [&str; 3] = ["jpg", "jpeg", "png"];/// The most an `.lrc` beside a song is read to: a song's timed lyrics run to/// a few kilobytes; a file past this under that name is left unread.pub const MOST_LRC_BYTES: usize = 256 * 1024;fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why.to_string())}pub fn call(method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "music.picked" => picked(request),        "music.gathered" => gathered(request),        "music.landed" => landed(request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a music intake method"))),    }}fn folder_of(path: &str) -> &str {    path.rsplit_once('/').map_or("", |(folder, _)| folder)}fn name_of(path: &str) -> &str {    path.rsplit('/').next().unwrap_or(path)}/// A name's stem and its extension, lower-cased.fn split_name(name: &str) -> (&str, Option<String>) {    match name.rsplit_once('.') {        Some((stem, ext)) if !stem.is_empty() => (stem, Some(ext.to_lowercase())),        _ => (name, None),    }}fn is_song(path: &str) -> bool {    split_name(name_of(path)).1.is_some_and(|ext| SONG_EXTENSIONS.contains(&ext.as_str()))}/// `music.picked { paths }`.fn picked(request: &Value) -> Result<Value, MethodError> {    let paths: Vec<&str> = request        .get("paths")        .and_then(Value::as_array)        .ok_or_else(|| bad("music.picked takes { paths: [path] }"))?        .iter()        .map(|path| path.as_str().ok_or_else(|| bad("music.picked takes { paths: [path] }")))        .collect::<Result<_, _>>()?;    let held: BTreeSet<&str> = paths.iter().copied().collect();    // A folder's cover, by the names it goes by in their order, any case.    let cover_of = |folder: &str| -> Option<String> {        let mut found: Vec<(usize, usize, &str)> = paths            .iter()            .filter(|path| folder_of(path) == folder)            .filter_map(|path| {                let (stem, ext) = split_name(name_of(path));                let ext = ext?;                let name = COVER_NAMES.iter().position(|name| stem.eq_ignore_ascii_case(name))?;                let kind = COVER_EXTENSIONS.iter().position(|kind| *kind == ext)?;                Some((name, kind, *path))            })            .collect();        found.sort();        found.first().map(|(_, _, path)| path.to_string())    };    let mut stage = BTreeSet::new();    let mut songs = Vec::new();    for path in paths.iter().filter(|path| is_song(path)) {        let folder = folder_of(path);        let (stem, _) = split_name(name_of(path));        let beside = if folder.is_empty() { format!("{stem}.lrc") } else { format!("{folder}/{stem}.lrc") };        let lyrics = held.contains(beside.as_str()).then_some(beside);        let cover = cover_of(folder);        let mut song = Map::new();        song.insert("path".into(), json!(path));        if let Some(lyrics) = &lyrics {            stage.insert(lyrics.clone());            song.insert("lyrics".into(), json!(lyrics));        }        if let Some(cover) = &cover {            stage.insert(cover.clone());            song.insert("cover".into(), json!(cover));        }        songs.push(Value::Object(song));    }    let lists: Vec<&str> = paths.iter().copied().filter(|path| is_list_file(path)).collect();    stage.extend(lists.iter().map(|path| path.to_string()));    Ok(json!({ "songs": songs, "lists": lists, "stage": stage.into_iter().collect::<Vec<_>>() }))}#[derive(Debug, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]struct ReadSong {    source_path: String,    #[serde(default)]    tags: Tags,    /// The text of the `.lrc` beside it, as the phone read it.    #[serde(default)]    lrc: Option<String>,}#[derive(Debug, Deserialize)]#[serde(deny_unknown_fields)]struct GatheredIn {    songs: Vec<ReadSong>,}/// Whether most of the text's lines carry a time mark (`[mm:ss.xx]`).pub fn looks_timed(text: &str) -> bool {    let lines: Vec<&str> = text.lines().map(str::trim).filter(|line| !line.is_empty()).collect();    if lines.is_empty() {        return false;    }    let timed = lines.iter().filter(|line| timed_line(line)).count();    timed * 2 > lines.len()}/// `[m:ss]`, `[mmm:ss.x]`, `[mm:ss:xxx]` at the line's start.fn timed_line(line: &str) -> bool {    let Some(rest) = line.strip_prefix('[') else { return false };    let Some((mark, _)) = rest.split_once(']') else { return false };    let Some((minutes, seconds)) = mark.split_once(':') else { return false };    let digits = |text: &str, least: usize, most: usize| (least..=most).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit());    if !digits(minutes, 1, 3) {        return false;    }    let (whole, part) = match seconds.find(['.', ':']) {        Some(at) => (&seconds[..at], Some(&seconds[at + 1..])),        None => (seconds, None),    };    digits(whole, 2, 2) && part.is_none_or(|part| digits(part, 1, 3))}/// The tags as they go in: LRC in the lyrics tag is timed lyrics; an `.lrc`/// beside fills timed lyrics the tags left empty.fn as_they_go(song: &ReadSong) -> Tags {    let mut tags = song.tags.clone();    if tags.synced_lyrics.is_none() && tags.lyrics.as_deref().is_some_and(looks_timed) {        tags.synced_lyrics = tags.lyrics.take();    }    if tags.synced_lyrics.is_none() {        if let Some(lrc) = song.lrc.as_deref().filter(|lrc| lrc.len() <= MOST_LRC_BYTES && looks_timed(lrc)) {            tags.synced_lyrics = Some(lrc.to_string());            tags.lyrics_beside = Some(true);        }    }    tags}/// Which write a song goes in: its album artist and album, as near as the/// tags and its folders say. The core keys the album itself in the capture;/// this only keeps an album's songs together.pub fn gathering_key(tags: &Tags, source_path: &str) -> String {    let folders: Vec<&str> = source_path.split('/').filter(|part| !part.is_empty()).collect();    let folders = &folders[..folders.len().saturating_sub(1)];    let words = |text: &Option<String>| text.as_deref().map(str::trim).filter(|text| !text.is_empty()).map(str::to_string);    let album = words(&tags.album).or_else(|| folders.last().map(|folder| folder.to_string())).unwrap_or_default();    let artist = words(&tags.album_artist)        .or_else(|| (tags.compilation == Some(true)).then(|| VARIOUS_ARTISTS.to_string()))        .or_else(|| words(&tags.artist))        .or_else(|| folders.len().checked_sub(2).map(|at| folders[at].to_string()))        .unwrap_or_default();    format!("{}\u{1f}{}", fold(&artist), fold(&album))}/// `music.gathered { songs }`.fn gathered(request: &Value) -> Result<Value, MethodError> {    let asked: GatheredIn = serde_json::from_value(request.clone()).map_err(|error| bad(&format!("music.gathered takes {{ songs: [{{ sourcePath, tags, lrc? }}] }}: {error}")))?;    let mut order: Vec<String> = Vec::new();    let mut albums: std::collections::HashMap<String, Vec<usize>> = std::collections::HashMap::new();    for (at, song) in asked.songs.iter().enumerate() {        let key = gathering_key(&song.tags, &song.source_path);        if !albums.contains_key(&key) {            order.push(key.clone());        }        albums.entry(key).or_default().push(at);    }    let batches: Vec<Vec<usize>> = order.iter().flat_map(|key| albums[key].chunks(MOST_IN_ONE).map(<[usize]>::to_vec).collect::<Vec<_>>()).collect();    let tags: Vec<Tags> = asked.songs.iter().map(as_they_go).collect();    Ok(json!({ "batches": batches, "tags": tags }))}/// `music.landed { answers, albums }`.fn landed(request: &Value) -> Result<Value, MethodError> {    let answers = request.get("answers").and_then(Value::as_array).ok_or_else(|| bad("music.landed takes { answers: [music.capture's answer], albums }"))?;    let albums = request.get("albums").and_then(Value::as_u64).ok_or_else(|| bad("music.landed takes the count of albums gathered (albums)"))?;    let songs: Vec<&Value> = answers.iter().flat_map(|answer| answer["songs"].as_array().into_iter().flatten()).collect();    let outcome = |song: &&Value, kinds: &[&str]| song["outcome"].as_str().is_some_and(|outcome| kinds.contains(&outcome));    let landing = songs        .iter()        .rev()        .find(|song| outcome(song, &["added", "better"]))        .or_else(|| songs.iter().rev().find(|song| outcome(song, &["here", "worse"])))        .and_then(|song| song["id"].as_str());    let added = songs.iter().filter(|song| outcome(song, &["added"])).count();    let own = answers.iter().rev().find_map(|answer| answer["said"].as_str().filter(|said| !said.is_empty()));    let said = if (albums > 1 || answers.len() > 1) && added > 0 { Some(line("intake.added_many", &[("count", &added.to_string())])?) } else { own.map(str::to_string) };    Ok(json!({ "said": said, "landing": landing }))}#[cfg(test)]#[path = "song_intake_tests.rs"]mod tests;