278 lines · 16.3 KB · RustRaw
//! A synthetic library for the open bundle ([`crate::open_bundle`]): the rows//! of each kit and the bytes they name, and the tree each kit lays from them.//! The store's own open-bundle tests and the phone's `package.export_open`//! tests lay from the same rows and expect the same trees, so there is one//! expected tree per kit, here.//!//! The rows are written into any copy holding the personal kit's tables, as//! database `ws`; the bytes go on a [`Shelf`], which a test hands to the//! bundle as its media source or lays into its own media store.use std::collections::BTreeMap;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use crate::cottonpkg::MediaSource;use crate::driver::Driver;use crate::fixtures::NOW;/// Bytes by media key.#[derive(Default)]pub struct Shelf(pub BTreeMap<String, Vec<u8>>);impl Shelf { /// Hold `bytes` under `key`, and answer the key. pub fn hold(&mut self, key: &str, bytes: &[u8]) -> String { self.0.insert(key.to_string(), bytes.to_vec()); key.to_string() }}impl MediaSource for Shelf { fn read(&mut self, key: &str) -> crate::Result<Option<Vec<u8>>> { Ok(self.0.get(key).cloned()) }}/// A content-addressed key in database `ws`: `<ws>/<folder>/<fill × 64>.<ext>`.pub fn key(ws: &str, folder: &str, fill: char, ext: &str) -> String { format!("{ws}/{folder}/{}.{ext}", fill.to_string().repeat(64))}/// One row of table `cotton_<id>` in database `ws`, its values in their/// domain form: a kit table, or a list's table the build compiles (`groups`,/// `group_members`), where every copy keeps lists.pub fn put(db: &Driver, ws: &str, id: &str, row: Value) { let mut row = row.as_object().expect("an object").clone(); row.entry("workspace_id").or_insert(json!(ws)); row.entry("created_at").or_insert(json!(NOW)); row.entry("updated_at").or_insert(json!(NOW)); let columns: Vec<String> = row.keys().map(|column| format!("\"{column}\"")).collect(); let values: Vec<SqlValue> = row .values() .map(|value| match value { Value::String(s) => SqlValue::Text(s.clone()), Value::Bool(b) => SqlValue::Integer(i64::from(*b)), Value::Number(n) if n.is_i64() => SqlValue::Integer(n.as_i64().unwrap_or_default()), Value::Number(n) => SqlValue::Real(n.as_f64().unwrap_or_default()), Value::Null => SqlValue::Null, other => SqlValue::Text(other.to_string()), }) .collect(); let sql = format!("INSERT INTO cotton_{id} ({}) VALUES ({})", columns.join(", "), vec!["?"; values.len()].join(", ")); db.run(&sql, &values).unwrap_or_else(|error| panic!("{id}: {error}"));}// ── Books ────────────────────────────────────────────────────────────────pub const EPUB: &[u8] = b"PK not really an epub";pub const PDF: &[u8] = b"%PDF not really a pdf";pub const JPEG: &[u8] = b"\xFF\xD8 not really a jpeg";pub fn shelf_of_books(db: &Driver, ws: &str, shelf: &mut Shelf) { let epub = shelf.hold(&key(ws, "books", 'a', "epub"), EPUB); let cover = shelf.hold(&key(ws, "photos", 'c', "jpg"), JPEG); let pdf = shelf.hold(&key(ws, "books", 'b', "pdf"), PDF); put(db, ws, "book", json!({ "id": "book-1", "title": "Harbour Lights", "author": "Ana Vell", "file": epub, "cover": cover, "format": "epub", "status": "finished", "rating": 4, "review": "Quiet, \"salty\", good.", "added_on": "2026-08-01", "finished_on": "2026-09-12", "read_count": 1, "pages": 312, "series": "Lantern Cycle", "series_number": 2, "year": "2019", "language": "en", "isbn": "0-14-143951-3", "ol_work": "OL1W", "goodreads_id": "77", })); put(db, ws, "book", json!({ "id": "book-2", "title": "Two Rooms: A Novel", "author": "ana vell", "file": pdf, "format": "pdf", "status": "reading", "isbn": "9780000000002", })); // The same author and title again, with no file: its own folder, no acquisition. put(db, ws, "book", json!({"id": "book-3", "title": "Harbour Lights", "author": "Ana Vell", "status": "want_to_read"})); // A file whose bytes this holder does not have. put(db, ws, "book", json!({"id": "book-4", "title": "Lost Pages", "file": key(ws, "books", 'd', "epub"), "status": "stopped"})); put(db, ws, "book", json!({"id": "book-5", "title": "Binned", "author": "Ana Vell", "deleted_at": NOW})); put(db, ws, "highlight", json!({ "id": "hl-2", "book": "book-1", "text": "The tide\nwent out.", "note": "Twice!", "progress": 0.5, "chapter": "Low Water", "page_label": "41", "made_at": "2026-09-02", "locator": "{\"href\":\"ch3.xhtml\",\"locations\":{\"progression\":0.2},\"text\":{\"before\":\"At dusk \",\"highlight\":\"The tide went out.\",\"after\":\" Then\"}}", })); put(db, ws, "highlight", json!({"id": "hl-1", "book": "book-1", "text": "Lamps came on.", "progress": 0.1, "made_at": "2026-09-01"})); put(db, ws, "highlight", json!({ "id": "hl-3", "book": "book-2", "text": "A door.", "progress": 0.3, "locator": "{\"href\":\"book.pdf\",\"locations\":{\"fragments\":[\"page=7\"]}}", }));}pub const FLAC: &[u8] = b"fLaC not really flac";pub const M4A: &[u8] = b"ftyp not really m4a";pub const MP3: &[u8] = b"ID3 not really mp3";pub const OPUS: &[u8] = b"OggS not really opus";pub const PNG: &[u8] = b"\x89PNG not really png";pub fn a_record_collection(db: &Driver, ws: &str, shelf: &mut Shelf) { put(db, ws, "artist", json!({"id": "art-1", "name": "The Paper Lanterns", "mb_artist": "mb-art-1"})); put(db, ws, "music_album", json!({ "id": "alb-1", "title": "Harbour Lights", "artist": "art-1", "artist_name": "The Paper Lanterns", "cover": shelf.hold(&key(ws, "photos", 'e', "jpg"), JPEG), "mb_release": "mb-rel-1", "discs": 1, })); put(db, ws, "music_album", json!({"id": "alb-2", "title": "Two Rooms", "artist_name": "Ana Vell", "discs": 2})); put(db, ws, "song", json!({ "id": "s1", "title": "Low Tide", "artist": "art-1", "artist_name": "The Paper Lanterns", "album": "alb-1", "track_number": 3, "duration": 203.4, "mb_recording": "mb-rec-1", "file": shelf.hold(&key(ws, "songs", 'f', "flac"), FLAC), })); put(db, ws, "song", json!({ "id": "s2", "title": "Lamps", "artist": "art-1", "artist_name": "The Paper Lanterns", "album": "alb-1", "track_number": 1, "duration": 180, "file": shelf.hold(&key(ws, "songs", 'g', "m4a"), M4A), })); put(db, ws, "song", json!({ "id": "s3", "title": "The Stair", "artist_name": "Ana Vell", "album": "alb-2", "disc_number": 1, "track_number": 4, "duration": 150, "file": shelf.hold(&key(ws, "songs", 'h', "mp3"), MP3), })); // The album has no cover: its song's cover is the folder's. put(db, ws, "song", json!({ "id": "s4", "title": "Up: Down?", "artist_name": "Ana Vell", "album": "alb-2", "disc_number": 2, "track_number": 1, "file": shelf.hold(&key(ws, "songs", 'i', "opus"), OPUS), "cover": shelf.hold(&key(ws, "photos", 'j', "png"), PNG), })); // Bytes this holder lacks, and a song with no file at all. put(db, ws, "song", json!({"id": "s5", "title": "Night Mix", "artist_name": "Oru", "file": key(ws, "songs", 'k', "flac")})); put(db, ws, "song", json!({"id": "s6", "title": "Typed In", "artist_name": "Oru"})); put(db, ws, "groups", json!({"id": "rg-1", "table_id": "song", "name": "Road Trip", "position": 1})); put(db, ws, "groups", json!({"id": "rg-2", "table_id": "book", "name": "Not songs", "position": 0})); put(db, ws, "group_members", json!({"id": "gm-1", "group_id": "rg-1", "record_id": "s1", "place": 2})); put(db, ws, "group_members", json!({"id": "gm-2", "group_id": "rg-1", "record_id": "s3", "place": 1})); put(db, ws, "group_members", json!({"id": "gm-3", "group_id": "rg-1", "record_id": "s5", "place": 3})); put(db, ws, "listen", json!({"id": "l1", "song": "s1", "title": "Low Tide", "artist_name": "The Paper Lanterns", "played_at": "2026-09-01T10:00:00.000Z", "seconds": 203, "ended": "finished"})); put(db, ws, "listen", json!({"id": "l2", "song": "s2", "title": "Lamps", "played_at": "2026-09-01T11:00:00.000Z", "seconds": 30, "ended": "stopped"})); put(db, ws, "listen", json!({"id": "l3", "song": "s2", "played_at": "2026-08-31T09:00:00.000Z", "seconds": 95, "ended": "skipped"})); put(db, ws, "listen", json!({"id": "l4", "title": "Radio Song", "artist_name": "Someone", "played_at": "2026-09-02", "seconds": 250, "ended": "stopped"}));}pub const MP4: &[u8] = b"\x00\x00\x00\x18ftypmp42 not really a film";pub const MKV: &[u8] = b"\x1A\x45\xDF\xA3 not really a source";pub const MASTER: &str = "#EXTM3U\n\#EXT-X-VERSION:7\n\#EXT-X-INDEPENDENT-SEGMENTS\n\#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"audio\",NAME=\"English\",LANGUAGE=\"en\",DEFAULT=YES,AUTOSELECT=YES,CHANNELS=\"2\",URI=\"audio-1/index.m3u8\"\n\#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"English\",LANGUAGE=\"en\",DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,URI=\"sub-en.m3u8\"\n\#EXT-X-STREAM-INF:BANDWIDTH=1,AVERAGE-BANDWIDTH=1,CODECS=\"avc1.640028,mp4a.40.2\",RESOLUTION=1920x1080,AUDIO=\"audio\",SUBTITLES=\"subs\"\n\video/index.m3u8\n";pub const MEDIA: &str = "#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:6\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:6.000,\nseg00000.m4s\n#EXT-X-ENDLIST\n";pub const SUBS: &str = "#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6.000,\nsub-en.vtt\n#EXT-X-ENDLIST\n";pub const VTT: &str = "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:0,LOCAL:00:00:00.000\n\n00:00:01.000 --> 00:00:02.000\nHello.\n";/// Two films (one whole file, one HLS stream), a series of two episodes (one/// whole, one waiting for the Mac), and a watch log.pub fn a_film_shelf(db: &Driver, ws: &str, shelf: &mut Shelf) { let whole = shelf.hold(&format!("{ws}/films/f1/whole.mp4"), MP4); let poster = shelf.hold(&key(ws, "photos", 'p', "jpg"), JPEG); let fanart = shelf.hold(&key(ws, "photos", 'f', "jpg"), JPEG); put(db, ws, "film", json!({ "id": "f1", "title": "Night Ferry", "year": "2019", "kind": "film", "status": "watched", "file": whole, "poster": poster, "backdrop": fanart, "original_title": "Nachtfähre", "synopsis": "A ferry & a night.", "minutes": 104, "certificate": "UA", "genres": "Drama, Mystery", "director": "Mara Quill", "cast": "Iris Calder, Tom Vey", "country": "United Kingdom", "rating": 4, "tmdb_id": "900101", "imdb_id": "tt0000101", "tvdb_id": "5501", })); let hls = format!("{ws}/films/f2"); for (file, bytes) in [ ("master.m3u8", MASTER.as_bytes()), ("video/index.m3u8", MEDIA.as_bytes()), ("video/init.mp4", b"video init".as_slice()), ("video/seg00000.m4s", b"video segment".as_slice()), ("audio-1/index.m3u8", MEDIA.as_bytes()), ("audio-1/init.mp4", b"audio init".as_slice()), ("audio-1/seg00000.m4s", b"audio segment".as_slice()), ("sub-en.m3u8", SUBS.as_bytes()), ("sub-en.vtt", VTT.as_bytes()), ] { shelf.hold(&format!("{hls}/{file}"), bytes); } // Its poster's bytes are not on the shelf. put(db, ws, "film", json!({"id": "f2", "title": "Dust Signals", "year": "2011", "kind": "film", "status": "want_to_watch", "file": format!("{hls}/master.m3u8"), "poster": key(ws, "photos", 'q', "jpg")})); let series_poster = shelf.hold(&key(ws, "photos", 's', "jpg"), JPEG); let season_poster = shelf.hold(&key(ws, "photos", 't', "jpg"), JPEG); put(db, ws, "film", json!({"id": "s1", "title": "Lowmarsh", "year": "2021", "kind": "series", "status": "watching", "poster": series_poster, "synopsis": "A town under water.", "tvdb_id": "440011", "tmdb_id": "880011"})); put(db, ws, "film_season", json!({"id": "se1", "film": "s1", "number": 1, "title": "Season 1", "poster": season_poster})); let pilot = shelf.hold(&format!("{ws}/films/e1/whole.mp4"), MP4); let still = shelf.hold(&key(ws, "photos", 'e', "jpg"), JPEG); put(db, ws, "film_episode", json!({"id": "e1", "series": "s1", "season": "se1", "number": 1, "title": "Pilot", "file": pilot, "still": still, "minutes": 48, "aired": "2021-09-01", "tvdb_id": "9900101"})); let source = shelf.hold(&format!("{ws}/films/e2/source.mkv"), MKV); put(db, ws, "film_episode", json!({"id": "e2", "series": "s1", "season": "se1", "number": 2, "title": "Cicadas", "source_file": source, "needs_mac": true})); put(db, ws, "watch", json!({"id": "w1", "film": "f1", "started_at": "2026-10-01T20:00:00.000Z", "seconds": 6240, "finished": true})); put(db, ws, "watch", json!({"id": "w2", "film": "f1", "started_at": "2026-10-20T21:30:00.000Z", "seconds": 6240, "finished": true})); put(db, ws, "watch", json!({"id": "w3", "film": "s1", "episode": "e1", "started_at": "2026-10-05T19:00:00.000+05:30", "seconds": 2880, "finished": true})); put(db, ws, "watch", json!({"id": "w4", "film": "s1", "episode": "e2", "started_at": "2026-10-06T19:00:00.000Z", "seconds": 300, "finished": false}));}// ── The trees ────────────────────────────────────────────────────────────/// What [`shelf_of_books`] lays.pub const BOOKS_TREE: &[&str] = &[ "Books/Ana Vell/Harbour Lights (2)/metadata.opf", "Books/Ana Vell/Harbour Lights/Harbour Lights.epub", "Books/Ana Vell/Harbour Lights/Harbour Lights.highlights.jsonld", "Books/Ana Vell/Harbour Lights/Harbour Lights.highlights.md", "Books/Ana Vell/Harbour Lights/cover.jpg", "Books/Ana Vell/Harbour Lights/metadata.opf", "Books/Ana Vell/Two Rooms_ A Novel/Two Rooms_ A Novel.highlights.jsonld", "Books/Ana Vell/Two Rooms_ A Novel/Two Rooms_ A Novel.highlights.md", "Books/Ana Vell/Two Rooms_ A Novel/Two Rooms_ A Novel.pdf", "Books/Ana Vell/Two Rooms_ A Novel/metadata.opf", "Books/Unknown Author/Lost Pages/metadata.opf", "Books/catalog.json", "Books/catalog.xml", "Books/goodreads.csv",];/// The keys [`shelf_of_books`] names and leaves off the shelf.pub fn books_missing(ws: &str) -> Vec<String> { vec![key(ws, "books", 'd', "epub")]}/// What [`a_record_collection`] lays.pub const MUSIC_TREE: &[&str] = &[ "Music/Ana Vell/Two Rooms/1-04 The Stair.mp3", "Music/Ana Vell/Two Rooms/2-01 Up_ Down_.opus", "Music/Ana Vell/Two Rooms/cover.png", "Music/The Paper Lanterns/Harbour Lights/01 Lamps.m4a", "Music/The Paper Lanterns/Harbour Lights/03 Low Tide.flac", "Music/The Paper Lanterns/Harbour Lights/cover.jpg", "Music/listens.jsonl", "Music/playlists/Road Trip.m3u8",];/// The keys [`a_record_collection`] names and leaves off the shelf.pub fn music_missing(ws: &str) -> Vec<String> { vec![key(ws, "songs", 'k', "flac")]}/// What [`a_film_shelf`] lays.pub const FILMS_TREE: &[&str] = &[ "Films/Dust Signals (2011)/Dust Signals (2011).en.vtt", "Films/Dust Signals (2011)/Dust Signals (2011).hls/audio-1/index.m3u8", "Films/Dust Signals (2011)/Dust Signals (2011).hls/audio-1/init.mp4", "Films/Dust Signals (2011)/Dust Signals (2011).hls/audio-1/seg00000.m4s", "Films/Dust Signals (2011)/Dust Signals (2011).hls/sub-en.m3u8", "Films/Dust Signals (2011)/Dust Signals (2011).hls/sub-en.vtt", "Films/Dust Signals (2011)/Dust Signals (2011).hls/video/index.m3u8", "Films/Dust Signals (2011)/Dust Signals (2011).hls/video/init.mp4", "Films/Dust Signals (2011)/Dust Signals (2011).hls/video/seg00000.m4s", "Films/Dust Signals (2011)/Dust Signals (2011).m3u8", "Films/Dust Signals (2011)/Dust Signals (2011).nfo", "Films/Lowmarsh/Season 01/Lowmarsh - S01E01 - Pilot-thumb.jpg", "Films/Lowmarsh/Season 01/Lowmarsh - S01E01 - Pilot.mp4", "Films/Lowmarsh/Season 01/Lowmarsh - S01E01 - Pilot.nfo", "Films/Lowmarsh/Season 01/Lowmarsh - S01E02 - Cicadas.mkv", "Films/Lowmarsh/Season 01/Lowmarsh - S01E02 - Cicadas.nfo", "Films/Lowmarsh/poster.jpg", "Films/Lowmarsh/season01-poster.jpg", "Films/Lowmarsh/tvshow.nfo", "Films/Night Ferry (2019)/Night Ferry (2019).mp4", "Films/Night Ferry (2019)/Night Ferry (2019).nfo", "Films/Night Ferry (2019)/fanart.jpg", "Films/Night Ferry (2019)/poster.jpg", "Films/trakt-watched.json",];/// The keys [`a_film_shelf`] names and leaves off the shelf.pub fn films_missing(ws: &str) -> Vec<String> { vec![key(ws, "photos", 'q', "jpg")]}