Cotton code
75 lines · 3.5 KB · RustRaw
//! `notes.shared {url?, text?, title?, file?, fileName?}` — WHAT IS SHARED//! INTO NOTES BECOMES A NOTE (the share sheet's words, or a text file handed//! over: the shell's ShareIntake stages it and asks this; it reads nothing).//!//! - The note's body is the words shared, with the link after them where the//!   words do not already hold it; a text file shared (UTF-8, at most//!   [`MOST_BYTES`]) is the body instead, its own words as written.//! - Its title is the share's subject where one came and the body does not//!   begin with it, else the file's name without its extension, else none (the//!   torn page then titles it by its first sentence).//! - Answers `{ lands: { table: "note", id } }`, the note the deck stands on;//!   a share holding no words (a picture, a file that is no text, an empty//!   one) writes nothing and answers `{ said }` in the kit's words//!   (`capture share.no_words`).use serde_json::{json, Value};use cotton_core::rules::shell_lines::LineSet;use crate::handle::CottonHandle;use crate::methods::MethodError;/// The most of a shared file read as a note's words.pub const MOST_BYTES: u64 = 1024 * 1024;pub fn shared(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let text = |key: &str| request.get(key).and_then(Value::as_str).map(str::trim).filter(|words| !words.is_empty()).map(str::to_string);    let from_file = text("file").and_then(|path| read_text(&path));    let file_name = text("fileName");    let body = match from_file {        Some(words) => Some(words),        None if text("file").is_some() && text("text").is_none() => None,        None => {            let words = text("text");            match (words, text("url")) {                (Some(words), Some(url)) if !words.contains(&url) => Some(format!("{words}\n\n{url}")),                (Some(words), _) => Some(words),                (None, Some(url)) => Some(url),                (None, None) => None,            }        }    };    let Some(body) = body.map(|body| body.trim().to_string()).filter(|body| !body.is_empty()) else {        return Ok(json!({"said": LineSet::shipped("capture").and_then(|lines| lines.say("share.no_words", &[])).unwrap_or_default()}));    };    let stem = file_name.as_deref().map(|name| name.rsplit_once('.').map(|(stem, _)| stem).unwrap_or(name).trim().to_string()).filter(|stem| !stem.is_empty());    let title = text("title").filter(|subject| !body.starts_with(subject.as_str())).or(stem);    let mut data = json!({"body": body});    if let Some(title) = title {        data["title"] = json!(title);    }    let made = crate::methods::dispatch(handle, "records.create", &json!({"table": "note", "data": data}))?;    let id = made["id"].as_str().or_else(|| made["record"]["id"].as_str()).ok_or_else(|| MethodError::new("unwritten", "the note came back without its id"))?;    Ok(json!({"lands": {"table": "note", "id": id}}))}/// A staged file's words: UTF-8 text no larger than [`MOST_BYTES`] holding/// no NUL (a picture or a PDF is no text).fn read_text(path: &str) -> Option<String> {    let meta = std::fs::metadata(path).ok()?;    if meta.len() > MOST_BYTES {        return None;    }    let bytes = std::fs::read(path).ok()?;    if bytes.contains(&0) {        return None;    }    let words = String::from_utf8(bytes).ok()?;    let words = words.trim_start_matches('\u{feff}').trim().to_string();    (!words.is_empty()).then_some(words)}#[cfg(test)]#[path = "notes_share_tests.rs"]mod tests;