//! Songs on this phone: the music kit's intake, what this device alone keeps //! of each song's file, and the player's door (Music definition, 4 Nov 2026). //! //! - `music.capture { songs: [{ path, sourcePath, tags, coverPath? }] }` → //! `{ songs: [{ sourcePath, outcome, id?, title, line }], said }`: the songs //! of ONE album as the phone read them (TagLib, off the main thread), made //! in one write: each file into the content-addressed store under its song //! key (`/music/.`) and queued up as `Song` media, its //! album (keyed on album artist and title) and artists found or made, its //! row made from `cotton_core::music::song_from` (tags first, the path for //! what they left). `outcome` is `added`, `here` (the same bytes are a song //! already), `better` (the same song in a worse file was here: this file //! takes its place, and the line says the other can go), `worse` (the same //! song is here in a better file: this one is not kept) or `refused` (not a //! song's file). A file brought in here is on this phone: it is `kept`, //! whether it made a song or its bytes were one already (`here`). //! - `music.capture { songs: [{ …, entry }], zip }` and `music.zip { path, //! name, into }`: an album ZIP, one album (`phone::songs_zip`). //! - `music.lists { lists: [{ sourcePath, text }] }` → `{ lists: [{ //! sourcePath, name, id, made, appended, skipped }] }`: the playlist files //! (`.m3u`, `.m3u8`) Add a folder found, after its songs came in, each a //! list of songs by `cotton_core::music::m3u` as the Mac's `music:import` //! makes it: named after its file, each entry found by its path relative to //! the list then by its file name among the songs held (by `path`), the //! rest skipped and counted; a list held by that name only grows. //! - `songs.here.read { key }`, `songs.here.write { key, state, from? }`, //! `songs.remove { key }`: as `books.here.*` and `books.remove`, for a //! song's file. //! - `songs.keepEverything { on? }` → `{ on }`: this phone's Keep everything, //! read without `on`, set with it. A fact of this phone alone. //! - `songs.keepPlan { op: keep|remove|sweep, table?, id? }` → `{ keys }`: //! the song files a keep, a Remove download or Keep everything's sweep //! touches on this phone (iOS's SongKeeper's rule, for any shell). //! - The player is `shell.player` (`shell_player`): the queue, the listen //! and the settings row. //! - `music.findDetails { table, id }` → `{ platform_action: "find_details", //! table, id }`: an album's lookups, run by the phone (MusicBrainz, then the //! object's `fetch_cover`, then iTunes), each filling only what is empty. //! //! - `music.fill { table, id, from, fields, coverPath? }` → `{ filled }`: what //! a lookup found for a song or an album (`from`: `musicbrainz`, `itunes`), //! written only where the column is empty, each column filled stamped in //! `filled_from` (`{ : }`, as the object stamps its own); a cover the phone fetched //! is kept as a picture and fills an empty `cover`. Only the columns a //! lookup may fill are taken ([`FILLABLE`]). //! //! WHAT IS KEPT HERE NEVER SYNCS: `songs-here.json` beside the client's other //! device-local files: `{ "keep_everything": bool, "songs": { : "keeping" //! | "kept" } }`. A song's record answers it in `on_phone`, and an album's //! from its songs (`absent`, `some`, `keeping`, `kept`). use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::{Mutex, MutexGuard}; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use cotton_client::layout::Layout; use cotton_client::media::storage::EvictOneError; use cotton_client::media::store::put_media_file; use cotton_core::media::keys::{song_content_type, song_key, SONG_EXTENSIONS}; use cotton_core::music::{album_fields, album_key, better, fold, same_song, song_from, song_row, sort_name_of, SongFacts, Tags, ALBUM_FIELDS}; use cotton_core::rules::shell_lines::LineSet; use cotton_store::media_holdings::Tier as HoldTier; use cotton_store::media_ledger::{enqueue_media, MediaEnqueueInput}; use cotton_tools::mcp::dispatch::Ctx; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::io_trouble::io_refusal; use crate::shell::client::ClientController; pub const METHODS: [&str; 10] = ["music.capture", "music.zip", "music.lists", "music.fill", "songs.here.read", "songs.here.write", "songs.remove", "songs.keepEverything", "music.findDetails", "songs.keepPlan"]; /// The device-local file, in the client's own folder. pub const FILE: &str = "songs-here.json"; pub const SONG_TABLE: &str = "song"; pub const ALBUM_TABLE: &str = "music_album"; pub const ARTIST_TABLE: &str = "artist"; pub const FILE_COLUMN: &str = "file"; pub use super::films::{KEEPING, KEPT, ON_PHONE}; pub const ABSENT: &str = "absent"; /// An album some of whose songs are kept here and some not. pub const SOME: &str = "some"; /// The flows a song's and an album's acts open (`song.json`, `music_album.json`). pub const FLOWS: [&str; 4] = ["keepSong", "removeSongDownload", "keepAlbum", "removeAlbumDownload"]; /// What a list matches when this device keeps nothing. pub const NOTHING_KEPT: &str = "nothing-kept"; /// The most songs one capture takes: one album, a box set's worth. pub const MOST_IN_ONE: usize = 400; fn flow_holds(flow: &str) -> (&'static str, &'static [&'static str]) { match flow { "keepSong" => (SONG_TABLE, &[ABSENT]), "removeSongDownload" => (SONG_TABLE, &[KEEPING, KEPT]), "keepAlbum" => (ALBUM_TABLE, &[ABSENT, SOME]), "removeAlbumDownload" => (ALBUM_TABLE, &[SOME, KEEPING, KEPT]), _ => ("", &[]), } } /// A song's or an album's flow comes only from its own record, and only while /// what this device keeps of it says the act is there to take. pub(crate) fn flow_origin(client: &ClientController, flow: &str, table: &str, id: &str) -> Result<(), MethodError> { let (from, holds) = flow_holds(flow); if table != from { return Err(MethodError::new("bad_request", "this flow comes only from its own song's or album's record")); } let record = crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id}))?; let on_phone = record["data"][ON_PHONE].as_str().unwrap_or_default(); if !holds.contains(&on_phone) { return Err(MethodError::new("flow_refused", "this is not one this act is for just now")); } Ok(()) } static WRITE_LOCK: Mutex<()> = Mutex::new(()); #[derive(Debug, Clone, Default, Serialize, Deserialize)] struct Stored { #[serde(default)] keep_everything: bool, #[serde(default)] songs: BTreeMap, } pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { let client = handle.client(); match method { "music.capture" => capture(&client, request), "music.zip" => super::songs_zip::open(&client, request), "music.lists" => lists(&client, request), "music.fill" => fill(&client, request), "songs.here.read" => read(&client, request), "songs.here.write" => write(&client, request), "songs.remove" => remove(&client, request), "songs.keepEverything" => keep_everything(&client, request), "music.findDetails" => find_details(&client, request), "songs.keepPlan" => keep_plan(&client, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a music method"))), } } fn bad(why: &str) -> MethodError { MethodError::new("bad_request", why.to_string()) } /// A line of the music set, filled. pub(crate) fn line(name: &str, fills: &[(&str, &str)]) -> Result { LineSet::shipped("music") .and_then(|lines| lines.say(name, fills)) .ok_or_else(|| MethodError::new("unreadable", format!("the music set says no line {name}"))) } // ── music.capture ─────────────────────────────────────────────────────────── /// One file of a capture, as the phone read it. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SongIn { /// Where the bytes are now: a staged copy the phone owns. pub path: PathBuf, /// The path it came in as (`Artist/Album (Year)/01 Title.flac` from a /// folder, the file's own name from the share sheet). pub source_path: String, #[serde(default)] pub tags: Tags, /// The album's picture: the file's embedded one, else the folder's. #[serde(default)] pub cover_path: Option, /// The ZIP entry it came out of, when a ZIP brought it (`music.zip`). #[serde(default)] pub entry: Option, } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] struct CaptureIn { songs: Vec, /// The album ZIP the songs came out of: one album, its shop and booklet. #[serde(default)] zip: Option, } /// The extension a song key ends in, from the file's own. fn key_ext(source_path: &str) -> Option<&'static str> { let ext = Path::new(source_path).extension()?.to_str()?.to_ascii_lowercase(); let ext = match ext.as_str() { "aif" | "aifc" => "aiff", "wave" => "wav", "oga" => "ogg", other => other, }; SONG_EXTENSIONS.iter().copied().find(|known| *known == ext) } fn capture(client: &ClientController, request: &Value) -> Result { let asked: CaptureIn = serde_json::from_value(request.clone()).map_err(|error| bad(&format!("music.capture takes {{ songs: [{{ path, sourcePath, tags, coverPath?, entry? }}], zip? }}: {error}")))?; if asked.songs.is_empty() || asked.songs.len() > MOST_IN_ONE { return Err(bad("music.capture takes one album's songs at a time")); } let zone = client .time_zone() .map(str::to_string) .ok_or_else(|| bad("this phone named no time zone, so a song's day added cannot be said"))?; let layout = client.layout().clone(); let answer = client .write_rows("music.capture", &mut |ctx| match &asked.zip { Some(zip) => super::songs_zip::write_zip_album(ctx, &layout, &asked.songs, &zone, zip), None => write_songs(ctx, &layout, &asked.songs, &zone), }) .map_err(|reason| MethodError::new("capture_refused", reason))?; let answer = crate::authoring::own_answer(answer); // Brought in here, so on this phone: kept, its ledger row pinned. A file // already a song is brought in too: its bytes are here now. let kept: Vec = answer["songs"] .as_array() .into_iter() .flatten() .filter(|song| matches!(song["outcome"].as_str(), Some("added" | "better" | "here"))) .filter_map(|song| song["key"].as_str().map(str::to_string)) .collect(); if !kept.is_empty() { let now = iso_now(client)?; let workspace = client .with_writer(|f| { for key in &kept { cotton_store::media_ledger::set_media_pinned(f.driver, key, true, &now).map_err(|error| error.to_string())?; } Ok(f.workspace_id.to_string()) }) .map_err(|reason| MethodError::new("unwritable", reason))?; { let _guard = write_lock(); let mut all = stored(client)?; for key in &kept { all.songs.insert(key.clone(), KEPT.to_string()); } write_locked(client, &all)?; } client.emit_data(&workspace, vec!["_media".into(), format!("cotton_{SONG_TABLE}"), format!("cotton_{ALBUM_TABLE}")], "local"); } Ok(answer) } // ── music.lists ───────────────────────────────────────────────────────────── /// One playlist file Add a folder found: its path as it came in, beside its /// songs' own, and its text. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ListIn { source_path: String, text: String, } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] struct ListsIn { lists: Vec, } fn lists(client: &ClientController, request: &Value) -> Result { let asked: ListsIn = serde_json::from_value(request.clone()).map_err(|error| bad(&format!("music.lists takes {{ lists: [{{ sourcePath, text }}] }}: {error}")))?; if asked.lists.is_empty() { return Err(bad("music.lists takes the playlist files a folder held")); } let answer = client .write_rows("music.lists", &mut |ctx| write_lists(ctx, &asked.lists)) .map_err(|reason| MethodError::new("lists_refused", reason))?; Ok(crate::authoring::own_answer(answer)) } fn write_lists(ctx: &mut Ctx<'_>, files: &[ListIn]) -> Result { use cotton_core::music::m3u; use cotton_tools::mcp::handlers::tables::groups; let object = |value: Value| value.as_object().cloned().unwrap_or_default(); let songs: Vec<(String, String)> = rows_where(ctx, SONG_TABLE, "id, path", "path IS NOT NULL AND path <> ''", &[])? .iter() .map(|row| (text_of(row, "path"), text_of(row, "id"))) .collect(); let mut answers = Vec::new(); for file in files { let name = m3u::list_name(&file.source_path); let resolved = m3u::resolve(&file.source_path, &m3u::entries(&file.text), &songs); let held = groups::list_groups(ctx, &object(json!({ "table": SONG_TABLE }))).map_err(|failure| failure.to_string())?; let held = held["groups"].as_array().into_iter().flatten().find(|group| group["name"].as_str().is_some_and(|held| fold(held) == fold(&name))).and_then(|group| group["id"].as_str()).map(str::to_string); let (id, made, appended) = match held { Some(id) => { let members = groups::member_order(ctx, &id).map_err(|failure| failure.to_string())?; let appended = m3u::to_append(&members, &resolved.songs); if !appended.is_empty() { groups::update_group(ctx, &object(json!({ "id": id, "add": appended }))).map_err(|failure| failure.to_string())?; } (id, false, appended.len()) } None => { let written = groups::create_group(ctx, &object(json!({ "table": SONG_TABLE, "name": name, "records": resolved.songs }))).map_err(|failure| failure.to_string())?; let id = written.pointer("/group/id").and_then(Value::as_str).map(str::to_string).ok_or("the list was made and named no id")?; (id, true, resolved.songs.len()) } }; answers.push(json!({ "sourcePath": file.source_path, "name": name, "id": id, "made": made, "appended": appended, "skipped": resolved.skipped })); } Ok(json!({ "lists": answers })) } /// The columns a lookup may fill, by table: never a title, an artist, a file /// or anything the person typed over. pub const FILLABLE: [(&str, &[&str]); 2] = [ (SONG_TABLE, &["year", "genre", "composer", "isrc", "mb_recording", "mb_release_track", "lyrics", "synced_lyrics", "lyrics_source"]), (ALBUM_TABLE, &["year", "mb_release", "mb_release_group", "cover", "original_year", "release_type", "label", "catalog_number", "barcode"]), ]; /// The sources a fill names. pub const FILLED_FROM: [&str; 3] = ["musicbrainz", "itunes", "lrclib"]; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct FillIn { table: String, id: String, from: String, #[serde(default)] fields: Map, #[serde(default)] cover_path: Option, } fn fill(client: &ClientController, request: &Value) -> Result { let asked: FillIn = serde_json::from_value(request.clone()).map_err(|error| bad(&format!("music.fill takes {{ table, id, from, fields, coverPath? }}: {error}")))?; let Some((_, fillable)) = FILLABLE.iter().find(|(table, _)| *table == asked.table) else { return Err(bad("music.fill fills a song or an album")); }; if !FILLED_FROM.contains(&asked.from.as_str()) { return Err(bad("music.fill names where it found what it fills")); } if let Some(key) = asked.fields.keys().find(|key| !fillable.contains(&key.as_str()) || key.as_str() == "cover") { return Err(bad(&format!("a lookup does not fill `{key}`"))); } if asked.cover_path.is_some() && !fillable.contains(&"cover") { return Err(bad("only an album takes a cover")); } let layout = client.layout().clone(); let now = iso_now(client)?; let answer = client .write_rows("music.fill", &mut |ctx| { let columns = format!("id, filled_from, {}", fillable.join(", ")); let Some(row) = rows_where(ctx, &asked.table, &columns, "id = ?", &[rusqlite::types::Value::Text(asked.id.clone())])?.into_iter().next() else { return Err(format!("no {} is {}", asked.table, asked.id)); }; let empty = |key: &str| row.get(key).is_none_or(|value| value.is_null() || value.as_str().is_some_and(|text| text.trim().is_empty())); let mut patch = Map::new(); for (key, value) in &asked.fields { let given = !(value.is_null() || value.as_str().is_some_and(|text| text.trim().is_empty())); if given && empty(key) { patch.insert(key.clone(), value.clone()); } } if let Some(path) = asked.cover_path.as_deref().filter(|_| empty("cover")) { let workspace_id = ctx.workspace_id.to_string(); let cover = super::media::keep_picture(ctx, &layout, &workspace_id, Path::new(path), &now, "an album's cover")?; patch.insert("cover".into(), Value::from(cover)); } let filled: Vec = patch.keys().cloned().collect(); if !filled.is_empty() { let mut stamps = row .get("filled_from") .and_then(Value::as_str) .and_then(|text| serde_json::from_str::>(text).ok()) .unwrap_or_default(); for key in &filled { stamps.insert(key.clone(), Value::from(asked.from.clone())); } patch.insert("filled_from".into(), Value::from(Value::Object(stamps).to_string())); patched(ctx, &asked.table, &asked.id, patch)?; } Ok(json!({ "filled": filled })) }) .map_err(|reason| MethodError::new("fill_refused", reason))?; Ok(crate::authoring::own_answer(answer)) } /// A live row of a made table, as its columns. pub(crate) type Row = Map; /// Whether this database holds `table`'s rows yet (a kit reaches it whole). pub(crate) fn holds_table(ctx: &Ctx<'_>, table: &str) -> Result { let made = cotton_tools::mcp::handlers::tables::made_table(table); Ok(ctx .db() .get("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(made)]) .map_err(|error| error.to_string())? .is_some()) } pub(crate) fn rows_where(ctx: &Ctx<'_>, table: &str, columns: &str, condition: &str, args: &[rusqlite::types::Value]) -> Result, String> { if !holds_table(ctx, table)? { return Err(format!("this database holds no {table} table: the music kit has not reached this phone")); } let made = cotton_tools::mcp::handlers::tables::made_table(table); let mut all = vec![rusqlite::types::Value::Text(ctx.workspace_id.to_string())]; all.extend_from_slice(args); let found = ctx .db() .all(&format!("SELECT {columns} FROM {made} WHERE workspace_id = ? AND deleted_at IS NULL AND {condition}"), &all) .map_err(|error| error.to_string())?; Ok(found.iter().map(json_row).collect()) } /// A driver row as JSON: text, numbers and nulls as they are. pub(crate) fn json_row(row: &cotton_store::driver::Row) -> Row { use rusqlite::types::Value as Sql; row.columns() .iter() .map(|(name, value)| { let value = match value { Sql::Null | Sql::Blob(_) => Value::Null, Sql::Integer(n) => Value::from(*n), Sql::Real(x) => Value::from(*x), Sql::Text(text) => Value::from(text.clone()), }; (name.clone(), value) }) .collect() } pub(crate) fn text_of(row: &Row, key: &str) -> String { row.get(key).and_then(Value::as_str).unwrap_or_default().to_string() } pub(crate) fn made(ctx: &mut Ctx<'_>, table: &str, data: Map) -> Result { let args = json!({ "table": table, "data": Value::Object(data) }); let made = cotton_tools::mcp::handlers::tables::create_produced_record(ctx, args.as_object().expect("an object")).map_err(|failure| failure.to_string())?; made.pointer("/record/id").and_then(Value::as_str).map(str::to_string).ok_or_else(|| format!("the {table} was made and named no id")) } pub(crate) fn patched(ctx: &mut Ctx<'_>, table: &str, id: &str, patch: Map) -> Result<(), String> { if patch.is_empty() { return Ok(()); } let args = json!({ "table": table, "id": id, "patch": Value::Object(patch) }); cotton_tools::mcp::handlers::tables::update_produced_record(ctx, args.as_object().expect("an object")).map_err(|failure| failure.to_string())?; Ok(()) } pub(crate) fn put(data: &mut Map, key: &str, value: Option) { if let Some(value) = value { data.insert(key.to_string(), value); } } /// The artist named `name`, found by its folded name or made. fn artist_of(ctx: &mut Ctx<'_>, name: &str, mb_artist: Option<&str>, sort: Option<&str>, made_here: &mut BTreeMap) -> Result { let folded = fold(name); if let Some(id) = made_here.get(&folded) { return Ok(id.clone()); } let found = rows_where(ctx, ARTIST_TABLE, "id, name", "lower(trim(name)) = ?", &[rusqlite::types::Value::Text(folded.clone())])? .into_iter() .find(|row| fold(&text_of(row, "name")) == folded); let id = match found { Some(row) => text_of(&row, "id"), None => { let mut data = Map::new(); data.insert("name".into(), Value::from(name.trim())); data.insert("sort_name".into(), Value::from(sort_name_of(name, sort))); put(&mut data, "mb_artist", mb_artist.map(Value::from)); made(ctx, ARTIST_TABLE, data)? } }; made_here.insert(folded, id.clone()); Ok(id) } pub use cotton_core::music::primary_artist; /// Everything a capture writes, in one write: the album's rows and each song. pub fn write_songs(ctx: &mut Ctx<'_>, layout: &Layout, songs: &[SongIn], zone: &str) -> Result { let workspace_id = ctx.workspace_id.to_string(); let file_id = ctx.file.id().clone(); let now = cotton_tools::mcp::handlers::common::now_iso(ctx); let now_ms = cotton_tools::mcp::handlers::common::now_ms(ctx); let today = cotton_tools::mcp::handlers::common::today_in(zone, now_ms).map_err(|failure| failure.to_string())?; let mut artists = BTreeMap::new(); let mut albums: BTreeMap = BTreeMap::new(); let mut answers = Vec::new(); let say = |name: &str, fills: &[(&str, &str)]| line(name, fills).map_err(|failure| failure.message); for song in songs { let name = song.source_path.rsplit('/').next().unwrap_or(&song.source_path).to_string(); let Some(ext) = key_ext(&song.source_path) else { answers.push(json!({"sourcePath": song.source_path, "outcome": "refused", "title": name, "line": say("intake.refused", &[("name", &name)])?})); continue; }; let Some(facts) = song_from(&song.tags, &song.source_path, ext) else { answers.push(json!({"sourcePath": song.source_path, "outcome": "refused", "title": name, "line": say("intake.refused", &[("name", &name)])?})); continue; }; let content_type = song_content_type(ext).ok_or("a song extension carries its type")?; // 1. THE BYTES, content-addressed: the same file twice is one object. let stored = put_media_file(layout, &workspace_id, &song.path, ext) .map_err(|error| io_refusal("the song could not be copied into this device's store", &song.path, &error))?; let key = song_key(&file_id, &stored.sha256, ext); // 2. The same bytes are a song already: already here, and now on this // phone too (a song the object held, its file brought in again). if let Some(row) = rows_where(ctx, SONG_TABLE, "id, title", "file = ?", &[rusqlite::types::Value::Text(key.clone())])?.into_iter().next() { queue(ctx, &workspace_id, &key, &stored, content_type, &now)?; let title = text_of(&row, "title"); answers.push(json!({"sourcePath": song.source_path, "outcome": "here", "id": text_of(&row, "id"), "key": key, "title": title, "line": say("intake.here", &[("title", &title)])?})); continue; } // 3. The same song in another file: the better one is kept. let album_title = facts.album_title.clone().unwrap_or_default(); let artist_name = facts.artist_name.clone().unwrap_or_default(); let twins = rows_where(ctx, SONG_TABLE, "id, title, artist_name, album, duration, format, bitrate, file", "lower(trim(title)) = ?", &[rusqlite::types::Value::Text(fold(&facts.title))])?; let mut twin = None; for row in twins { // `album_title` is the album's own, read through the link. let held_album = match row.get("album").and_then(Value::as_str) { Some(album) => rows_where(ctx, ALBUM_TABLE, "title", "id = ?", &[rusqlite::types::Value::Text(album.to_string())])? .first() .map(|album| text_of(album, "title")) .unwrap_or_default(), None => String::new(), }; let held = (text_of(&row, "artist_name"), text_of(&row, "title"), held_album, row.get("duration").and_then(Value::as_f64)); if same_song((&artist_name, &facts.title, &album_title, facts.duration), (&held.0, &held.1, &held.2, held.3)) { twin = Some(row); break; } } if let Some(row) = twin { let id = text_of(&row, "id"); let held_format = text_of(&row, "format"); let held_bitrate = row.get("bitrate").and_then(Value::as_u64).map(|n| n as u32); if !better(&facts.format, facts.bitrate, &held_format, held_bitrate) { answers.push(json!({"sourcePath": song.source_path, "outcome": "worse", "id": id, "title": facts.title, "line": say("intake.worse", &[("title", &facts.title)])?})); continue; } let mut patch = Map::new(); patch.insert("file".into(), Value::from(key.clone())); patch.insert("format".into(), Value::from(facts.format.clone())); put(&mut patch, "duration", facts.duration.map(Value::from)); put(&mut patch, "bitrate", facts.bitrate.map(Value::from)); put(&mut patch, "sample_rate", facts.sample_rate.map(Value::from)); patch.insert("path".into(), Value::from(facts.path.clone())); patched(ctx, SONG_TABLE, &id, patch)?; queue(ctx, &workspace_id, &key, &stored, content_type, &now)?; let format = held_format.to_uppercase(); answers.push(json!({"sourcePath": song.source_path, "outcome": "better", "id": id, "key": key, "replaced": text_of(&row, "file"), "title": facts.title, "line": say("intake.better", &[("title", &facts.title), ("format", &format)])?})); continue; } // 4. Its artist and album, found or made, then the song. let artist = match facts.artist_name.as_deref() { Some(credit) => { // The sort tag is the credit's: it names this artist only when the credit is them alone. let primary = primary_artist(credit); let sort = song.tags.artist_sort.as_deref().filter(|_| fold(primary) == fold(credit)); Some(artist_of(ctx, primary, song.tags.mb_artist.as_deref(), sort, &mut artists)?) } None => None, }; let album = match facts.album_title.as_deref() { Some(title) => Some(album_of(ctx, layout, &workspace_id, &facts, title, song, &today, &now, &mut artists, &mut albums)?), None => None, }; let id = made(ctx, SONG_TABLE, song_row(&facts, &key, artist, album, &today))?; queue(ctx, &workspace_id, &key, &stored, content_type, &now)?; answers.push(json!({"sourcePath": song.source_path, "outcome": "added", "id": id, "key": key, "title": facts.title, "line": say("intake.added", &[("title", &facts.title)])?})); } let added = answers.iter().filter(|answer| answer["outcome"] == "added").count(); let said = match answers.as_slice() { [one] => one["line"].clone(), _ if added > 0 => Value::from(say("intake.added_many", &[("count", &added.to_string())])?), _ => answers.first().map(|answer| answer["line"].clone()).unwrap_or(Value::Null), }; Ok(json!({ "songs": answers, "said": said })) } /// The album keyed on its album artist and title, found or made; a cover or a /// field its songs bring fills only what it lacks. #[allow(clippy::too_many_arguments)] fn album_of( ctx: &mut Ctx<'_>, layout: &Layout, workspace_id: &str, facts: &SongFacts, title: &str, song: &SongIn, today: &str, now: &str, artists: &mut BTreeMap, albums: &mut BTreeMap, ) -> Result { let album_artist = facts.album_artist.clone().or(facts.artist_name.clone()).unwrap_or_default(); let keyed = album_key(&album_artist, title); let held = match albums.get(&keyed) { Some(id) => Some(id.clone()), None => rows_where(ctx, ALBUM_TABLE, "id, title, artist_name", "lower(trim(title)) = ?", &[rusqlite::types::Value::Text(fold(title))])? .into_iter() .find(|row| album_key(&text_of(row, "artist_name"), &text_of(row, "title")) == keyed) .map(|row| text_of(&row, "id")), }; let tags = &song.tags; let cover = |ctx: &mut Ctx<'_>| -> Result, String> { match song.cover_path.as_deref() { Some(path) => keep_cover(ctx, layout, workspace_id, path, now).map(Some), None => Ok(None), } }; let id = match held { Some(id) => { let columns = format!("id, cover, {}", ALBUM_FIELDS.join(", ")); let row = rows_where(ctx, ALBUM_TABLE, &columns, "id = ?", &[rusqlite::types::Value::Text(id.clone())])? .into_iter() .next() .unwrap_or_default(); let empty = |key: &str| row.get(key).is_none_or(|value| value.is_null() || value.as_str() == Some("")); let mut patch = Map::new(); if empty("cover") { put(&mut patch, "cover", cover(ctx)?.map(Value::from)); } for (key, value) in album_fields(facts, tags) { if empty(key) { patch.insert(key.into(), value); } } patched(ctx, ALBUM_TABLE, &id, patch)?; id } None => { let artist = if album_artist.is_empty() { None } else { Some(artist_of(ctx, &album_artist, tags.mb_album_artist.as_deref(), tags.album_artist_sort.as_deref(), artists)?) }; let mut data = Map::new(); data.insert("title".into(), Value::from(title.trim())); put(&mut data, "artist", artist.map(Value::from)); if !album_artist.is_empty() { data.insert("artist_name".into(), Value::from(album_artist.clone())); } put(&mut data, "cover", cover(ctx)?.map(Value::from)); put(&mut data, "compilation", tags.compilation.filter(|on| *on).map(Value::from)); data.extend(album_fields(facts, tags).into_iter().map(|(key, value)| (key.to_string(), value))); data.insert("added_on".into(), Value::from(today)); made(ctx, ALBUM_TABLE, data)? } }; albums.insert(keyed, id.clone()); Ok(id) } /// The song's upload, queued as any capture's: this phone took it, so its /// bytes are kept here for good. pub(crate) fn queue(ctx: &mut Ctx<'_>, workspace_id: &str, key: &str, stored: &cotton_client::media::store::StoredMediaFile, content_type: &str, now: &str) -> Result<(), String> { enqueue_media( ctx.db(), &MediaEnqueueInput { key: key.to_string(), workspace_id: workspace_id.to_string(), sha256: stored.sha256.clone(), content_type: content_type.to_string(), size_bytes: i64::try_from(stored.size_bytes).unwrap_or(i64::MAX), local_path: Some(stored.path.to_string_lossy().to_string()), state: None, after: None, after_row_id: None, tier: Some(HoldTier::Original), captured_here: true, now: now.to_string(), }, ) .map(|_| ()) .map_err(|error| error.to_string()) } fn keep_cover(ctx: &mut Ctx<'_>, layout: &Layout, workspace_id: &str, path: &Path, now: &str) -> Result { super::media::keep_picture(ctx, layout, workspace_id, path, now, "an album's cover") } // ── what this phone keeps ─────────────────────────────────────────────────── fn key_of<'a>(request: &'a Value, allowed: &[&str]) -> Result<&'a str, MethodError> { let fields = request.as_object().ok_or_else(|| bad("a songs method takes an object"))?; if fields.keys().any(|key| !allowed.contains(&key.as_str())) { return Err(bad("a songs method has an unknown field")); } fields .get("key") .and_then(Value::as_str) .map(str::trim) .filter(|key| !key.is_empty()) .ok_or_else(|| bad("a song is named by its file's key")) } fn read(client: &ClientController, request: &Value) -> Result { let key = key_of(request, &["key"])?; let state = stored(client)?.songs.remove(key); Ok(json!({ "key": key, "state": state })) } /// Signed in, the songs this phone kept stay kept under the object's keys: /// the backup re-keys each file (`/music/…` becomes `/music/…`), /// and a keep left under the old key would send the player to the object for /// bytes this phone holds. pub(crate) fn rekey_here(client: &ClientController, rekey: &dyn Fn(&str) -> String) -> Result<(), MethodError> { let moved: Vec<(String, String, String)> = stored(client)? .songs .iter() .map(|(key, state)| (key.clone(), rekey(key), state.clone())) .filter(|(key, again, _)| key != again) .collect(); if moved.is_empty() { return Ok(()); } { let _guard = write_lock(); let mut all = stored(client)?; for (key, _, _) in &moved { all.songs.remove(key); } write_locked(client, &all)?; } for (_, again, state) in moved { if state == KEPT { write(client, &json!({ "key": again, "state": KEPT }))?; } } Ok(()) } fn write(client: &ClientController, request: &Value) -> Result { let key = key_of(request, &["key", "state", "from"])?.to_string(); let state = match request.get("state") { None => return Err(bad("songs.here.write names the state, or null")), Some(Value::Null) => None, Some(Value::String(state)) if state == KEEPING || state == KEPT => Some(state.clone()), Some(_) => return Err(bad("a song is keeping or kept on this phone")), }; let kept = state.as_deref() == Some(KEPT); match request.get("from") { None => {} Some(Value::String(from)) if kept && !from.trim().is_empty() => { super::media::adopt_download(client, &key, Path::new(from.trim()), super::media::Expected::Named)?; } Some(_) => return Err(bad("`from` is the downloaded file's path, given with kept")), } let now = iso_now(client)?; let workspace = client .with_writer(|f| { if kept && super::media::local_path_of(f.driver, &key).is_none() { return Ok(Err(MethodError::new("not_here", "a song is kept only once its file is on this phone"))); } cotton_store::media_ledger::set_media_pinned(f.driver, &key, kept, &now).map_err(|error| error.to_string())?; Ok(Ok(f.workspace_id.to_string())) }) .map_err(|reason| MethodError::new("unwritable", reason))??; { let _guard = write_lock(); let mut all = stored(client)?; match &state { Some(state) => all.songs.insert(key.clone(), state.clone()), None => all.songs.remove(&key), }; write_locked(client, &all)?; } client.emit_data(&workspace, vec!["_media".into(), format!("cotton_{SONG_TABLE}"), format!("cotton_{ALBUM_TABLE}")], "local"); Ok(json!({ "key": key, "state": state })) } fn remove(client: &ClientController, request: &Value) -> Result { let key = key_of(request, &["key"])?.to_string(); let device = client.self_device_id().ok_or_else(not_backed_up)?; let now = client.clock().now().timestamp_millis(); let mut ids = cotton_client::seams::op_ids(client.random()); let (workspace, freed) = client .with_writer(|f| { let freed = cotton_client::media::storage::evict_one( f.driver, f.workspace_id, &device, client.layout(), &cotton_client::media::SystemEvictDisk, &key, now, &mut ids, super::storage::held(f), ); Ok((f.workspace_id.to_string(), freed)) }) .map_err(|reason| MethodError::new("unwritable", reason))?; let freed_bytes = freed.map_err(|error| match error { EvictOneError::NotBackedUp => not_backed_up(), EvictOneError::SharedFileKept(_) => MethodError::new("kept_by_another", "another record keeps this song's file on this phone"), EvictOneError::OutsideMediaFolder => MethodError::new("refused", error.to_string()), EvictOneError::Failed(why) => MethodError::new("unwritable", why), })?; { let _guard = write_lock(); let mut all = stored(client)?; if all.songs.remove(&key).is_some() { write_locked(client, &all)?; } } client.emit_data( &workspace, vec!["_media".into(), "cotton_media_holdings".into(), format!("cotton_{SONG_TABLE}"), format!("cotton_{ALBUM_TABLE}")], "local", ); client.nudge_sync(); Ok(json!({ "key": key, "freed_bytes": freed_bytes })) } fn not_backed_up() -> MethodError { MethodError::new("not_backed_up", "This song's file has not synced yet, so it stays on this phone.") } /// Whether this phone keeps every song, read or set. pub(crate) fn keeps_everything(client: &ClientController) -> Result { Ok(stored(client)?.keep_everything) } fn keep_everything(client: &ClientController, request: &Value) -> Result { let fields = request.as_object().ok_or_else(|| bad("songs.keepEverything takes an object"))?; if fields.keys().any(|key| key != "on") { return Err(bad("songs.keepEverything takes only `on`")); } match fields.get("on") { None | Some(Value::Null) => Ok(json!({ "on": keeps_everything(client)? })), Some(Value::Bool(on)) => call_keep_everything(client, *on), Some(_) => Err(bad("`on` is true or false")), } } /// This phone's Keep everything set, answered with the words it says. pub(crate) fn call_keep_everything(client: &ClientController, on: bool) -> Result { { let _guard = write_lock(); let mut all = stored(client)?; all.keep_everything = on; write_locked(client, &all)?; } let said = line(if on { "acts.keeping_everything" } else { "acts.stopped_keeping_everything" }, &[])?; Ok(json!({ "on": on, "said": said })) } // ── an album's lookups ─────────────────────────────── /// The record a play or a lookup names, checked to be one of this database's. fn named<'a>(client: &ClientController, request: &'a Value, tables: &[&str], extra: &[&str]) -> Result<(&'a str, &'a str), MethodError> { let fields = request.as_object().ok_or_else(|| bad("this method takes an object"))?; if fields.keys().any(|key| !matches!(key.as_str(), "table" | "id") && !extra.contains(&key.as_str())) { return Err(bad("this method has an unknown field")); } let table = fields.get("table").and_then(Value::as_str).filter(|table| tables.contains(table)).ok_or_else(|| bad("this names a song, an album or an artist"))?; let id = fields.get("id").and_then(Value::as_str).map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| bad("this names the record's id"))?; crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id}))?; Ok((table, id)) } fn find_details(client: &ClientController, request: &Value) -> Result { let (table, id) = named(client, request, &[ALBUM_TABLE], &[])?; Ok(json!({ "platform_action": "find_details", "table": table, "id": id })) } // ── on_phone, answered ────────────────────────────────────────────────────── pub(crate) fn records_of(answer: &mut Value) -> Vec<&mut Value> { if answer.get("records").is_some_and(Value::is_array) { return answer["records"].as_array_mut().map(|records| records.iter_mut().collect()).unwrap_or_default(); } vec![answer] } pub(crate) fn data_of(record: &mut Value) -> Option<&mut Map> { if record.get("data").is_some_and(Value::is_object) { return record.get_mut("data").and_then(Value::as_object_mut); } record.as_object_mut() } /// `on_phone` on every song of a records answer whose file is named. pub(crate) fn answer_on_phone(client: &ClientController, answer: &mut Value) -> Result<(), MethodError> { let mut kept: Option = None; for record in records_of(answer) { let Some(data) = data_of(record) else { continue }; data.remove(ON_PHONE); let Some(file) = data.get(FILE_COLUMN).and_then(Value::as_str).map(str::trim).filter(|file| !file.is_empty()) else { continue }; if kept.is_none() { kept = Some(stored(client)?); } let state = kept.as_ref().and_then(|kept| kept.songs.get(file)).cloned(); data.insert(ON_PHONE.to_string(), Value::from(state.unwrap_or_else(|| ABSENT.to_string()))); } Ok(()) } /// What a set of songs' states says of their album. pub fn album_state<'a>(states: impl IntoIterator>) -> &'static str { let (mut all, mut kept, mut keeping) = (0, 0, 0); for state in states { all += 1; match state { Some(KEPT) => kept += 1, Some(KEEPING) => keeping += 1, _ => {} } } match () { _ if all == 0 || kept + keeping == 0 => ABSENT, _ if kept == all => KEPT, _ if kept + keeping == all => KEEPING, _ => SOME, } } /// `on_phone` on every album of a records answer, from its songs. pub(crate) fn answer_albums_on_phone(client: &ClientController, answer: &mut Value) -> Result<(), MethodError> { let mut records = records_of(answer); let ids: Vec = records.iter_mut().filter_map(|record| data_of(record).and_then(|data| data.get("id").and_then(Value::as_str).map(str::to_string)).or_else(|| record.get("id").and_then(Value::as_str).map(str::to_string))).collect(); if ids.is_empty() { return Ok(()); } let mut files: BTreeMap> = BTreeMap::new(); client .read_rows("music.albumsOnPhone", &mut |ctx| { let marks = vec!["?"; ids.len()].join(", "); let args: Vec = ids.iter().cloned().map(rusqlite::types::Value::Text).collect(); for row in rows_where(ctx, SONG_TABLE, "album, file", &format!("album IN ({marks}) AND file IS NOT NULL AND file != ''"), &args)? { files.entry(text_of(&row, "album")).or_default().push(text_of(&row, "file")); } Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?; let kept = stored(client)?; for record in records { let id = record.get("id").and_then(Value::as_str).map(str::to_string); let Some(data) = data_of(record) else { continue }; let id = id.or_else(|| data.get("id").and_then(Value::as_str).map(str::to_string)).unwrap_or_default(); let songs = files.get(&id).map(Vec::as_slice).unwrap_or_default(); data.insert(ON_PHONE.to_string(), Value::from(album_state(songs.iter().map(|file| kept.songs.get(file).map(String::as_str))))); } Ok(()) } /// `songs.keepPlan { op: keep|remove|sweep, table?, id? }` → `{ keys }`: the /// song files a move touches on this phone, as a shell keeps or lets them go /// (iOS's SongKeeper, its rule here): Keep on phone of a song or an album, its /// files not here yet (an album's every song's, in no order a shell reads); /// Remove download, its files this phone keeps or is fetching; Keep /// everything's sweep, every song's file not here while it is on, none while /// it is off. A shell fetches each key (`media.stream`), marks it `keeping` /// and hands what lands to `songs.here.write { from }`. fn keep_plan(client: &ClientController, request: &Value) -> Result { let op = request.get("op").and_then(Value::as_str).ok_or_else(|| bad("songs.keepPlan takes { op: keep|remove|sweep, table?, id? }"))?; let here = stored(client)?; let files: Vec = match op { "sweep" => { if !here.keep_everything { return Ok(json!({ "keys": [] })); } client .read_rows("songs.keepPlan", &mut |ctx| Ok(json!(rows_where(ctx, SONG_TABLE, "file", "file IS NOT NULL AND file != ''", &[])?.iter().map(|row| text_of(row, "file")).collect::>()))) .map_err(|why| MethodError::new("unreadable", why))? } "keep" | "remove" => { let (table, id) = named(client, request, &[SONG_TABLE, ALBUM_TABLE], &["op"])?; let column = if table == SONG_TABLE { "id" } else { "album" }; client .read_rows("songs.keepPlan", &mut |ctx| { let rows = rows_where(ctx, SONG_TABLE, "file", &format!("{column} = ? AND file IS NOT NULL AND file != ''"), &[rusqlite::types::Value::Text(id.to_string())])?; Ok(json!(rows.iter().map(|row| text_of(row, "file")).collect::>())) }) .map_err(|why| MethodError::new("unreadable", why))? } _ => return Err(bad("songs.keepPlan's op is keep, remove or sweep")), } .as_array() .into_iter() .flatten() .filter_map(|file| file.as_str().map(str::to_string)) .collect(); let mut keys: Vec = files.into_iter().filter(|key| (op == "remove") == here.songs.contains_key(key)).collect(); keys.sort(); keys.dedup(); Ok(json!({ "keys": keys })) } /// A list of songs read by `where.on_phone`, as the files this device keeps /// in those states (`books::narrow_where`'s rule, for songs). pub(crate) fn narrow_where(client: &ClientController, args: &mut Map) -> Result<(), MethodError> { if args.get("table").and_then(Value::as_str) != Some(SONG_TABLE) { return Ok(()); } let Some(conditions) = args.get_mut("where").and_then(Value::as_object_mut) else { return Ok(()) }; let Some(wanted) = conditions.remove(ON_PHONE) else { return Ok(()) }; let refused = || bad("on_phone reads absent, or keeping and kept"); let states: Vec<&str> = match &wanted { Value::String(state) => vec![state.as_str()], Value::Array(states) => states.iter().map(|state| state.as_str().ok_or_else(refused)).collect::>()?, _ => return Err(refused()), }; let stored = stored(client)?; let keys = |held: &[&str]| -> Vec { stored.songs.iter().filter(|(_, state)| held.contains(&state.as_str())).map(|(key, _)| Value::from(key.as_str())).collect() }; let condition = match states.as_slice() { [ABSENT] => { let held = keys(&[KEEPING, KEPT]); if held.is_empty() { json!({ "present": true }) } else { json!({ "not": held }) } } states if !states.is_empty() && states.iter().all(|state| *state == KEEPING || *state == KEPT) => { let held = keys(states); Value::Array(if held.is_empty() { vec![Value::from(NOTHING_KEPT)] } else { held }) } _ => return Err(refused()), }; if conditions.contains_key(FILE_COLUMN) { return Err(bad("a list reads on_phone or file, not both")); } conditions.insert(FILE_COLUMN.to_string(), condition); Ok(()) } // ── the file ──────────────────────────────────────────────────────────────── pub(crate) fn iso_now(client: &ClientController) -> Result { cotton_store::protocol::js::to_iso_string(client.clock().now().timestamp_millis()) .ok_or_else(|| MethodError::new("unwritable", "the clock is out of range")) } fn path(client: &ClientController) -> PathBuf { client.layout().client_dir().join(FILE) } fn stored(client: &ClientController) -> Result { let path = path(client); let bytes = match std::fs::read(&path) { Ok(bytes) => bytes, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Stored::default()), Err(error) => return Err(MethodError::new("unreadable", format!("{FILE}: {error}"))), }; serde_json::from_slice(&bytes).map_err(|error| MethodError::new("unreadable", format!("{FILE} is not valid JSON: {error}"))) } fn write_locked(client: &ClientController, all: &Stored) -> Result<(), MethodError> { let path = path(client); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))?; } let partial = path.with_extension(format!("json.{}.partial", std::process::id())); // not a copy: song files. std::fs::write(&partial, serde_json::to_vec_pretty(all).expect("songs serialise")) .map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))?; // not a copy: song files. std::fs::rename(&partial, path).map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}"))) } pub(crate) fn write_lock() -> MutexGuard<'static, ()> { WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } #[cfg(test)] #[path = "songs_tests.rs"] mod tests;