Cotton code
214 lines · 9.4 KB · RustRaw
//! `notes.import` — Bring notes in. The phone only hands over files: each//! a path on this phone (a file, or a folder the core walks) and, for a//! file, the name it had inside what was picked (`Trip.textbundle/text.md`).//! A TextPack (`.textpack`, a zipped TextBundle) is opened here. Which files//! make which notes is `cotton_rules::writing::import`'s rule.//!//! - **No duplicates, and resumable.** A note whose text this copy already//!   holds word for word is not made again, so the same library brought in//!   twice — or a big import cut short and started again — makes each note//!   once. Nothing marks a note as imported: a mark in a clear column would//!   tell the server something about what it says.//! - **Pictures** are kept as photos once by their bytes (the same picture//!   in two notes, or brought in twice, is one photo) and the text points at//!   them where it pointed at the file (`![](assets/a.jpg)` →//!   `![](photo:<id>)`).//! - **Hashtags file** each note as a note written here is filed.//! - **The answer says** how many notes, pictures and tags came in, how many//!   notes were already here, and what could not be read, in words.use std::collections::BTreeSet;use std::path::{Path, PathBuf};use serde_json::{json, Value};use cotton_core::cotton_rules::writing::{derive, import};use super::notes::{create, every_note, keep_picture, line, text_of, with_read, with_write};use crate::handle::CottonHandle;use crate::methods::MethodError;/// The most bytes one handed file may hold (a TextPack with its pictures).const LARGEST: u64 = 512 * 1024 * 1024;fn bad(why: impl Into<String>) -> MethodError {    MethodError::new("bad_request", why.into())}/// A handed file still on disk, or bytes the core took out of a TextPack.struct Source {    name: String,    bytes: Vec<u8>,}fn walk(dir: &Path, root: &Path, out: &mut Vec<Source>, unread: &mut Vec<String>) {    let Ok(entries) = std::fs::read_dir(dir) else {        unread.push(dir.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default());        return;    };    let mut entries: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect();    entries.sort();    for path in entries {        if path.is_dir() {            walk(&path, root, out, unread);        } else {            let name = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");            read_one(&path, name, out, unread);        }    }}fn read_one(path: &Path, name: String, out: &mut Vec<Source>, unread: &mut Vec<String>) {    let too_big = std::fs::metadata(path).map(|m| m.len() > LARGEST).unwrap_or(true);    match (too_big, std::fs::read(path)) {        (false, Ok(bytes)) if name.to_ascii_lowercase().ends_with(".textpack") => unpack(&name, &bytes, out, unread),        (false, Ok(bytes)) => out.push(Source { name, bytes }),        _ => unread.push(name),    }}/// A TextPack's entries, each under `<name>.textbundle/` unless the zip/// already holds its bundle folder.fn unpack(name: &str, bytes: &[u8], out: &mut Vec<Source>, unread: &mut Vec<String>) {    use cotton_core::import::zip::{list_zip_entries, read_zip_entry};    let Ok(entries) = list_zip_entries(bytes) else {        unread.push(name.to_string());        return;    };    let stem = name.rsplit('/').next().unwrap_or(name);    let stem = stem.rsplit_once('.').map(|(s, _)| s).unwrap_or(stem);    let folder = name.rsplit_once('/').map(|(dir, _)| format!("{dir}/")).unwrap_or_default();    let bundled = entries.iter().any(|e| e.name.split('/').next().is_some_and(|top| top.to_ascii_lowercase().ends_with(".textbundle")));    let mut any = false;    for entry in &entries {        if entry.name.ends_with('/') {            continue;        }        match read_zip_entry(bytes, entry) {            Ok(content) => {                let inside = if bundled { format!("{folder}{}", entry.name) } else { format!("{folder}{stem}.textbundle/{}", entry.name) };                out.push(Source { name: inside, bytes: content });                any = true;            }            Err(_) => unread.push(format!("{name}/{}", entry.name)),        }    }    if !any {        unread.push(name.to_string());    }}/// A text compared for duplicates: its line ends trimmed.fn same(text: &str) -> String {    text.trim_end().lines().map(str::trim_end).collect::<Vec<_>>().join("\n")}/// `notes.import { files: [{ path, name? }] }`.pub fn import(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let files = request.get("files").and_then(Value::as_array).ok_or_else(|| bad("an import hands over `files`"))?;    let mut sources = Vec::new();    let mut unread = Vec::new();    for file in files {        let path = file["path"].as_str().map(str::trim).filter(|p| !p.is_empty()).ok_or_else(|| bad("each file is its `path`"))?;        let path = Path::new(path);        let fallback = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();        if path.is_dir() {            let root = path.parent().unwrap_or(path);            walk(path, root, &mut sources, &mut unread);        } else {            let name = file["name"].as_str().map(str::to_string).filter(|n| !n.trim().is_empty()).unwrap_or(fallback);            read_one(path, name, &mut sources, &mut unread);        }    }    let handed: Vec<import::Handed> = sources.iter().map(|s| import::Handed { path: s.name.clone(), bytes: s.bytes.clone() }).collect();    let plan = import::plan(&handed);    unread.extend(plan.skipped.iter().filter(|path| import::picture_type(path).is_none()).cloned());    // What this copy already says, word for word.    let held = with_read(handle, "notes.import", |ctx| {        let mut texts = Vec::new();        for note in every_note(ctx)? {            if !note.binned {                texts.push(same(&text_of(ctx, &note)?));            }        }        Ok(json!(texts))    })?;    let mut known: BTreeSet<String> = serde_json::from_value(held).unwrap_or_default();    let scratch = tempfile::tempdir().map_err(|why| MethodError::new("unreadable", why.to_string()))?;    let mut made = 0usize;    let mut already = 0usize;    let mut pictures = 0usize;    let mut tags: BTreeSet<String> = BTreeSet::new();    for note in &plan.notes {        let mut text = note.text.clone();        let mut kept = 0usize;        for (index, picture) in note.pictures.iter().enumerate() {            let source = &handed[picture.file];            let ext = source.path.rsplit_once('.').map(|(_, e)| e).unwrap_or("jpg");            let file = scratch.path().join(format!("p{index}.{ext}"));            // not a copy: an import's picture in a scratch folder.            if std::fs::write(&file, &source.bytes).is_err() {                unread.push(source.path.clone());                continue;            }            let filename = source.path.rsplit('/').next();            match keep_picture(handle, &file.to_string_lossy(), &picture.content_type, filename) {                Ok(src) => {                    for written in [format!("]({})", picture.path), format!("](<{}>)", picture.path), format!("]({})", picture.path.replace(' ', "%20"))] {                        text = text.replace(&written, &format!("]({src})"));                    }                    kept += 1;                }                Err(_) => unread.push(source.path.clone()),            }        }        let key = same(&text);        if key.is_empty() {            continue;        }        if known.contains(&key) {            already += 1;            continue;        }        with_write(handle, "notes.import", |ctx| {            let id = create(ctx, &text)?;            // The bundle's own dates and pin, where its info.json says them.            let mut patch = serde_json::Map::new();            if let Some(made) = &note.made {                patch.insert("created_at".into(), json!(made));            }            if let Some(edited) = note.edited.as_ref().or(note.made.as_ref()) {                patch.insert("updated_at".into(), json!(edited));            }            if note.pinned {                patch.insert("pinned".into(), json!(true));            }            if !patch.is_empty() {                cotton_tools::mcp::handlers::common::update_row(ctx, super::notes::NOTES, &id, patch).map_err(super::notes::tool)?;                ctx.commit().map_err(super::notes::tool)?;            }            Ok(Value::from(id))        })?;        known.insert(key);        made += 1;        pictures += kept;        tags.extend(derive::tags(&text).iter().map(|t| derive::tag_key(t)));    }    unread.sort();    unread.dedup();    let said_notes = super::notes::counted_line("import.notes", made)?;    let said_pictures = super::notes::counted_line("import.pictures", pictures)?;    let said_tags = super::notes::counted_line("import.tags", tags.len())?;    let mut said = if made == 0 && already == 0 { line("import.nothing", &[])? } else { line("import.done", &[("notes", &said_notes), ("pictures", &said_pictures), ("tags", &said_tags)])? };    if already > 0 {        said.push(' ');        said.push_str(&super::notes::counted_line("import.already", already)?);    }    if !unread.is_empty() {        said.push(' ');        said.push_str(&line("import.unread", &[("names", &unread.join(", "))])?);    }    Ok(json!({ "notes": made, "already": already, "pictures": pictures, "tags": tags.len(), "unread": unread, "said": said }))}