Cotton code
305 lines · 12.4 KB · RustRaw
//! BRING NOTES IN — the files a person handed over → the notes they make.//!//! The phone hands over files (one, many, a folder's, a TextPack the core has//! unzipped), each by its path inside what was handed. This rule decides://!//! - A **TextBundle** is any folder named `*.textbundle`: its `text.md`//!   (or `text.markdown`, `text.txt`) is one note, titled by the folder's//!   name; every picture under it (`assets/…`) is kept with the note.//! - Every other **Markdown or text file** (`.md`, `.markdown`, `.mdown`,//!   `.txt`, `.text`) is one note, titled by its file name; a picture it//!   points at (`![](images/a.png)`) that was handed over too is kept with it.//! - A note's title is its file's (or bundle's) name, written as the first//!   heading, unless the text already starts with a heading (then that is the//!   title) or with those very words (then that line becomes the heading) —//!   the rule an old note opens by ([`super::derive::opened_text`]).//! - The words are kept as written: line breaks made `\n`, a byte-order mark//!   dropped, anything not UTF-8 read as Latin-1. Markdown this app does not//!   draw passes through untouched.//! - Anything else (a stray picture, `info.json`, a hidden file) makes no//!   note and is named in `skipped` only when it is neither a picture kept//!   with a note nor a bundle's own file.use serde::{Deserialize, Serialize};use super::derive;#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Handed {    /// Its path inside what was handed: `Trip.textbundle/assets/a.jpg`,    /// `Notes/Groceries.md`.    pub path: String,    #[serde(with = "bytes_b64", default)]    pub bytes: Vec<u8>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Picture {    /// The handed file it is (an index into the handed list).    pub file: usize,    /// The path the note's text points at it by, relative to the note.    pub path: String,    pub content_type: String,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Imported {    /// The handed file (or bundle) it came from.    pub source: String,    pub text: String,    pub pictures: Vec<Picture>,    /// When it was made and last edited, as a TextBundle's `info.json` says    /// (RFC 3339, UTC); none when nothing says.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub made: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub edited: Option<String>,    /// Pinned, as the reference app's `info.json` says.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub pinned: bool,}/// What a TextBundle's `info.json` says of its note: its made and edited/// moments and its pin, read at the top level or under the app's own key/// (the reference app writes `net.shinyfrog.bear`).pub fn bundle_info(bytes: &[u8]) -> (Option<String>, Option<String>, bool) {    let Ok(info) = serde_json::from_slice::<serde_json::Value>(bytes) else { return (None, None, false) };    let mut places = vec![&info];    if let Some(own) = info.as_object() {        places.extend(own.values().filter(|value| value.is_object()));    }    let moment = |key: &str| {        places.iter().find_map(|place| place.get(key).and_then(serde_json::Value::as_str)).and_then(|said| {            chrono::DateTime::parse_from_rfc3339(said.trim()).ok().map(|when| when.with_timezone(&chrono::Utc).to_rfc3339_opts(chrono::SecondsFormat::Millis, true))        })    };    let pinned = places.iter().find_map(|place| place.get("pinned")).is_some_and(|said| said.as_bool().unwrap_or_else(|| matches!(said.as_str(), Some("yes" | "true" | "1"))) || said.as_i64() == Some(1));    (moment("creationDate"), moment("modificationDate"), pinned)}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]pub struct Plan {    pub notes: Vec<Imported>,    /// Handed paths that make no note and belong to none.    pub skipped: Vec<String>,}const TEXT: [&str; 5] = ["md", "markdown", "mdown", "txt", "text"];const BUNDLE_TEXT: [&str; 3] = ["text.md", "text.markdown", "text.txt"];fn extension(path: &str) -> String {    let name = path.rsplit('/').next().unwrap_or(path);    name.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()).unwrap_or_default()}/// A picture's content type by its extension; none for anything else.pub fn picture_type(path: &str) -> Option<&'static str> {    Some(match extension(path).as_str() {        "png" => "image/png",        "jpg" | "jpeg" => "image/jpeg",        "gif" => "image/gif",        "webp" => "image/webp",        "heic" => "image/heic",        "heif" => "image/heif",        "svg" => "image/svg+xml",        "tif" | "tiff" => "image/tiff",        _ => return None,    })}fn stem(name: &str) -> &str {    let name = name.trim_end_matches('/').rsplit('/').next().unwrap_or(name);    name.rsplit_once('.').map(|(stem, _)| stem).filter(|stem| !stem.is_empty()).unwrap_or(name)}fn hidden(path: &str) -> bool {    path.split('/').any(|part| part.starts_with('.') || part == "__MACOSX")}/// The words of a handed text file.pub fn words_of(bytes: &[u8]) -> String {    let bytes = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);    let text = match std::str::from_utf8(bytes) {        Ok(text) => text.to_string(),        Err(_) => bytes.iter().map(|&b| b as char).collect(),    };    text.replace("\r\n", "\n").replace('\r', "\n")}/// Normalise a relative path: `./a/../b.png` → `b.png`; none when it leaves/// its root.fn normal(path: &str) -> Option<String> {    let mut parts: Vec<&str> = Vec::new();    for part in path.split('/') {        match part {            "" | "." => {}            ".." => {                parts.pop()?;            }            other => parts.push(other),        }    }    Some(parts.join("/"))}/// The local pictures a text points at (`![alt](path)`), as written.fn pointed(text: &str) -> Vec<String> {    let mut out = Vec::new();    let mut rest = text;    while let Some(at) = rest.find("![") {        rest = &rest[at + 2..];        let Some(close) = rest.find("](") else { break };        let after = &rest[close + 2..];        let Some(end) = after.find(')') else { break };        let target = after[..end].trim().trim_matches(['<', '>']);        let target = target.split_once(' ').map(|(path, _)| path).unwrap_or(target);        if !target.contains("://") && !target.starts_with("data:") && !target.is_empty() {            out.push(target.to_string());        }        rest = &after[end..];    }    out}fn unescape_path(path: &str) -> String {    // `%20` and friends, as Markdown writers escape spaces in paths.    let bytes = path.as_bytes();    let mut out = Vec::with_capacity(bytes.len());    let mut k = 0;    while k < bytes.len() {        if bytes[k] == b'%' && k + 2 < bytes.len() {            if let Some(byte) = path.get(k + 1..k + 3).and_then(|hex| u8::from_str_radix(hex, 16).ok()) {                out.push(byte);                k += 3;                continue;            }        }        out.push(bytes[k]);        k += 1;    }    String::from_utf8(out).unwrap_or_else(|_| path.to_string())}/// Plan the notes `handed` makes.pub fn plan(handed: &[Handed]) -> Plan {    let mut plan = Plan::default();    let mut used = vec![false; handed.len()];    let paths: Vec<String> = handed.iter().map(|file| normal(&file.path.replace('\\', "/")).unwrap_or_default()).collect();    // Bundles first: every folder named *.textbundle.    let mut bundles: Vec<String> = Vec::new();    for path in &paths {        let mut prefix = String::new();        for part in path.split('/') {            if !prefix.is_empty() {                prefix.push('/');            }            prefix.push_str(part);            if part.to_ascii_lowercase().ends_with(".textbundle") {                if !bundles.contains(&prefix) {                    bundles.push(prefix.clone());                }                break;            }        }    }    for bundle in &bundles {        let inside = |k: usize| paths[k].starts_with(&format!("{bundle}/"));        let text_file = BUNDLE_TEXT.iter().find_map(|name| (0..handed.len()).find(|&k| paths[k].eq_ignore_ascii_case(&format!("{bundle}/{name}"))));        let Some(text_file) = text_file else {            continue;        };        let words = words_of(&handed[text_file].bytes);        let mut pictures = Vec::new();        for k in 0..handed.len() {            if !inside(k) {                continue;            }            used[k] = true;            if let Some(kind) = picture_type(&paths[k]).filter(|_| !hidden(&paths[k])) {                pictures.push(Picture { file: k, path: paths[k][bundle.len() + 1..].to_string(), content_type: kind.to_string() });            }        }        let info = (0..handed.len()).find(|&k| paths[k].eq_ignore_ascii_case(&format!("{bundle}/info.json")));        let (made, edited, pinned) = info.map(|k| bundle_info(&handed[k].bytes)).unwrap_or_default();        plan.notes.push(Imported { source: bundle.clone(), text: derive::opened_text(Some(stem(bundle)), &words), pictures, made, edited, pinned });    }    for k in 0..handed.len() {        if used[k] || hidden(&paths[k]) || !TEXT.contains(&extension(&paths[k]).as_str()) {            continue;        }        used[k] = true;        let words = words_of(&handed[k].bytes);        let folder = paths[k].rsplit_once('/').map(|(dir, _)| dir.to_string()).unwrap_or_default();        let mut pictures = Vec::new();        for target in pointed(&words) {            let joined = if folder.is_empty() { unescape_path(&target) } else { format!("{folder}/{}", unescape_path(&target)) };            let Some(joined) = normal(&joined) else { continue };            if let Some(file) = (0..handed.len()).find(|&j| paths[j] == joined) {                if let Some(kind) = picture_type(&joined) {                    if !pictures.iter().any(|picture: &Picture| picture.file == file) {                        pictures.push(Picture { file, path: target.clone(), content_type: kind.to_string() });                    }                    used[file] = true;                }            }        }        plan.notes.push(Imported { source: paths[k].clone(), text: derive::opened_text(Some(stem(&paths[k])), &words), pictures, made: None, edited: None, pinned: false });    }    for k in 0..handed.len() {        let name = paths[k].rsplit('/').next().unwrap_or_default();        if !used[k] && !hidden(&paths[k]) && name != "info.json" {            plan.skipped.push(handed[k].path.clone());        }    }    plan}/// Bytes ride as base64 in JSON vectors and requests.mod bytes_b64 {    use serde::{Deserialize, Deserializer, Serializer};    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";    pub fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {        let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);        for chunk in bytes.chunks(3) {            let n = (chunk[0] as u32) << 16 | (*chunk.get(1).unwrap_or(&0) as u32) << 8 | *chunk.get(2).unwrap_or(&0) as u32;            for k in 0..4 {                if k <= chunk.len() {                    out.push(ALPHABET[(n >> (18 - 6 * k) & 63) as usize] as char);                } else {                    out.push('=');                }            }        }        serializer.serialize_str(&out)    }    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {        let said = String::deserialize(deserializer)?;        decode(&said).ok_or_else(|| serde::de::Error::custom("not base64"))    }    pub fn decode(said: &str) -> Option<Vec<u8>> {        let mut out = Vec::with_capacity(said.len() / 4 * 3);        let mut buffer = 0u32;        let mut bits = 0;        for c in said.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=') {            let value = match c {                b'A'..=b'Z' => c - b'A',                b'a'..=b'z' => c - b'a' + 26,                b'0'..=b'9' => c - b'0' + 52,                b'+' | b'-' => 62,                b'/' | b'_' => 63,                _ => return None,            } as u32;            buffer = buffer << 6 | value;            bits += 6;            if bits >= 8 {                bits -= 8;                out.push((buffer >> bits & 0xFF) as u8);            }        }        Some(out)    }}