//! THE OPEN BUNDLE — a library leaves Cotton in shapes other apps open. //! //! The `.cottonpkg` is the faithful Cotton-to-Cotton copy, and no other app //! opens it. The open bundle is the other door: one folder tree per kit, laid //! from the kit's rows and the bytes they name, in the formats the apps people //! already use read. //! //! - **Books** ([`books`]): `Books///` with the book file as //! stored, `metadata.opf` and the cover; `catalog.json` (OPDS 2.0), //! `catalog.xml` (OPDS 1.2) and `goodreads.csv` at the root; highlights as //! Markdown and as W3C Web Annotation JSON-LD beside the book. //! - **Music** ([`music`]): `Music/<Artist>/<Album>/NN Title.<ext>` as stored //! with the album's cover, `playlists/*.m3u8` and `listens.jsonl` //! (ListenBrainz). //! - **Films** ([`films`]): `Films/<Title (Year)>/` with the film as stored //! (a whole file, or its HLS master and renditions), its Kodi NFO, //! subtitles, poster and fanart; series as `<Series>/Season NN/<Series> - //! SNNENN - <Title>` with episode NFOs and `tvshow.nfo`; //! `trakt-watched.json` (Trakt's watched export) at the root. //! //! **Media bytes are copied, never transcoded**, and keep the extension of the //! key they were stored under. **Nothing is invented**: a column the kit does //! not hold is not written, and a book with no file has no acquisition link. //! The same rows and media at the same `exported_at` lay the same tree. //! //! **This rule holds no bytes.** It is handed the kit's live rows and what is //! known of the media they name, and answers either the keys it still needs to //! know about ([`Laid::Asks`]: whether a key is held, or a playlist's text) or //! the whole tree ([`Laid::Tree`]): each file as its text or as the media key //! whose bytes it is. The host — the phone's store writing a folder, the //! Worker streaming a ZIP from R2 — answers the asks and calls again, then //! copies each media key's bytes itself. use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value as JsonValue}; mod books; mod films; mod music; /// Why a bundle could not be laid, in words. pub type Refusal = String; type Result<T> = std::result::Result<T, Refusal>; fn refuse(message: impl Into<String>) -> Refusal { message.into() } /// The kits an open bundle can be laid for. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Kit { Books, Music, Films, } impl Kit { /// The folder this kit's tree is laid under, inside the bundle. pub fn root(self) -> &'static str { match self { Kit::Books => "Books", Kit::Music => "Music", Kit::Films => "Films", } } /// The kit tables the bundle reads, by table id. Music's lists come too, /// from [`LISTS`] and [`LIST_MEMBERS`]. pub fn tables(self) -> &'static [&'static str] { match self { Kit::Books => &["book", "highlight"], Kit::Music => &["artist", "music_album", "song", "listen"], Kit::Films => &["film", "film_season", "film_episode", "watch"], } } } /// A list of records: `{ id, table_id, name, position }`. pub const LISTS: &str = "record_group"; /// One record on a list: `{ id, group, record_id, place }`. pub const LIST_MEMBERS: &str = "group_member"; /// A row of a kit table, in its domain form. pub type Row = Map<String, JsonValue>; /// What the host knows of one media key. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Held { /// Its bytes are held. Held, /// No bytes are held at it. Missing, /// Its bytes, read as text (a playlist). Text(String), } /// What the rule lays from. #[derive(Debug, Clone, Deserialize)] pub struct Library { pub kit: Kit, /// Each table's live rows (none in the bin), by table id. A table left /// out holds none. #[serde(default)] pub tables: BTreeMap<String, Vec<Row>>, /// The database's id: the OPDS 1.2 feed's id says it. #[serde(default)] pub database: String, /// The caller's clock, an RFC 3339 instant: a format that must say when it /// was made says this. pub exported_at: String, /// False lays the metadata alone: no media key is asked for, copied or /// counted missing. #[serde(default = "yes")] pub media: bool, /// What is known of the media keys asked for so far. #[serde(default)] pub known: BTreeMap<String, Held>, } fn yes() -> bool { true } /// One question for the host about a media key. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)] pub struct Ask { pub key: String, /// True: answer its bytes as text ([`Held::Text`]). False: whether it is /// held is enough. pub read: bool, } /// One file of the tree. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(untagged)] pub enum Entry { /// A file the rule wrote. Text { path: String, text: String }, /// A file that is a media key's bytes, as stored. Media { path: String, media: String }, } impl Entry { pub fn path(&self) -> &str { match self { Entry::Text { path, .. } | Entry::Media { path, .. } => path, } } } /// What a call answers. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum Laid { /// Answer these in `known` and call again. Asks(Vec<Ask>), /// The tree, every path `/`-separated under the kit's root and sorted, /// and the keys a row names that are not held (sorted). Tree { entries: Vec<Entry>, missing_media: Vec<String> }, } /// Lay `library`'s tree, or say which media keys must be known first. pub fn lay(library: &Library) -> Result<Laid> { let mut out = Out { library, entries: BTreeMap::new(), missing: BTreeSet::new(), asks: BTreeSet::new() }; match library.kit { Kit::Books => books::write(&mut out)?, Kit::Music => music::write(&mut out)?, Kit::Films => films::write(&mut out)?, } if !out.asks.is_empty() { return Ok(Laid::Asks(out.asks.into_iter().collect())); } Ok(Laid::Tree { entries: out.entries.into_values().collect(), missing_media: out.missing.into_iter().collect() }) } /// `lay` as the boundary reads it: a [`Library`] as JSON in, [`Laid`] as JSON /// out (`{"asks": [...]}` or `{"tree": {entries, missing_media}}`). pub fn lay_json(value: JsonValue) -> Result<JsonValue> { let library: Library = serde_json::from_value(value).map_err(|error| format!("open_bundle.lay: the input does not read: {error}"))?; serde_json::to_value(lay(&library)?).map_err(|error| error.to_string()) } /// The files laid so far, what is missing and what must be asked. struct Out<'l> { library: &'l Library, entries: BTreeMap<String, Entry>, missing: BTreeSet<String>, asks: BTreeSet<Ask>, } impl Out<'_> { /// Table `id`'s rows, in id order. fn rows(&self, id: &str) -> Vec<Row> { let mut rows = self.library.tables.get(id).cloned().unwrap_or_default(); rows.sort_by(|a, b| text(a, "id").cmp(&text(b, "id"))); rows } fn exported_at(&self) -> &str { &self.library.exported_at } /// Write `text` at `relative` (`/`-separated) under the bundle. fn write(&mut self, relative: &str, text: impl Into<String>) { self.entries.insert(relative.to_string(), Entry::Text { path: relative.to_string(), text: text.into() }); } /// The bytes at media `key` laid at `relative`, as stored. Answers whether /// they are held; a key not known yet is asked for. fn copy(&mut self, key: &str, relative: &str) -> bool { if !self.library.media { return false; } match self.library.known.get(key) { Some(Held::Held | Held::Text(_)) => { self.entries.insert(relative.to_string(), Entry::Media { path: relative.to_string(), media: key.to_string() }); true } Some(Held::Missing) => { self.missing.insert(key.to_string()); false } None => { self.asks.insert(Ask { key: key.to_string(), read: false }); false } } } /// The text at media `key` (a playlist), when held; a key not known yet /// is asked for, a key not held is missing. fn read(&mut self, key: &str) -> Option<String> { if !self.library.media { return None; } match self.library.known.get(key) { Some(Held::Text(text)) => Some(text.clone()), Some(Held::Missing) => { self.missing.insert(key.to_string()); None } Some(Held::Held) | None => { self.asks.insert(Ask { key: key.to_string(), read: true }); None } } } } /// Rows by id. fn by_id(rows: &[Row]) -> BTreeMap<String, &Row> { rows.iter().filter_map(|row| Some((text(row, "id")?.to_string(), row))).collect() } /// A text column, trimmed, or `None` when empty. fn text<'a>(row: &'a Row, column: &str) -> Option<&'a str> { row.get(column).and_then(JsonValue::as_str).map(str::trim).filter(|value| !value.is_empty()) } /// A number column. fn number(row: &Row, column: &str) -> Option<f64> { match row.get(column)? { JsonValue::Number(number) => number.as_f64(), JsonValue::String(text) => text.trim().parse().ok(), _ => None, } } /// A number as people write it: whole numbers without a point. fn plain_number(value: f64) -> String { if value.fract() == 0.0 && value.abs() < 1e15 { format!("{}", value as i64) } else { format!("{value}") } } /// A number as JSON: whole numbers as integers. fn json_number(value: f64) -> JsonValue { if value.fract() == 0.0 && value.abs() < 1e15 { JsonValue::from(value as i64) } else { JsonValue::from(value) } } /// The extension of a media key (`…/<sha>.epub` → `epub`), lowercased. fn extension(key: &str) -> Option<String> { let name = key.rsplit('/').next()?; let (_, ext) = name.rsplit_once('.')?; (!ext.is_empty() && ext.len() <= 8 && ext.chars().all(|c| c.is_ascii_alphanumeric())).then(|| ext.to_ascii_lowercase()) } /// The media type of a picture by its extension. fn picture_type(ext: &str) -> &'static str { match ext { "png" => "image/png", "webp" => "image/webp", "gif" => "image/gif", "heic" => "image/heic", _ => "image/jpeg", } } /// One path component from a name a person gave: the characters no file /// system takes become `_`, leading and trailing dots and spaces go, and an /// empty name is `fallback`. At most 120 characters. fn component(name: Option<&str>, fallback: &str) -> String { let cleaned: String = name .unwrap_or_default() .chars() .map(|c| if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }) .take(120) .collect(); let trimmed = cleaned.trim_matches(|c: char| c == '.' || c.is_whitespace()); if trimmed.is_empty() { fallback.to_string() } else { trimmed.to_string() } } /// `wanted`, or `wanted (2)`, `wanted (3)` … — the first `taken` does not hold /// case-insensitively (two folders differing only in case are one on a Mac). fn unique(taken: &mut BTreeSet<String>, wanted: &str) -> String { let mut candidate = wanted.to_string(); let mut n = 2; while !taken.insert(candidate.to_lowercase()) { candidate = format!("{wanted} ({n})"); n += 1; } candidate } /// Text for XML character data and attribute values. fn xml(text: &str) -> String { let mut out = String::with_capacity(text.len()); for c in text.chars() { match c { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), // XML 1.0 takes no control characters but tab and line breaks. c if c.is_control() && !matches!(c, '\t' | '\n' | '\r') => {} c => out.push(c), } } out } /// One CSV field (RFC 4180): quoted when it holds a comma, a quote or a line /// break. fn csv(field: &str) -> String { if field.contains([',', '"', '\n', '\r']) { format!("\"{}\"", field.replace('"', "\"\"")) } else { field.to_string() } } /// A path relative to the bundle, as a URL path: each component /// percent-encoded where a URL may not carry it raw. fn href(path: &str) -> String { let mut out = String::with_capacity(path.len()); for byte in path.bytes() { match byte { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' | b'(' | b')' | b'\'' | b'!' => { out.push(byte as char) } _ => out.push_str(&format!("%{byte:02X}")), } } out } /// JSON, pretty and ending in a line break. fn pretty(value: &JsonValue) -> String { let mut text = serde_json::to_string_pretty(value).unwrap_or_default(); text.push('\n'); text } #[cfg(test)] mod tests;