Cotton code
379 lines · 15.5 KB · RustRaw
//! An album ZIP into Music (`pnpm music:import <file.zip>`, or a ZIP met in a//! walked folder): a Bandcamp download is one album.//!//! The ZIP is read from its central directory and each entry the album wants//! (its songs, its cover, its booklets and notes) is streamed into a temp//! folder, never read whole: a FLAC album runs to hundreds of MB.//! `cotton_core::music::album_zip` says from the names whether it is one//! album; the songs are read as a folder's are (`walk::read`), and their//! album tags handed back to the rule, which names the one album. Every song//! then carries that album and its album artist, so the importer gathers them//! into one album even when a compilation tags each track its own way.//!//! After the songs, the album is found by its key and only its empty columns//! are filled: `store_url` and `store_id` from a Bandcamp album page named in//! a note (or the ZIP's name), `bought_on` the ZIP's own file date in the//! owner's zone, `booklet` the first PDF, sent 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 cotton_core::media::keys::{media_limits, MediaKind};use cotton_core::music::album_zip::{album_zip, store_of, NamedFrom, Store, ZipAlbum, ZipEntry, ZipRefusal};use cotton_core::music::album_key;use cotton_core::rules::shell_lines::LineSet;use serde_json::Value;use super::import::{read_folder, ImportError, Importer, Object, Outcome, Report, Row, ALBUM_TABLE};use super::walk::{natural_cmp, read, CoverFrom, Found, SongIn};use crate::ids;/// The most of a note read for a shop's page: a note is a few lines.const NOTE_BYTES: u64 = 64 * 1024;/// What became of one ZIP.#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]#[serde(rename_all = "camelCase")]pub struct ZipOutcome {    /// The ZIP's file name.    pub zip: String,    /// The album it came in as; `None` when it was refused.    #[serde(skip_serializing_if = "Option::is_none")]    pub album: Option<String>,    #[serde(skip_serializing_if = "Option::is_none")]    pub artist: Option<String>,    /// `tags`, `zip_disagreeing` or `zip_untagged`.    #[serde(skip_serializing_if = "Option::is_none")]    pub named_from: Option<&'static str>,    #[serde(skip_serializing_if = "Option::is_none")]    pub store_url: Option<String>,    #[serde(skip_serializing_if = "Option::is_none")]    pub store_id: Option<String>,    #[serde(skip_serializing_if = "Option::is_none")]    pub bought_on: Option<String>,    /// The booklet's key in the object.    #[serde(skip_serializing_if = "Option::is_none")]    pub booklet: Option<String>,    pub refused: bool,    pub line: String,}/// A whole run over a ZIP or a folder: the songs, and each ZIP.#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]pub struct PathReport {    pub report: Report,    pub zips: Vec<ZipOutcome>,}fn lines() -> Result<LineSet, ImportError> {    LineSet::shipped("music").ok_or_else(|| ImportError::Refused("the kit ships no music lines".to_string()))}fn say(name: &str, fills: &[(&str, &str)]) -> Result<String, ImportError> {    lines()?.say(name, fills).ok_or_else(|| ImportError::Refused(format!("the music set says no line {name}")))}fn io(path: &Path) -> impl FnOnce(std::io::Error) -> ImportError + '_ {    move |error| ImportError::Io { path: path.to_path_buf(), error }}/// Whether a path is a ZIP by its name.pub fn is_zip(path: &Path) -> bool {    path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))}fn file_name(path: &Path) -> String {    path.file_name().map(|name| name.to_string_lossy().to_string()).unwrap_or_default()}/// A ZIP's songs streamed out and read, the one album its rule names, and/// its extras, in a temp folder that goes when this does.pub struct Unpacked {    _dir: tempfile::TempDir,    pub album: ZipAlbum,    pub songs: Vec<SongIn>,    pub booklet: Option<PathBuf>,    pub store: Option<Store>,}/// Why a ZIP is not unpacked, said in the music set's words.fn refusal(name: &str, why: &ZipRefusal) -> Result<String, ImportError> {    match why {        ZipRefusal::NoSongs => say("intake.zip_empty", &[("name", name)]),        ZipRefusal::Folders(_) => say("intake.zip_folders", &[("name", name)]),    }}/// `zip`'s album, streamed into a temp folder and read; `Err(line)` when it/// is not one album or cannot be opened.pub fn unpack(zip: &Path) -> Result<Result<Unpacked, String>, ImportError> {    let name = file_name(zip);    let unreadable = || say("intake.zip_unreadable", &[("name", &name)]);    let file = File::open(zip).map_err(io(zip))?;    let Ok(mut archive) = zip::ZipArchive::new(BufReader::new(file)) else { return Ok(Err(unreadable()?)) };    // The names, from the central directory alone; a name that would land    // outside the folder (`../x`, an absolute path) is not one of the album's.    let mut entries = Vec::new();    for at in 0..archive.len() {        let Ok(entry) = archive.by_index_raw(at) else { return Ok(Err(unreadable()?)) };        if entry.enclosed_name().is_none() {            continue;        }        let Ok(entry_name) = entry.name() else { return Ok(Err(unreadable()?)) };        entries.push(ZipEntry::named(&entry_name, entry.size()));    }    let layout = match album_zip(&name, &entries) {        Ok(layout) => layout,        Err(why) => return Ok(Err(refusal(&name, &why)?)),    };    // Only what the album wants comes out, each entry streamed to its file.    let dir = tempfile::tempdir().map_err(io(zip))?;    let mut out = |entry_name: &str| -> Result<Option<PathBuf>, ImportError> {        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 = dir.path().join(below);        if let Some(parent) = path.parent() {            std::fs::create_dir_all(parent).map_err(io(parent))?;        }        let mut file = File::create(&path).map_err(io(&path))?;        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 found = Vec::new();    for song in &layout.songs {        let Some(path) = out(song)? else { return Ok(Err(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}") };        found.push(Found { path, source_path });    }    let cover = match &layout.cover {        Some(cover) => out(cover)?,        None => None,    };    let booklet = match layout.booklets.first() {        Some(booklet) => out(booklet)?,        None => None,    };    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();            let _ = File::open(&path).map_err(io(&path))?.take(NOTE_BYTES).read_to_string(&mut text);            store = store_of(&text);        }    }    // The songs read, and their album tags handed back to name the one album.    let mut songs: Vec<SongIn> = found.iter().map(read).collect();    let tagged: Vec<ZipEntry> = entries        .iter()        .map(|entry| match layout.songs.iter().position(|song| *song == entry.name) {            Some(at) => ZipEntry {                album: songs[at].tags.album.clone(),                album_artist: songs[at].tags.album_artist.clone(),                artist: songs[at].tags.artist.clone(),                ..entry.clone()            },            None => entry.clone(),        })        .collect();    let album = match album_zip(&name, &tagged) {        Ok(album) => album,        Err(why) => return Ok(Err(refusal(&name, &why)?)),    };    for song in &mut songs {        song.tags.album = Some(album.title.clone());        if let Some(artist) = &album.artist {            song.tags.album_artist = Some(artist.clone());        }        if !matches!(song.cover, Some(CoverFrom::Embedded(_))) {            if let Some(cover) = &cover {                song.cover = Some(CoverFrom::Folder(cover.clone()));            }        }    }    Ok(Ok(Unpacked { _dir: dir, album, songs, booklet, store }))}/// The day a file was last written, in the owner's zone.fn file_day(path: &Path, zone: &str) -> Option<String> {    let modified = std::fs::metadata(path).ok()?.modified().ok()?;    let millis = modified.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis() as i64;    let day = cotton_core::transforms::zoned_clock::zoned_parts(millis, zone).ok()?;    Some(format!("{:04}-{:02}-{:02}", day.year, day.month, day.day))}fn named_from_word(named: NamedFrom) -> &'static str {    match named {        NamedFrom::Tags => "tags",        NamedFrom::ZipDisagreeing => "zip_disagreeing",        NamedFrom::ZipUntagged => "zip_untagged",    }}fn empty(row: &Row, key: &str) -> bool {    row.get(key).is_none_or(|value| value.is_null() || value.as_str() == Some(""))}/// A ZIP unpacked and its songs brought in, waiting for its album's columns.struct Landed {    unpacked: Unpacked,    outcome: ZipOutcome,}/// One ZIP's songs into the run; `Ok(None)` and a refused outcome when it is/// not one album.fn land_zip(importer: &mut Importer<'_>, zip: &Path, zone: &str, each: &mut dyn FnMut(&Outcome)) -> Result<Result<Landed, ZipOutcome>, ImportError> {    let name = file_name(zip);    let unpacked = match unpack(zip)? {        Ok(unpacked) => unpacked,        Err(line) => return Ok(Err(ZipOutcome { zip: name, refused: true, line, ..ZipOutcome::default() })),    };    importer.album(&unpacked.songs, each)?;    let album = &unpacked.album;    let line = match album.named_from {        NamedFrom::ZipDisagreeing => say("intake.zip_one_album", &[("name", &name), ("title", &album.title)])?,        _ => say("intake.zip_album", &[("name", &name), ("title", &album.title)])?,    };    let outcome = ZipOutcome {        zip: name,        album: Some(album.title.clone()),        artist: album.artist.clone(),        named_from: Some(named_from_word(album.named_from)),        store_url: unpacked.store.as_ref().map(|store| store.url.clone()),        store_id: unpacked.store.as_ref().map(|store| store.id.clone()),        bought_on: file_day(zip, zone),        booklet: None,        refused: false,        line,    };    Ok(Ok(Landed { unpacked, outcome }))}/// The album a landed ZIP came in as, its empty shop columns and booklet filled.fn fill_album(object: &dyn Object, albums: &[Row], landed: &mut Landed) -> Result<(), ImportError> {    let album = &landed.unpacked.album;    let keyed = album_key(album.artist.as_deref().unwrap_or_default(), &album.title);    let Some(row) = albums.iter().find(|row| {        let text = |key: &str| row.get(key).and_then(Value::as_str).unwrap_or_default().to_string();        album_key(&text("artist_name"), &text("title")) == keyed    }) else {        return Ok(());    };    let id = row.get("id").and_then(Value::as_str).unwrap_or_default().to_string();    // "Only if empty" judged on the album as it is now, not as the run read it before its unzip and uploads: a shop    // link or a booklet the owner set meanwhile stays (STALE WRITES 2, 25 Nov 2026).    let now = object.row_now(ALBUM_TABLE, &id)?;    let row = now.as_ref().unwrap_or(row);    let mut patch = Row::new();    let outcome = &mut landed.outcome;    for (key, value) in [("store_url", &outcome.store_url), ("store_id", &outcome.store_id), ("bought_on", &outcome.bought_on)] {        if let Some(value) = value {            if empty(row, key) {                patch.insert(key.into(), Value::from(value.clone()));            }        }    }    if let Some(path) = &landed.unpacked.booklet {        let (sha256, size) = ids::sha256_of_file(path).map_err(io(path))?;        let key = format!("{}/books/{sha256}.pdf", object.database_id()?);        if size <= media_limits(MediaKind::Book).max_bytes {            if !object.media_held(&key)? {                object.put_file(&key, path, size, "application/pdf")?;            }            if empty(row, "booklet") {                patch.insert("booklet".into(), Value::from(key.clone()));            }            outcome.booklet = Some(key);        }    }    if !patch.is_empty() {        object.update(ALBUM_TABLE, &id, &patch)?;    }    Ok(())}/// Every ZIP under `folder`, hidden ones skipped.fn zips_in(folder: &Path) -> std::io::Result<Vec<PathBuf>> {    let mut zips = 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 entry.file_name().to_string_lossy().starts_with('.') {                continue;            }            let kind = entry.file_type()?;            if kind.is_dir() {                pending.push(entry.path());            } else if kind.is_file() && is_zip(&entry.path()) {                zips.push(entry.path());            }        }    }    zips.sort_by(|a, b| natural_cmp(&a.to_string_lossy(), &b.to_string_lossy()));    Ok(zips)}/// The whole verb over a path: a ZIP is one album; a folder comes in as/// `import_folder` brings it (its songs album by album, then its playlist/// files as lists) with every ZIP inside it as one album each, before the/// lists. `zone` is the owner's, for a ZIP's day bought.pub fn import_path(object: &dyn Object, path: &Path, today: &str, zone: &str, each: &mut dyn FnMut(&Outcome)) -> Result<PathReport, ImportError> {    let (albums, lists, zips) = if path.is_file() && is_zip(path) {        (Vec::new(), Vec::new(), vec![path.to_path_buf()])    } else if path.is_dir() {        let zips = zips_in(path).map_err(io(path))?;        match read_folder(path) {            Ok((albums, lists)) => (albums, lists, zips),            // A folder holding only ZIPs holds albums all the same.            Err(ImportError::Refused(_)) if !zips.is_empty() => (Vec::new(), Vec::new(), zips),            Err(error) => return Err(error),        }    } else {        return Err(ImportError::Refused(format!("{} is not a folder or a ZIP", path.display())));    };    let loose = !albums.is_empty() || !lists.is_empty();    let mut importer = Importer::open(object, today)?;    for album in albums {        importer.album(&album, each)?;    }    let mut landed = Vec::new();    let mut zip_outcomes = Vec::new();    for zip in &zips {        match land_zip(&mut importer, zip, zone, each)? {            Ok(done) => landed.push(done),            Err(refused) => zip_outcomes.push(refused),        }    }    // A ZIP named alone that is no album is refused whole, in its words.    if let ([_], [refused], false) = (zips.as_slice(), zip_outcomes.as_slice(), loose) {        return Err(ImportError::Refused(refused.line.clone()));    }    for list in &lists {        importer.list(list)?;    }    let mut report = importer.finish()?;    if !landed.is_empty() {        let albums = object.rows(ALBUM_TABLE)?;        for done in &mut landed {            fill_album(object, &albums, done)?;        }    }    zip_outcomes.extend(landed.into_iter().map(|done| done.outcome));    zip_outcomes.sort_by(|a, b| natural_cmp(&a.zip, &b.zip));    if let ([zip], false) = (zip_outcomes.as_slice(), loose) {        report.said = zip.line.clone();    }    Ok(PathReport { report, zips: zip_outcomes })}