Cotton code
283 lines · 13.5 KB · RustRaw
//! `music-import` of an album ZIP, end to end on synthetic ZIPs the test//! builds itself: tiny FLAC and MP3 streams of silence tagged by lofty,//! packed with the `zip` crate. No real music, no Bandcamp, no network.//!//! A clean Bandcamp album; a booklet; a compilation whose tags disagree,//! still one album named by the ZIP; a ZIP holding no songs, refused in//! words; a nested folder; a ZIP met inside a walked folder.use std::fs;use std::io::Write;use std::path::{Path, PathBuf};use std::time::{Duration, SystemTime};use cotton_mac::music::album_zip::{import_path, unpack, PathReport};use cotton_mac::music::import::{ImportError, Memory, Outcome, ALBUM_TABLE, ARTIST_TABLE, SONG_TABLE};use lofty::config::WriteOptions;use lofty::prelude::*;use lofty::tag::{ItemKey, Tag, TagType};use serde_json::Value;use zip::write::SimpleFileOptions;const DB: &str = "00000000-0000-4000-8000-0000000000bb";const TODAY: &str = "2026-11-07";const ZONE: &str = "Asia/Kolkata";/// 2026-09-21 19:43 in Kolkata: the ZIP's own file date, its day bought.const ZIP_WRITTEN: u64 = 1_790_000_000;const JPEG: &[u8] = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, b'J', b'F', b'I', b'F', 0x00, 0x01, 0x02, 0x03];const PDF: &[u8] = b"%PDF-1.4\n% a booklet of nothing\n%%EOF\n";// ── synthetic audio ─────────────────────────────────────────────────────────/// A FLAC stream: STREAMINFO saying `seconds` at 44.1 kHz, then a little/// padding standing in for frames; `salt` makes each file's bytes its own.fn flac(seconds: u64, salt: u8) -> Vec<u8> {    let rate: u64 = 44_100;    let mut info = Vec::new();    info.extend_from_slice(&4096u16.to_be_bytes());    info.extend_from_slice(&4096u16.to_be_bytes());    info.extend_from_slice(&[0, 0, 0, 0, 0, 0]);    let packed: u64 = (rate << 44) | (1 << 41) | (15 << 36) | (rate * seconds);    info.extend_from_slice(&packed.to_be_bytes());    info.extend_from_slice(&[salt; 16]);    let mut bytes = b"fLaC".to_vec();    bytes.push(0x80);    bytes.extend_from_slice(&(info.len() as u32).to_be_bytes()[1..]);    bytes.extend_from_slice(&info);    bytes.extend_from_slice(&[0xFF, 0xF8]);    bytes.resize(bytes.len() + 4000, salt);    bytes}/// An MPEG-1 Layer III stream at 128 kbps, 44.1 kHz: `seconds` of frames.fn mp3(seconds: u32, salt: u8) -> Vec<u8> {    let mut bytes = Vec::new();    for _ in 0..seconds * 44_100 / 1152 + 1 {        bytes.extend_from_slice(&[0xFF, 0xFB, 0x90, 0x64]);        bytes.resize(bytes.len() + 413, salt);    }    bytes}/// `bytes` tagged by lofty as a tagger would, through a file in `scratch`.fn tagged(scratch: &Path, ext: &str, bytes: Vec<u8>, fields: &[(ItemKey, &str)]) -> Vec<u8> {    let path = scratch.join(format!("tagging.{ext}"));    fs::write(&path, bytes).unwrap();    let kind = if ext == "mp3" { TagType::Id3v2 } else { TagType::VorbisComments };    let mut tag = Tag::new(kind);    for (key, value) in fields {        assert!(tag.insert_text(*key, value.to_string()), "{key:?} goes in a {kind:?} tag");    }    tag.save_to_path(&path, WriteOptions::default()).unwrap();    fs::read(&path).unwrap()}fn track(scratch: &Path, salt: u8, title: &str, artist: &str, album: &str, album_artist: Option<&str>) -> Vec<u8> {    let mut fields = vec![(ItemKey::TrackTitle, title), (ItemKey::TrackArtist, artist), (ItemKey::AlbumTitle, album)];    if let Some(album_artist) = album_artist {        fields.push((ItemKey::AlbumArtist, album_artist));    }    tagged(scratch, "flac", flac(3, salt), &fields)}/// A ZIP at `path` holding `entries` (a name ending `/` is a folder),/// deflated, its file date [`ZIP_WRITTEN`].fn zip_file(path: &Path, entries: &[(&str, Vec<u8>)]) -> PathBuf {    fs::create_dir_all(path.parent().unwrap()).unwrap();    let mut writer = zip::ZipWriter::new(fs::File::create(path).unwrap());    let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);    for (name, bytes) in entries {        if let Some(folder) = name.strip_suffix('/') {            writer.add_directory(folder, options).unwrap();        } else {            writer.start_file(*name, options).unwrap();            writer.write_all(bytes).unwrap();        }    }    writer.finish().unwrap();    let file = fs::File::options().write(true).open(path).unwrap();    file.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(ZIP_WRITTEN)).unwrap();    path.to_path_buf()}fn run(object: &Memory, path: &Path) -> Result<PathReport, ImportError> {    let mut said: Vec<Outcome> = Vec::new();    let run = import_path(object, path, TODAY, ZONE, &mut |outcome| said.push(outcome.clone()))?;    assert_eq!(said, run.report.songs, "every file is told as it is answered");    Ok(run)}fn text<'a>(row: &'a serde_json::Map<String, Value>, key: &str) -> &'a str {    row.get(key).and_then(Value::as_str).unwrap_or_default()}fn titles(object: &Memory, table: &str, key: &str) -> Vec<String> {    let mut titles: Vec<String> = object.table(table).iter().map(|row| text(row, key).to_string()).collect();    titles.sort();    titles}// ── the cases ───────────────────────────────────────────────────────────────#[test]fn a_clean_bandcamp_album_zip_is_one_album_with_its_cover_shop_and_day_bought() {    let root = tempfile::tempdir().unwrap();    let s = root.path();    let zip = zip_file(        &s.join("Downloads/Ana Lume - Blue Hour.zip"),        &[            ("Ana Lume - Blue Hour - 01 Dawn.flac", track(s, 1, "Dawn", "Ana Lume", "Blue Hour", Some("Ana Lume"))),            ("Ana Lume - Blue Hour - 02 Noon.flac", track(s, 2, "Noon", "Ana Lume", "Blue Hour", Some("Ana Lume"))),            ("Ana Lume - Blue Hour - 03 Dusk.flac", track(s, 3, "Dusk", "Ana Lume", "Blue Hour", Some("Ana Lume"))),            ("cover.jpg", JPEG.to_vec()),            ("thanks.txt", b"Thank you!\nhttps://analume.bandcamp.com/album/blue-hour?from=fan\n".to_vec()),        ],    );    let object = Memory::new(DB);    let run = run(&object, &zip).unwrap();    assert_eq!(run.report.count("added"), 3);    assert_eq!(run.report.albums_made, 1);    assert_eq!(run.report.covers_sent, 1, "cover.jpg is the album's cover");    assert_eq!(run.report.said, "Ana Lume - Blue Hour.zip came in as Blue Hour.");    assert_eq!(run.report.songs[0].source_path, "Ana Lume - Blue Hour/Ana Lume - Blue Hour - 01 Dawn.flac");    let albums = object.table(ALBUM_TABLE);    assert_eq!(albums.len(), 1);    let album = &albums[0];    assert_eq!(text(album, "title"), "Blue Hour");    assert_eq!(text(album, "artist_name"), "Ana Lume");    assert!(text(album, "cover").starts_with(&format!("{DB}/photos/")));    assert_eq!(text(album, "store_url"), "https://analume.bandcamp.com/album/blue-hour");    assert_eq!(text(album, "store_id"), "bandcamp:analume/blue-hour");    assert_eq!(text(album, "bought_on"), "2026-09-21");    assert!(album.get("booklet").is_none());    let zipped = &run.zips[0];    assert_eq!((zipped.album.as_deref(), zipped.named_from, zipped.refused), (Some("Blue Hour"), Some("tags"), false));    // Run again: every song is here, and nothing the album holds is written over.    let again = self::run(&object, &zip).unwrap();    assert_eq!(again.report.count("here"), 3);    assert_eq!(object.table(ALBUM_TABLE).len(), 1);}#[test]fn a_booklet_pdf_is_kept_as_the_albums_book_file() {    let root = tempfile::tempdir().unwrap();    let s = root.path();    let zip = zip_file(        &s.join("Ana Lume - Tide.zip"),        &[            ("Ana Lume - Tide - 01 Ebb.flac", track(s, 4, "Ebb", "Ana Lume", "Tide", None)),            ("Ana Lume - Tide - 02 Flow.flac", track(s, 5, "Flow", "Ana Lume", "Tide", None)),            ("Tide - booklet.pdf", PDF.to_vec()),            ("cover.jpg", JPEG.to_vec()),        ],    );    let object = Memory::new(DB);    let run = run(&object, &zip).unwrap();    let album = &object.table(ALBUM_TABLE)[0];    let booklet = text(album, "booklet").to_string();    assert!(booklet.starts_with(&format!("{DB}/books/")) && booklet.ends_with(".pdf"), "{booklet}");    assert_eq!(object.media.borrow().get(&booklet), Some(&(PDF.len() as u64, "application/pdf".to_string())));    assert_eq!(run.zips[0].booklet.as_deref(), Some(booklet.as_str()));    assert!(text(album, "store_url").is_empty(), "no note, no shop page");}#[test]fn a_compilation_whose_album_tags_disagree_is_one_album_named_by_the_zip() {    let root = tempfile::tempdir().unwrap();    let s = root.path();    let zip = zip_file(        &s.join("Various Artists - Summer Sampler.zip"),        &[            ("01 Ana - Sun.flac", track(s, 6, "Sun", "Ana", "Summer Sampler (Ana)", Some("Ana"))),            ("02 Bo - Sea.flac", track(s, 7, "Sea", "Bo", "Summer Sampler (Bo)", Some("Bo"))),            ("03 Cy - Sand.flac", track(s, 8, "Sand", "Cy", "Summer Sampler", None)),            ("cover.jpg", JPEG.to_vec()),        ],    );    let object = Memory::new(DB);    let run = run(&object, &zip).unwrap();    assert_eq!(run.report.count("added"), 3);    assert_eq!(run.report.albums_made, 1, "never two albums from one ZIP");    assert_eq!(titles(&object, ALBUM_TABLE, "title"), vec!["Summer Sampler"]);    assert_eq!(titles(&object, ALBUM_TABLE, "artist_name"), vec!["Various Artists"]);    let album_id = text(&object.table(ALBUM_TABLE)[0], "id").to_string();    assert!(object.table(SONG_TABLE).iter().all(|song| text(song, "album") == album_id), "every song is the one album's");    assert_eq!(titles(&object, ARTIST_TABLE, "name"), vec!["Ana", "Bo", "Cy", "Various Artists"]);    assert_eq!(run.zips[0].named_from, Some("zip_disagreeing"));    assert_eq!(        run.report.said,        "Various Artists - Summer Sampler.zip came in as one album, Summer Sampler, though its songs name different albums."    );}#[test]fn a_zip_holding_no_songs_is_refused_in_words() {    let root = tempfile::tempdir().unwrap();    let zip = zip_file(&root.path().join("Empty.zip"), &[("cover.jpg", JPEG.to_vec()), ("read me.txt", b"hello".to_vec())]);    let object = Memory::new(DB);    match run(&object, &zip) {        Err(ImportError::Refused(line)) => assert_eq!(line, "Empty.zip holds no songs."),        other => panic!("refused, not {other:?}"),    }    assert!(object.writes.borrow().is_empty(), "nothing is sent");    let broken = root.path().join("Broken.zip");    fs::write(&broken, b"PK not really a zip").unwrap();    match unpack(&broken).unwrap() {        Err(line) => assert_eq!(line, "Broken.zip could not be opened as a ZIP."),        Ok(_) => panic!("a broken ZIP is refused"),    }}#[test]fn a_nested_folder_is_the_album_and_songs_in_two_folders_are_refused() {    let root = tempfile::tempdir().unwrap();    let s = root.path();    let song = |salt: u8, title: &str| tagged(s, "mp3", mp3(2, salt), &[(ItemKey::TrackTitle, title), (ItemKey::TrackArtist, "Oru"), (ItemKey::AlbumTitle, "Low Tide")]);    let zip = zip_file(        &s.join("Oru - Low Tide.zip"),        &[            ("Oru - Low Tide/", Vec::new()),            ("Oru - Low Tide/01 Shore.mp3", song(9, "Shore")),            ("Oru - Low Tide/02 Reef.mp3", song(10, "Reef")),            ("Oru - Low Tide/folder.jpg", JPEG.to_vec()),            ("__MACOSX/Oru - Low Tide/._01 Shore.mp3", b"fork".to_vec()),            ("../escape.mp3", song(11, "Escape")),        ],    );    let object = Memory::new(DB);    let run = run(&object, &zip).unwrap();    let paths: Vec<&str> = run.report.songs.iter().map(|song| song.source_path.as_str()).collect();    assert_eq!(paths, vec!["Oru - Low Tide/01 Shore.mp3", "Oru - Low Tide/02 Reef.mp3"], "named once, the escaping entry left out");    assert_eq!(titles(&object, ALBUM_TABLE, "title"), vec!["Low Tide"]);    assert!(!text(&object.table(ALBUM_TABLE)[0], "cover").is_empty(), "the folder's folder.jpg");    let two = zip_file(&s.join("Two.zip"), &[("A/01 a.mp3", song(12, "A")), ("B/01 b.mp3", song(13, "B"))]);    match self::run(&Memory::new(DB), &two) {        Err(ImportError::Refused(line)) => assert_eq!(line, "Two.zip holds songs in more than one folder, so it is not one album."),        other => panic!("refused, not {other:?}"),    }}#[test]fn a_zip_met_in_a_walked_folder_comes_in_beside_the_folders_songs() {    let root = tempfile::tempdir().unwrap();    let s = root.path();    let library = s.join("Library");    fs::create_dir_all(library.join("Oru/Shore")).unwrap();    fs::write(library.join("Oru/Shore/01 Wave.flac"), track(s, 14, "Wave", "Oru", "Shore", None)).unwrap();    zip_file(&library.join("Bought/Ana Lume - Blue Hour.zip"), &[("Ana Lume - Blue Hour - 01 Dawn.flac", track(s, 15, "Dawn", "Ana Lume", "Blue Hour", None))]);    zip_file(&library.join("Bought/Nothing.zip"), &[("notes.txt", b"none".to_vec())]);    let object = Memory::new(DB);    let run = run(&object, &library).unwrap();    assert_eq!(run.report.count("added"), 2);    assert_eq!(titles(&object, ALBUM_TABLE, "title"), vec!["Blue Hour", "Shore"]);    let zips: Vec<(&str, bool)> = run.zips.iter().map(|zip| (zip.zip.as_str(), zip.refused)).collect();    assert_eq!(zips, vec![("Ana Lume - Blue Hour.zip", false), ("Nothing.zip", true)], "a ZIP that is no album is said, the run goes on");    assert_eq!(run.zips[1].line, "Nothing.zip holds no songs.");    let bought = object.table(ALBUM_TABLE).into_iter().find(|album| text(album, "title") == "Blue Hour").unwrap();    assert_eq!(text(&bought, "bought_on"), "2026-09-21");}