//! An album ZIP into Music on the phone: the names decide, the entries are//! streamed out, the songs' tags name the one album, and the album's shop,//! day bought and booklet are filled once. Every ZIP here is invented.use std::io::Writeas _;use std::path::{Path, PathBuf};use serde_json::{json, Value};usesuper::*;usecrate::phone::songs::{SongIn, ALBUM_TABLE, SONG_TABLE};usecrate::shell::client::phone_tests::attached;usecrate::shell::client::ClientController;/// A ZIP of `entries` (name, bytes) at `dir/name`.fn zipped(dir: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {let path = dir.join(name);letmut writer = zip::ZipWriter::new(std::fs::File::create(&path).expect("the zip"));for (entry, bytes) in entries { writer.start_file(*entry, zip::write::SimpleFileOptions::default()).expect("an entry"); writer.write_all(bytes).expect("its bytes"); } writer.finish().expect("the zip written"); path}/// Three invented songs, a cover, a one-page booklet, a note naming the shop.fn bandcamp(dir: &Path) -> PathBuf { zipped( dir,"Ana Lume - Blue Hour.zip", &[ ("Ana Lume - Blue Hour - 01 Dawn.flac", b"fLaC invented dawn"), ("Ana Lume - Blue Hour - 02 Noon.flac", b"fLaC invented noon"), ("Ana Lume - Blue Hour - 03 Dusk.flac", b"fLaC invented dusk"), ("cover.jpg", &[0xFF, 0xD8, 0xFF, 0xE0, 0, 0, 0, 0]), ("Blue Hour booklet.pdf", b"%PDF-1.4 invented booklet"), ("about.txt", b"Thanks!\nhttps://analume.bandcamp.com/album/blue-hour?from=fan\n"), ("../outside.mp3", b"ID3 an escape"), ], )}fn opened(zip: &Path, into: &Path) -> Value {let name = zip.file_name().unwrap().to_string_lossy().to_string(); open_in(&json!({ "path": zip, "name": name, "into": into }), Some("Asia/Kolkata")).expect("music.zip answers")}/// The songs `music.zip` streamed out, each with the tags TagLib would read.fn songs_of(opened: &Value, tags: implFn(usize) -> Value) -> Vec<SongIn> { opened["songs"] .as_array() .expect("songs") .iter() .enumerate() .map(|(at, song)| { serde_json::from_value(json!({"path": song["path"], "sourcePath": song["sourcePath"], "entry": song["entry"], "tags": tags(at), "coverPath": opened["coverPath"], })) .expect("a song") }) .collect()}fn zip_in(opened: &Value, name: &str) -> ZipIn { serde_json::from_value(json!({"name": name, "boughtOn": opened["boughtOn"], "storeUrl": opened["storeUrl"], "storeId": opened["storeId"], "bookletPath": opened["bookletPath"], })) .expect("the zip")}fn captured(client: &ClientController, songs: &[SongIn], zip: &ZipIn) -> Value {let layout = client.layout().clone();let written = client.write_rows("music.capture", &mut |ctx| write_zip_album(ctx, &layout, songs, "Asia/Kolkata", zip)).expect("a capture"); written["answer"].clone()}fn albums(client: &ClientController) -> Vec<Value> {crate::phone::records::call(client, "records.list", &json!({"table": ALBUM_TABLE, "limit": 100})).expect("a list")["records"].as_array().cloned().unwrap_or_default()}// RULE (Bandcamp into Music, 7 Nov 2026): a ZIP's album is read from its names alone and only what the album wants is streamed out — its songs, cover, booklet and notes — each under the folder the phone named; an entry whose name escapes that folder is no entry; the shop's page comes from a note and the day bought from the ZIP's own date.#[test]fn a_zips_album_is_streamed_out_entry_by_entry_and_an_escape_is_dropped() {let dir = tempfile::tempdir().expect("a folder");let into = dir.path().join("out");let answer = opened(&bandcamp(dir.path()), &into);let entries: Vec<&str> = answer["songs"].as_array().expect("songs").iter().map(|song| song["entry"].as_str().unwrap_or_default()).collect(); assert_eq!(entries, ["Ana Lume - Blue Hour - 01 Dawn.flac", "Ana Lume - Blue Hour - 02 Noon.flac", "Ana Lume - Blue Hour - 03 Dusk.flac"], "{answer}"); assert_eq!(answer["songs"][0]["sourcePath"], "Ana Lume - Blue Hour/Ana Lume - Blue Hour - 01 Dawn.flac", "a root song is named under the ZIP's own name"); assert_eq!(std::fs::read(answer["songs"][1]["path"].as_str().unwrap()).expect("streamed out"), b"fLaC invented noon"); assert_eq!(answer["coverPath"], json!(into.join("cover.jpg"))); assert_eq!(answer["bookletPath"], json!(into.join("Blue Hour booklet.pdf"))); assert_eq!((answer["storeUrl"].as_str(), answer["storeId"].as_str()), (Some("https://analume.bandcamp.com/album/blue-hour"), Some("bandcamp:analume/blue-hour"))); assert!(answer["boughtOn"].as_str().is_some_and(|day| day.len() == 10), "{answer}"); assert!(!dir.path().join("outside.mp3").exists() && !into.join("../outside.mp3").exists(), "an escaping entry is never written");}// RULE (Bandcamp into Music, 7 Nov 2026): a ZIP holding no songs is no album (it stays what it was), songs in two albums' folders are refused, and bytes that are no ZIP are said as unreadable.#[test]fn a_zip_that_is_no_album_is_refused_in_its_words() {let dir = tempfile::tempdir().expect("a folder");let into = dir.path().join("out");let empty = opened(&zipped(dir.path(), "Photos.zip", &[("a.jpg", b"x"), ("notes.txt", b"y")]), &into); assert_eq!((empty["refused"].as_str(), empty["line"].as_str()), (Some("no_songs"), Some("Photos.zip holds no songs.")));let two = opened(&zipped(dir.path(), "Two.zip", &[("A/01 a.mp3", b"ID3 a"), ("B/01 b.mp3", b"ID3 b")]), &into); assert_eq!(two["refused"], "folders");let junk = dir.path().join("Junk.zip"); std::fs::write(&junk, b"no zip at all").expect("junk"); assert_eq!(opened(&junk, &into)["refused"], "unreadable"); assert!(!into.join("a.jpg").exists(), "nothing comes out of a ZIP that is no album");}// RULE (Bandcamp into Music, 7 Nov 2026): a ZIP's songs land as one album through music.capture, its empty store_url, store_id, bought_on and booklet filled as the Mac's import fills them (the booklet a book file under <db>/books/), and the same ZIP shared again doubles nothing.#[test]fn a_bandcamp_zip_is_one_album_with_its_shop_and_booklet_and_twice_is_once() {let (dir, client) = attached();let opened = opened(&bandcamp(dir.path()), &dir.path().join("out"));let titles = ["Dawn", "Noon", "Dusk"];let tags = |at: usize| json!({"title": (titles[at]), "artist": "Ana Lume", "album": "Blue Hour", "albumArtist": "Ana Lume", "track": at + 1, "duration": 120.0});let zip = zip_in(&opened, "Ana Lume - Blue Hour.zip");let first = captured(&client, &songs_of(&opened, tags), &zip);let outcomes: Vec<&str> = first["songs"].as_array().expect("songs").iter().map(|song| song["outcome"].as_str().unwrap_or_default()).collect(); assert_eq!(outcomes, ["added", "added", "added"], "{first}"); assert_eq!(first["said"], "Ana Lume - Blue Hour.zip came in as Blue Hour.");let held = albums(&client); assert_eq!(held.len(), 1, "{held:?}");let album = &held[0]["data"]; assert_eq!(first["album"], held[0]["id"]); assert_eq!((album["title"].as_str(), album["artist_name"].as_str()), (Some("Blue Hour"), Some("Ana Lume"))); assert_eq!(album["store_url"], "https://analume.bandcamp.com/album/blue-hour"); assert_eq!(album["store_id"], "bandcamp:analume/blue-hour"); assert_eq!(album["bought_on"], opened["boughtOn"]);let booklet = album["booklet"].as_str().expect("the booklet"); assert!(booklet.starts_with(&format!("{}/books/", crate::fixture::WORKSPACE)) && booklet.ends_with(".pdf"), "{booklet}"); assert!(album["cover"].as_str().is_some_and(|cover| !cover.is_empty()), "the ZIP's cover is the album's");let queued = client.with_writer(|replica| Ok(cotton_store::media_ledger::media_by_key(replica.driver, booklet).ok().flatten())).expect("the ledger"); assert_eq!(queued.map(|row| row.content_type), Some("application/pdf".to_string()), "the booklet goes up as a book file");let again = captured(&client, &songs_of(&opened, tags), &zip);let outcomes: Vec<&str> = again["songs"].as_array().expect("songs").iter().map(|song| song["outcome"].as_str().unwrap_or_default()).collect(); assert_eq!(outcomes, ["here", "here", "here"], "{again}"); assert_eq!(albums(&client).len(), 1, "one album still"); assert_eq!(albums(&client)[0]["data"]["booklet"].as_str(), Some(booklet));let songs = crate::phone::records::call(&client, "records.list", &json!({"table": SONG_TABLE, "limit": 100})).expect("songs")["records"].as_array().map(Vec::len); assert_eq!(songs, Some(3), "three songs, none doubled");}// RULE (Bandcamp into Music, 7 Nov 2026): a compilation ZIP whose songs tag each its own album is still one album, named by the ZIP and gathered under its artist, and said so.#[test]fn a_compilation_zip_tagged_track_by_track_is_one_album() {let (dir, client) = attached();let zip = zipped(dir.path(), "Various Artists - Summer Sampler.zip", &[("01 A.mp3", b"ID3 invented a"), ("02 B.mp3", b"ID3 invented b")]);let opened = opened(&zip, &dir.path().join("out"));let tags = |at: usize| json!({"title": (["Sun", "Sea"][at]), "artist": (["Ana", "Bo"][at]), "album": (["Sampler (Ana)", "Sampler (Bo)"][at]), "albumArtist": (["Ana", "Bo"][at])});let answer = captured(&client, &songs_of(&opened, tags), &zip_in(&opened, "Various Artists - Summer Sampler.zip")); assert_eq!(answer["said"], "Various Artists - Summer Sampler.zip came in as one album, Summer Sampler, though its songs name different albums.");let held = albums(&client); assert_eq!(held.len(), 1, "{held:?}"); assert_eq!((held[0]["data"]["title"].as_str(), held[0]["data"]["artist_name"].as_str()), (Some("Summer Sampler"), Some("Various Artists")));}