Cotton code
291 lines · 19.7 KB · RustRaw
//! Cotton Music on this phone: a capture's rows, its duplicates, what this//! device keeps of each song, and the player's door.use serde_json::json;use super::*;use crate::shell::client::phone_tests::attached;/// An invented audio file in the test's folder: bytes that are no real song.fn invented(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf {    let path = dir.join(name.replace('/', "_"));    std::fs::write(&path, bytes).expect("the file");    path}fn song_in(dir: &Path, source_path: &str, bytes: &[u8], tags: Value) -> SongIn {    serde_json::from_value(json!({        "path": invented(dir, source_path, bytes).to_string_lossy(),        "sourcePath": source_path,        "tags": tags,    }))    .expect("a song")}fn captured(client: &ClientController, songs: &[SongIn]) -> Value {    let layout = client.layout().clone();    let written = client.write_rows("music.capture", &mut |ctx| write_songs(ctx, &layout, songs, "Asia/Kolkata")).expect("a capture");    written["answer"].clone()}fn record(client: &ClientController, table: &str, id: &str) -> Value {    crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id})).expect("the record")["data"].clone()}fn listed(client: &ClientController, table: &str) -> Vec<Value> {    crate::phone::records::call(client, "records.list", &json!({"table": table, "limit": 100})).expect("a list")["records"]        .as_array()        .cloned()        .unwrap_or_default()}// RULE (Music definition, 4 Nov 2026): one album's songs come in in one write: each a song row from its tags with its file under `<db>/music/<sha256>.<ext>` and queued up, gathered into one album keyed on album artist and title and one artist row each.#[test]fn an_albums_songs_come_in_as_songs_one_album_and_their_artists() {    let (dir, client) = attached();    let tags = |title: &str, track: u32| json!({"title": title, "artist": "Ana Vell", "album": "Harbour Lights", "albumArtist": "Ana Vell", "track": track, "year": "2019", "genre": "Folk", "duration": 181.5, "bitrate": 320, "sampleRate": 44100});    let songs = [        song_in(dir.path(), "01 Low Tide.mp3", b"ID3 one invented song", tags("Low Tide", 1)),        song_in(dir.path(), "02 The Pier.mp3", b"ID3 two invented song", tags("The Pier", 2)),        song_in(dir.path(), "03 Gulls.mp3", b"ID3 three invented song", json!({"title": "Gulls", "artist": "Ana Vell feat. Oru", "album": "Harbour Lights", "albumArtist": "Ana Vell", "track": 3, "duration": 200.0})),    ];    let answer = captured(&client, &songs);    let outcomes: Vec<&str> = answer["songs"].as_array().expect("songs").iter().map(|song| song["outcome"].as_str().unwrap_or_default()).collect();    assert_eq!(outcomes, ["added", "added", "added"], "{answer}");    assert_eq!(answer["said"], "3 songs came in.");    let first = &answer["songs"][0];    let key = first["key"].as_str().expect("its key");    assert!(key.starts_with(&format!("{}/music/", crate::fixture::WORKSPACE)) && key.ends_with(".mp3"), "{key}");    let song = record(&client, SONG_TABLE, first["id"].as_str().expect("its id"));    assert_eq!((song["title"].as_str(), song["artist_name"].as_str(), song["format"].as_str(), song["source"].as_str()), (Some("Low Tide"), Some("Ana Vell"), Some("mp3"), Some("file")));    assert_eq!((song["track_number"].as_i64(), song["year"].as_str(), song["bitrate"].as_i64()), (Some(1), Some("2019"), Some(320)));    assert_eq!(song["file"], json!(key));    assert_eq!(song["album_title"], "Harbour Lights");    let albums = listed(&client, ALBUM_TABLE);    assert_eq!(albums.len(), 1, "one album, its songs gathered: {albums:?}");    assert_eq!(albums[0]["data"]["artist_name"], "Ana Vell");    let artists: Vec<String> = listed(&client, ARTIST_TABLE).iter().map(|artist| artist["data"]["name"].as_str().unwrap_or_default().to_string()).collect();    assert_eq!(artists, ["Ana Vell"], "a featured credit is the primary artist's song");    let queued = client.with_writer(|replica| Ok(cotton_store::media_ledger::media_by_key(replica.driver, key).ok().flatten())).expect("the ledger");    assert_eq!(queued.map(|row| row.content_type), Some("audio/mpeg".to_string()), "queued to go up as a song");}// RULE (Music definition, 4 Nov 2026): the same bytes twice is already here; the same song in two formats is one song, the better file kept and the worse said.#[test]fn the_same_file_is_already_here_and_the_better_of_two_formats_is_kept() {    let (dir, client) = attached();    let tags = json!({"title": "Low Tide", "artist": "Ana Vell", "album": "Harbour Lights", "duration": 181.0, "bitrate": 192});    let mp3 = song_in(dir.path(), "Low Tide.mp3", b"ID3 the invented mp3", tags.clone());    let first = captured(&client, std::slice::from_ref(&mp3));    let id = first["songs"][0]["id"].as_str().expect("an id").to_string();    let again = captured(&client, &[mp3]);    assert_eq!((again["songs"][0]["outcome"].as_str(), again["said"].as_str()), (Some("here"), Some("Low Tide is already here.")));    let mut lossless = tags.clone();    lossless["duration"] = json!(182.4);    lossless["bitrate"] = json!(900);    let flac = captured(&client, &[song_in(dir.path(), "Low Tide.flac", b"fLaC the invented flac", lossless)]);    let kept = &flac["songs"][0];    assert_eq!((kept["outcome"].as_str(), kept["id"].as_str()), (Some("better"), Some(id.as_str())), "{flac}");    assert_eq!(kept["line"], "Kept the better file of Low Tide. The MP3 it replaced can go.");    let song = record(&client, SONG_TABLE, &id);    assert_eq!((song["format"].as_str(), song["file"].as_str()), (Some("flac"), kept["key"].as_str()));    let worse = captured(&client, &[song_in(dir.path(), "Low Tide.m4a", b"the invented aac", json!({"title": "Low Tide", "artist": "Ana Vell", "album": "Harbour Lights", "duration": 181.0, "bitrate": 256}))]);    assert_eq!(worse["songs"][0]["outcome"], "worse");    assert_eq!(listed(&client, SONG_TABLE).len(), 1, "one song in all");}// RULE (Music, 7 Nov 2026): a song's file added on this phone is kept on it, as a book's is (6e8eee54aa), whether it makes a song or its bytes are one the object already holds: kept, its file on this phone for the player, signed in or not.#[test]fn a_songs_file_added_here_is_kept_here_even_when_the_object_held_the_song() {    let (dir, client) = attached();    let tags = json!({"title": "Low Tide", "artist": "Ana Vell", "album": "Harbour Lights", "duration": 181.0});    let path = |key: &str| client.with_file(|f| Ok(super::super::media::local_path_of(f.driver, key))).expect("the ledger reads");    let kept = |key: &str| read(&client, &json!({"key": key})).expect("what this phone keeps")["state"].clone();    let added = capture(&client, &json!({"songs": [{"path": invented(dir.path(), "a.mp3", b"ID3 an added song").to_string_lossy(), "sourcePath": "Ana Vell/Harbour Lights/01 Low Tide.mp3", "tags": tags}]})).expect("a capture");    let key = added["songs"][0]["key"].as_str().expect("its key").to_string();    assert_eq!((added["songs"][0]["outcome"].as_str(), kept(&key)), (Some("added"), json!(KEPT)));    assert!(path(&key).is_some_and(|at| at.is_file()), "its file is on this phone");    // The object's song: its row came down, its file is not on this phone.    let bytes: &[u8] = b"ID3 the object's song";    let theirs = client        .write_rows("sync", &mut |ctx| {            let key = song_key(ctx.file.id(), &hex::encode(<sha2::Sha256 as sha2::Digest>::digest(bytes)), "mp3");            made(ctx, SONG_TABLE, Map::from_iter([("title".to_string(), json!("The Pier")), ("file".to_string(), json!(key)), ("format".to_string(), json!("mp3"))]))?;            Ok(json!(key))        })        .expect("the object's row")["answer"]        .as_str()        .expect("its key")        .to_string();    assert_eq!((kept(&theirs), path(&theirs)), (Value::Null, None), "not on this phone yet");    let again = capture(&client, &json!({"songs": [{"path": invented(dir.path(), "b.mp3", bytes).to_string_lossy(), "sourcePath": "The Pier.mp3", "tags": {"title": "The Pier"}}]})).expect("a capture");    assert_eq!((again["songs"][0]["outcome"].as_str(), again["songs"][0]["key"].as_str()), (Some("here"), Some(theirs.as_str())), "{again}");    assert_eq!(kept(&theirs), json!(KEPT), "brought in here, so kept here");    assert!(path(&theirs).is_some_and(|at| at.is_file()), "and the player plays it from this phone");    let song = listed(&client, SONG_TABLE).into_iter().find(|song| song["data"]["file"] == json!(theirs)).expect("the song");    assert_eq!(song["data"][ON_PHONE], json!(KEPT), "{song}");}// RULE (Music definition, 4 Nov 2026): a file with no tags takes its row from its folder and name, and a file that is no song is refused by its line.#[test]fn a_song_with_no_tags_reads_its_folder_and_a_file_that_is_no_song_is_refused() {    let (dir, client) = attached();    let answer = captured(&client, &[        song_in(dir.path(), "The Paper Lanterns/Night Ferry (2021)/04 Lamps.flac", b"fLaC a bare invented song", json!({})),        song_in(dir.path(), "The Paper Lanterns/Night Ferry (2021)/notes.txt", b"words", json!({})),    ]);    assert_eq!(answer["songs"][1]["outcome"], "refused");    assert_eq!(answer["songs"][1]["line"], "notes.txt is not a song Cotton can play.");    let song = record(&client, SONG_TABLE, answer["songs"][0]["id"].as_str().expect("an id"));    assert_eq!((song["title"].as_str(), song["artist_name"].as_str(), song["track_number"].as_i64(), song["year"].as_str(), song["source"].as_str()), (Some("Lamps"), Some("The Paper Lanterns"), Some(4), Some("2021"), Some("folder")));    let artist = &listed(&client, ARTIST_TABLE)[0]["data"];    assert_eq!((artist["name"].as_str(), artist["sort_name"].as_str()), (Some("The Paper Lanterns"), Some("Paper Lanterns")));}// RULE: a song's and an album's `on_phone` are this phone's answer: a song brought in here is kept, an album says it from its songs.#[test]fn what_this_phone_keeps_is_answered_on_songs_and_their_albums() {    let (dir, client) = attached();    let tags = |title: &str| json!({"title": title, "artist": "Ana Vell", "album": "Harbour Lights", "duration": 100.0});    let layout = client.layout().clone();    let answer = client        .write_rows("music.capture", &mut |ctx| write_songs(ctx, &layout, &[song_in(dir.path(), "a.mp3", b"ID3 a", tags("A")), song_in(dir.path(), "b.mp3", b"ID3 b", tags("B"))], "Asia/Kolkata"))        .expect("a capture")["answer"]        .clone();    let (a, b) = (answer["songs"][0]["key"].as_str().unwrap().to_string(), answer["songs"][1]["key"].as_str().unwrap().to_string());    let songs = |client: &ClientController| listed(client, SONG_TABLE).iter().map(|song| song["data"][ON_PHONE].as_str().unwrap_or_default().to_string()).collect::<Vec<_>>();    let album = |client: &ClientController| listed(client, ALBUM_TABLE)[0]["data"][ON_PHONE].as_str().unwrap_or_default().to_string();    assert_eq!(songs(&client), [ABSENT, ABSENT]);    assert_eq!(album(&client), ABSENT);    write(&client, &json!({"key": a, "state": KEEPING})).expect("keeping");    assert_eq!(album(&client), SOME);    write(&client, &json!({"key": b, "state": KEEPING})).expect("keeping");    assert_eq!(album(&client), KEEPING);    assert_eq!(album_state([Some(KEPT), Some(KEPT)]), KEPT);    assert_eq!(album_state([Some(KEPT), None]), SOME);    assert_eq!(album_state(std::iter::empty()), ABSENT);    let mut only_kept = Map::new();    only_kept.insert("table".into(), json!(SONG_TABLE));    only_kept.insert("where".into(), json!({"on_phone": ["kept"]}));    narrow_where(&client, &mut only_kept).expect("narrowed");    assert_eq!(only_kept["where"]["file"], json!([NOTHING_KEPT]), "nothing kept yet, so nothing is listed");}// RULE (Music definition, 4 Nov 2026): Keep everything is a fact of this phone alone, read and set.#[test]fn keep_everything_is_this_phones_own() {    let (_dir, client) = attached();    assert_eq!(keep_everything(&client, &json!({})).expect("read"), json!({"on": false}));    let set = keep_everything(&client, &json!({"on": true})).expect("set");    assert_eq!((set["on"].as_bool(), set["said"].as_str()), (Some(true), Some("Every song stays on this phone.")));    assert!(keeps_everything(&client).expect("read"));    assert_eq!(keep_everything(&client, &json!({"on": "yes"})).expect_err("refused").code, "bad_request");}// RULE (Music definition, 4 Nov 2026): an album's Find details is the phone's lookup, and only an album's.#[test]fn find_details_is_the_phones() {    let (dir, client) = attached();    let answer = captured(&client, &[song_in(dir.path(), "a.mp3", b"ID3 a", json!({"title": "A", "artist": "Ana Vell", "album": "Harbour Lights"}))]);    let id = answer["songs"][0]["id"].as_str().unwrap().to_string();    let album = listed(&client, ALBUM_TABLE)[0]["id"].as_str().unwrap().to_string();    assert_eq!(find_details(&client, &json!({"table": ALBUM_TABLE, "id": album})).expect("an answer"), json!({"platform_action": "find_details", "table": ALBUM_TABLE, "id": album}));    assert!(find_details(&client, &json!({"table": SONG_TABLE, "id": id})).is_err(), "an album's alone");}// RULE: the primary artist of a credit is the name before its featured artists.#[test]fn a_featured_credit_is_its_primary_artists_song() {    assert_eq!(primary_artist("Ana Vell feat. Oru"), "Ana Vell");    assert_eq!(primary_artist("Ana Vell ft. Oru & Lin"), "Ana Vell");    assert_eq!(primary_artist("Simon & Garfunkel"), "Simon & Garfunkel");}// RULE (Music definition, 4 Nov 2026): a lookup fills only what is empty, stamps each column it filled, and fills nothing it may not.#[test]fn a_lookup_fills_only_the_empty_columns_and_stamps_each_fill() {    let (dir, client) = attached();    let tags = json!({"title": "Low Tide", "artist": "Ana Vell", "album": "Harbour Lights", "year": "2019", "duration": 181.0});    let song = captured(&client, &[song_in(dir.path(), "Low Tide.mp3", b"ID3 the invented mp3", tags)]);    let id = song["songs"][0]["id"].as_str().expect("an id").to_string();    let album = record(&client, SONG_TABLE, &id)["album"].as_str().expect("its album").to_string();    let cover = invented(dir.path(), "front.jpg", b"the invented cover");    let filled = fill(        &client,        &json!({"table": ALBUM_TABLE, "id": album, "from": "musicbrainz", "fields": {"year": "1999", "mb_release": "rel-1"}, "coverPath": cover.to_string_lossy()}),    )    .expect("a fill");    let mut said: Vec<String> = filled["filled"].as_array().expect("filled").iter().map(|key| key.as_str().unwrap_or_default().to_string()).collect();    said.sort();    assert_eq!(said, ["cover", "mb_release"], "the year the tags gave stays");    let held = record(&client, ALBUM_TABLE, &album);    assert_eq!((held["year"].as_str(), held["mb_release"].as_str()), (Some("2019"), Some("rel-1")));    assert!(held["cover"].as_str().is_some_and(|key| !key.is_empty()), "the fetched cover is kept");    let stamps: Value = serde_json::from_str(held["filled_from"].as_str().expect("stamped")).expect("json stamps");    assert_eq!(stamps["mb_release"], "musicbrainz");    assert!(stamps.get("year").is_none(), "nothing filled, nothing stamped");    let again = fill(&client, &json!({"table": ALBUM_TABLE, "id": album, "from": "itunes", "fields": {"mb_release": "rel-2"}})).expect("a second fill");    assert_eq!(again["filled"], json!([]), "a filled column stays filled");    for wrong in [        json!({"table": ALBUM_TABLE, "id": album, "from": "musicbrainz", "fields": {"title": "Another"}}),        json!({"table": SONG_TABLE, "id": id, "from": "musicbrainz", "fields": {"cover": "x"}}),        json!({"table": ARTIST_TABLE, "id": album, "from": "musicbrainz", "fields": {}}),        json!({"table": ALBUM_TABLE, "id": album, "from": "somewhere", "fields": {}}),    ] {        assert_eq!(fill(&client, &wrong).expect_err("refused").code, "bad_request", "{wrong}");    }}// RULE (open standards, 7 Nov 2026): a playlist file Add a folder found is a list of the songs it names, by the rule music:import uses (cotton_core::music::m3u): named after its file, found by relative path then by name, the rest counted; a list held by that name only grows.#[test]fn a_folders_playlist_is_a_list_of_its_songs_and_a_held_one_only_grows() {    let (dir, client) = attached();    let tags = |title: &str| json!({"title": title, "artist": "Ana Vell", "album": "Two Rooms"});    let songs = [        song_in(dir.path(), "Music/Ana Vell/Two Rooms/01 Low Tide.mp3", b"ID3 low tide invented", tags("Low Tide")),        song_in(dir.path(), "Music/Ana Vell/Two Rooms/02 Morning.mp3", b"ID3 morning invented", tags("Morning")),    ];    let captured = captured(&client, &songs);    let id_of = |at: usize| captured["songs"][at]["id"].as_str().expect("an id").to_string();    let first = call_lists(&client, "../Ana Vell/Two Rooms/02 Morning.mp3\n#EXTINF:1,Not It\n../Gone/x.mp3\n");    assert_eq!((first["made"].as_bool(), first["appended"].as_u64(), first["skipped"].as_u64(), first["name"].as_str()), (Some(true), Some(1), Some(1), Some("Night")));    let list = first["id"].as_str().expect("the list").to_string();    let again = call_lists(&client, "C:\\Old\\01 Low Tide.mp3\n../Ana Vell/Two Rooms/02 Morning.mp3\n");    assert_eq!((again["id"].as_str(), again["made"].as_bool(), again["appended"].as_u64()), (Some(list.as_str()), Some(false), Some(1)));    let order = client        .write_rows("members", &mut |ctx| cotton_tools::mcp::handlers::tables::groups::member_order(ctx, &list).map(|order| json!(order)).map_err(|failure| failure.to_string()))        .expect("the members");    assert_eq!(order["answer"], json!([id_of(1), id_of(0)]), "appended after what it held, nothing moved");}fn call_lists(client: &ClientController, text: &str) -> Value {    let answer = lists(client, &json!({"lists": [{"sourcePath": "Music/playlists/Night.m3u8", "text": text}]})).expect("the lists");    answer["lists"][0].clone()}// RULE (Cotton Music on Android, 12 Nov 2026): what a keep, a Remove download and Keep everything's sweep touch is the core's, never a shell's: a keep's files not here, a removal's files here, the sweep's every file not here while Keep everything is on.#[test]fn a_keep_plan_names_the_files_a_move_touches() {    let (dir, client) = attached();    let tags = |title: &str| json!({"title": title, "artist": "Ana Vell", "album": "Harbour Lights", "duration": 100.0});    let answer = captured(&client, &[song_in(dir.path(), "a.mp3", b"ID3 a", tags("A")), song_in(dir.path(), "b.mp3", b"ID3 b", tags("B"))]);    let key = |at: usize| answer["songs"][at]["key"].as_str().unwrap().to_string();    let song = answer["songs"][0]["id"].as_str().unwrap().to_string();    let album = listed(&client, ALBUM_TABLE)[0]["id"].as_str().unwrap().to_string();    let plan = |request: Value| keep_plan(&client, &request).expect("a plan")["keys"].clone();    let mut both = vec![key(0), key(1)];    both.sort();    assert_eq!(plan(json!({"op": "keep", "table": SONG_TABLE, "id": song})), json!([key(0)]));    assert_eq!(plan(json!({"op": "keep", "table": ALBUM_TABLE, "id": album})), json!(both));    assert_eq!(plan(json!({"op": "remove", "table": ALBUM_TABLE, "id": album})), json!([]), "nothing here to let go");    assert_eq!(plan(json!({"op": "sweep"})), json!([]), "Keep everything is off");    write(&client, &json!({"key": key(0), "state": KEEPING})).expect("keeping");    assert_eq!(plan(json!({"op": "keep", "table": ALBUM_TABLE, "id": album})), json!([key(1)]), "a song coming down is not fetched twice");    assert_eq!(plan(json!({"op": "remove", "table": ALBUM_TABLE, "id": album})), json!([key(0)]));    keep_everything(&client, &json!({"on": true})).expect("on");    assert_eq!(plan(json!({"op": "sweep"})), json!([key(1)]));    assert_eq!(keep_plan(&client, &json!({"op": "keep", "table": "artist", "id": "x"})).expect_err("refused").code, "bad_request");    assert_eq!(keep_plan(&client, &json!({"op": "hold"})).expect_err("refused").code, "bad_request");}