//! The owner's cross-database record move, signed to the Mac serving the source. use serde_json::{Value, json}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::owner; pub const METHOD: &str = "records.move"; const PATH: &str = "/v1/records/move"; /// The serving route needs the source database as well as the record and the /// destination, because a device may be viewing any held database. pub fn request_for(request: &Value, source: &str) -> Option { let text = |key: &str| { request .get(key) .and_then(Value::as_str) .map(str::trim) .filter(|text| !text.is_empty()) }; let source = text("database").unwrap_or(source); if let Some(change) = text("change_id") { return Some(json!({"change_id":change, "database":source})); } Some(json!({ "id": text("id")?, "to": text("to")?, "database": source })) } pub fn call(handle: &CottonHandle, request: &Value) -> Result { let source = handle .client() .current_database() .map_err(|error| MethodError::new("unreadable", error))?; let body = request_for(request, &source).ok_or_else(|| { MethodError::new( "bad_request", "`records.move` needs a record and destination database", ) })?; let answer = over(&handle.client(), &body, || owner::with_fetch(handle, |fetch| owner::send(fetch, owner::post(PATH.to_owned(), &body))))?; let _ = crate::methods::sync::now(handle, &Value::Null); Ok(answer) } /// The same transfer boundary with its signed send supplied by the caller. pub(crate) fn over(client: &crate::shell::client::ClientController, body: &Value, send: impl FnOnce() -> Result) -> Result { owner::with_sent_files(client, || { let source=body["database"].as_str().ok_or_else(||MethodError::new("bad_request","A move needs its source database."))?; let destination=if let Some(to)=body["to"].as_str(){to.to_owned()}else{ let change=body["change_id"].as_str().ok_or_else(||MethodError::new("bad_request","An undo needs its move receipt."))?; client.with_file_in(source,|file| { let row=file.driver.get("SELECT after FROM cotton_changes WHERE id=? AND verb='move'",&[rusqlite::types::Value::Text(change.into())]).map_err(|e|e.to_string())?; let metadata:Value=serde_json::from_str(row.as_ref().and_then(|r|r.text("after")).unwrap_or("null")).map_err(|e|e.to_string())?; metadata["to"].as_str().map(str::to_owned).ok_or_else(||"That move is not available to undo.".into()) }).map_err(|e|MethodError::new("move_not_found",e))? }; Ok(vec![source.into(),destination]) }, send) } #[cfg(test)] mod tests { use super::*; /// RULE: a device sends the record, picked destination and current source to the serving Mac, so a move never guesses which of its held databases owns the record. #[test] fn request_names_record_destination_and_source() { assert_eq!( request_for(&json!({"id":"record-1", "to":"Work"}), "personal-1"), Some(json!({"id":"record-1", "to":"Work", "database":"personal-1"})) ); assert_eq!(request_for(&json!({"id":"record-1"}), "personal-1"), None); } }