Cotton code
264 lines · 12.3 KB · RustRaw
//! An album ZIP into Music on the phone (Bandcamp into Music, 7 Nov 2026)://! the share sheet's or a door's ZIP is one album, as the Mac's//! `music:import` makes it (`cotton-mac/src/music/album_zip.rs`).//!//! - `music.zip { path, name, into }` → `{ songs: [{ entry, path, sourcePath }],//!   coverPath?, bookletPath?, storeUrl?, storeId?, boughtOn? }`, or `{//!   refused: "no_songs" | "folders" | "unreadable", line }`: the ZIP read//!   from its central directory, `cotton_core::music::album_zip` asked from//!   the names whether it is one album, and only what the album wants (its//!   songs, its cover, its first booklet, its notes until one names the shop)//!   streamed entry by entry into `into`, never the whole archive into memory//!   (a FLAC album runs to hundreds of MB). An entry whose name would land//!   outside `into` (`../x`, an absolute path) is no entry of the album.//!   `boughtOn` is the ZIP's own file date in this phone's zone; the shop's//!   page is a Bandcamp album named in the ZIP's name or a note.//! - The phone reads each song's tags (TagLib) and hands them to//!   `music.capture { songs: [{ …, entry }], zip: { name, boughtOn?,//!   storeUrl?, storeId?, bookletPath? } }`: the rule names the one album//!   from the songs' tags ([`named`]), every song carries that album and its//!   album artist so a compilation tagged track by track is still one album,//!   and after the songs the album's empty `store_url`, `store_id`,//!   `bought_on` and `booklet` are filled ([`write_zip_album`]), the booklet//!   kept as a book file (`<db>/books/<sha256>.pdf`) the reader opens.use std::fs::File;use std::io::{BufReader, Read};use std::path::{Path, PathBuf};use serde::Deserialize;use serde_json::{json, Map, Value};use cotton_client::layout::Layout;use cotton_client::media::store::put_media_file;use cotton_core::media::keys::{book_key, media_limits, MediaKind};use cotton_core::music::album_zip::{album_zip, store_of, NamedFrom, ZipAlbum, ZipEntry, ZipRefusal};use cotton_tools::mcp::dispatch::Ctx;use super::io_trouble::io_refusal;use super::songs::{line, patched, queue, rows_where, text_of, write_songs, SongIn, ALBUM_TABLE, SONG_TABLE};use crate::methods::MethodError;use crate::shell::client::ClientController;/// The most of a note read for a shop's page: a note is a few lines.const NOTE_BYTES: u64 = 64 * 1024;#[derive(Debug, Deserialize)]#[serde(deny_unknown_fields)]struct OpenIn {    /// The ZIP, staged where the phone owns it.    path: PathBuf,    /// Its file name as it came in (`Artist - Album.zip`): it names the    /// album when the songs' tags do not, and may carry the shop's page.    name: String,    /// The folder the album's entries are streamed into; the phone's own.    into: PathBuf,}/// What a ZIP's capture brings beside its songs (`music.capture`'s `zip`).#[derive(Debug, Clone, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct ZipIn {    pub name: String,    #[serde(default)]    pub bought_on: Option<String>,    #[serde(default)]    pub store_url: Option<String>,    #[serde(default)]    pub store_id: Option<String>,    #[serde(default)]    pub booklet_path: Option<PathBuf>,}fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why.to_string())}fn refused(kind: &str, line_name: &str, name: &str) -> Result<Value, MethodError> {    Ok(json!({ "refused": kind, "line": line(line_name, &[("name", name)])? }))}fn refusal(why: &ZipRefusal, name: &str) -> Result<Value, MethodError> {    match why {        ZipRefusal::NoSongs => refused("no_songs", "intake.zip_empty", name),        ZipRefusal::Folders(_) => refused("folders", "intake.zip_folders", name),    }}/// `music.zip`: the album's entries out of the ZIP, or why it is no album.pub fn open(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    open_in(request, client.time_zone())}/// [`open`] with the zone the day bought is said in (none: not said).fn open_in(request: &Value, zone: Option<&str>) -> Result<Value, MethodError> {    let asked: OpenIn = serde_json::from_value(request.clone()).map_err(|error| bad(&format!("music.zip takes {{ path, name, into }}: {error}")))?;    let name = asked.name.rsplit(['/', '\\']).next().unwrap_or(&asked.name).to_string();    let unreadable = || refused("unreadable", "intake.zip_unreadable", &name);    let Ok(file) = File::open(&asked.path) else { return unreadable() };    let Ok(mut archive) = zip::ZipArchive::new(BufReader::new(file)) else { return unreadable() };    // The names, from the central directory alone.    let mut entries = Vec::new();    for at in 0..archive.len() {        let Ok(entry) = archive.by_index_raw(at) else { return unreadable() };        if entry.enclosed_name().is_none() {            continue;        }        let Ok(entry_name) = entry.name() else { return unreadable() };        entries.push(ZipEntry::named(&entry_name, entry.size()));    }    let layout = match album_zip(&name, &entries) {        Ok(layout) => layout,        Err(why) => return refusal(&why, &name),    };    // Only what the album wants comes out, each entry streamed to its file.    std::fs::create_dir_all(&asked.into).map_err(|error| MethodError::new("unwritable", io_refusal("the ZIP's folder could not be made", &asked.into, &error)))?;    let mut out = |entry_name: &str| -> Result<Option<PathBuf>, MethodError> {        let Ok(mut entry) = archive.by_name(entry_name) else { return Ok(None) };        let Some(below) = entry.enclosed_name() else { return Ok(None) };        let path = asked.into.join(below);        if let Some(parent) = path.parent() {            std::fs::create_dir_all(parent).map_err(|error| MethodError::new("unwritable", io_refusal("the ZIP's folder could not be made", parent, &error)))?;        }        // not a copy: a ZIP's entry.        let mut file = File::create(&path).map_err(|error| MethodError::new("unwritable", io_refusal("a ZIP's entry could not be written", &path, &error)))?;        if std::io::copy(&mut entry, &mut file).is_err() {            return Ok(None);        }        Ok(Some(path))    };    let stem = name.rsplit_once('.').map(|(stem, _)| stem.to_string()).unwrap_or(name.clone());    let mut songs = Vec::new();    for song in &layout.songs {        let Some(path) = out(song)? else { return unreadable() };        // Named as a folder's song is: under the ZIP's own name when it sits at its root.        let source_path = if song.contains('/') { song.clone() } else { format!("{stem}/{song}") };        songs.push(json!({ "entry": song, "path": path, "sourcePath": source_path }));    }    let mut answer = Map::new();    answer.insert("songs".into(), Value::from(songs));    if let Some(cover) = &layout.cover {        if let Some(path) = out(cover)? {            answer.insert("coverPath".into(), json!(path));        }    }    if let Some(booklet) = layout.booklets.first() {        if let Some(path) = out(booklet)? {            answer.insert("bookletPath".into(), json!(path));        }    }    let mut store = store_of(&name);    for note in &layout.notes {        if store.is_some() {            break;        }        if let Some(path) = out(note)? {            let mut text = String::new();            if let Ok(file) = File::open(&path) {                let _ = file.take(NOTE_BYTES).read_to_string(&mut text);            }            store = store_of(&text);        }    }    if let Some(store) = store {        answer.insert("storeUrl".into(), Value::from(store.url));        answer.insert("storeId".into(), Value::from(store.id));    }    if let Some(day) = zone.and_then(|zone| file_day(&asked.path, zone)) {        answer.insert("boughtOn".into(), Value::from(day));    }    Ok(Value::Object(answer))}/// The day a file was last written, in `zone`.fn file_day(path: &Path, zone: &str) -> Option<String> {    let modified = std::fs::metadata(path).ok()?.modified().ok()?;    let millis = i64::try_from(modified.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis()).ok()?;    cotton_tools::mcp::handlers::common::today_in(zone, millis).ok()}/// The one album a ZIP's songs make, named from their tags by the rule, and/// the songs each carrying it; `Err` the refusal's line.pub fn named(zip: &ZipIn, songs: &[SongIn]) -> Result<(ZipAlbum, Vec<SongIn>), String> {    let mut entries = Vec::with_capacity(songs.len());    for song in songs {        let entry = song.entry.as_deref().filter(|entry| !entry.is_empty()).ok_or("a ZIP's song names its entry")?;        entries.push(ZipEntry {            album: song.tags.album.clone(),            album_artist: song.tags.album_artist.clone(),            artist: song.tags.artist.clone(),            ..ZipEntry::named(entry, 0)        });    }    let say = |name: &str| line(name, &[("name", &zip.name)]).map_err(|failure| failure.message);    let album = match album_zip(&zip.name, &entries) {        Ok(album) => album,        Err(ZipRefusal::NoSongs) => return Err(say("intake.zip_empty")?),        Err(ZipRefusal::Folders(_)) => return Err(say("intake.zip_folders")?),    };    let mut named = songs.to_vec();    for song in &mut named {        song.tags.album = Some(album.title.clone());        if let Some(artist) = &album.artist {            song.tags.album_artist = Some(artist.clone());        }    }    Ok((album, named))}/// A ZIP's songs in one write, then its album's empty shop columns and/// booklet filled; the answer names the album and says the ZIP's line.pub fn write_zip_album(ctx: &mut Ctx<'_>, layout: &Layout, songs: &[SongIn], zone: &str, zip: &ZipIn) -> Result<Value, String> {    let (album, songs) = named(zip, songs)?;    let mut answer = write_songs(ctx, layout, &songs, zone)?;    let song = answer["songs"].as_array().into_iter().flatten().find_map(|song| song["id"].as_str().map(str::to_string));    let album_id = match song {        Some(id) => rows_where(ctx, SONG_TABLE, "id, album", "id = ?", &[rusqlite::types::Value::Text(id)])?.first().map(|row| text_of(row, "album")).filter(|album| !album.is_empty()),        None => None,    };    if let Some(id) = &album_id {        fill_album(ctx, layout, id, zip)?;        answer["album"] = Value::from(id.clone());    }    let words = match album.named_from {        NamedFrom::ZipDisagreeing => "intake.zip_one_album",        _ => "intake.zip_album",    };    answer["said"] = Value::from(line(words, &[("name", &zip.name), ("title", &album.title)]).map_err(|failure| failure.message)?);    Ok(answer)}/// Only the album's empty columns: the shop's page and id, the day bought,/// the booklet (its bytes into this device's store as a book file, queued up).fn fill_album(ctx: &mut Ctx<'_>, layout: &Layout, id: &str, zip: &ZipIn) -> Result<(), String> {    let Some(row) = rows_where(ctx, ALBUM_TABLE, "id, store_url, store_id, bought_on, booklet", "id = ?", &[rusqlite::types::Value::Text(id.to_string())])?.into_iter().next() else {        return Ok(());    };    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 [("store_url", &zip.store_url), ("store_id", &zip.store_id), ("bought_on", &zip.bought_on)] {        if let Some(value) = value.as_deref().map(str::trim).filter(|value| !value.is_empty()) {            if empty(key) {                patch.insert(key.into(), Value::from(value));            }        }    }    if let Some(path) = zip.booklet_path.as_deref().filter(|_| empty("booklet")) {        let workspace_id = ctx.workspace_id.to_string();        let size = std::fs::metadata(path).map_err(|error| io_refusal("the ZIP's booklet could not be read", path, &error))?.len();        if size <= media_limits(MediaKind::Book).max_bytes {            let stored = put_media_file(layout, &workspace_id, path, "pdf").map_err(|error| io_refusal("the ZIP's booklet could not be copied into this device's store", path, &error))?;            let key = book_key(ctx.file.id(), &stored.sha256, "pdf");            let now = cotton_tools::mcp::handlers::common::now_iso(ctx);            queue(ctx, &workspace_id, &key, &stored, "application/pdf", &now)?;            patch.insert("booklet".into(), Value::from(key));        }    }    patched(ctx, ALBUM_TABLE, id, patch)}#[cfg(test)]#[path = "songs_zip_tests.rs"]mod tests;