rightkit_document_workspace/
document_io.rs1use crate::documents::{DocumentBackend, FileFingerprint, RawDocument, WriteDocumentResult};
5use crate::error::{broker_error, WorkspaceError};
6use crate::grants::{authorize_existing_for_read, PathGrants};
7use crate::store::Db;
8use crate::watch::WorkspaceWatcher;
9
10pub fn read_document(
13 db: &Db,
14 grants: &dyn PathGrants,
15 docs: &dyn DocumentBackend,
16 path: &str,
17) -> Result<RawDocument, WorkspaceError> {
18 let path = authorize_existing_for_read(path, grants)?;
19 let format = docs.format_of(&path);
20 let mut doc = docs.read(&path).map_err(|e| match format {
21 "unknown" => WorkspaceError::UnsupportedFormat(e),
22 _ if e.contains("too large") => WorkspaceError::DocumentTooLarge(e),
23 _ => WorkspaceError::Io(e),
24 })?;
25 if matches!(format, "pdf" | "docx" | "image") {
26 doc.stream_token = Some(grants.grant_stream_token(&path)?);
27 }
28 let st = db.view_state(&path)?;
29 doc.last_view = st.last_view;
30 doc.view_meta = st.view_meta;
31 Ok(doc)
32}
33
34pub fn write_document(
35 grants: &dyn PathGrants,
36 docs: &dyn DocumentBackend,
37 path: &str,
38 content: &str,
39 encoding: Option<String>,
40 expected_source_sha256: Option<&str>,
41) -> Result<WriteDocumentResult, WorkspaceError> {
42 let path = grants.require_write_target(path).map_err(broker_error)?;
43 let encoding = encoding.unwrap_or_else(|| "UTF-8".to_string());
44 let result = docs.write(&path, content, &encoding, expected_source_sha256);
45 if result.is_ok() {
46 let _ = grants.record_write_target(std::path::Path::new(&path));
47 }
48 result.map_err(|e| {
49 if e.starts_with("write conflict:") {
50 WorkspaceError::WriteConflict(e)
51 } else if e.to_ascii_lowercase().contains("encod") {
52 WorkspaceError::Encoding(e)
53 } else {
54 WorkspaceError::Io(e)
55 }
56 })
57}
58
59#[derive(Debug, PartialEq)]
61pub enum WritePayload {
62 Raw(Vec<u8>),
63 Base64(String),
64}
65
66pub fn decode_hex_path(hex: &str) -> Result<String, String> {
69 rightkit_fs::digest::unhex(hex)
70 .filter(|bytes| !bytes.is_empty())
71 .and_then(|bytes| String::from_utf8(bytes).ok())
72 .ok_or_else(|| "invalid write path header".to_string())
73}
74
75pub fn write_document_payload(
76 grants: &dyn PathGrants,
77 docs: &dyn DocumentBackend,
78 path: &str,
79 payload: WritePayload,
80) -> Result<(), WorkspaceError> {
81 let path = grants.require_write_target(path).map_err(broker_error)?;
82 let result = match payload {
83 WritePayload::Raw(bytes) => docs.write_raw_bytes(&path, &bytes),
84 WritePayload::Base64(b64) => docs.write_bytes(&path, &b64),
85 };
86 if result.is_ok() {
87 let _ = grants.record_write_target(std::path::Path::new(&path));
88 }
89 result.map_err(WorkspaceError::Io)
90}
91
92pub fn copy_document(
93 grants: &dyn PathGrants,
94 docs: &dyn DocumentBackend,
95 source_path: &str,
96 target_path: &str,
97) -> Result<(), WorkspaceError> {
98 let source = authorize_existing_for_read(source_path, grants).map_err(broker_error)?;
99 let target = grants
100 .require_write_target(target_path)
101 .map_err(broker_error)?;
102 docs.copy_document(&source, &target)
103 .map_err(WorkspaceError::Io)?;
104 grants
105 .record_write_target(std::path::Path::new(&target))
106 .map_err(broker_error)?;
107 Ok(())
108}
109
110pub fn revoke_path(grants: &dyn PathGrants, path: &str) -> Result<(), WorkspaceError> {
111 grants.revoke_path(path).map_err(broker_error)
112}
113
114pub fn list_sibling_images(
120 grants: &dyn PathGrants,
121 docs: &dyn DocumentBackend,
122 path: &str,
123) -> Result<Vec<String>, WorkspaceError> {
124 let current = authorize_existing_for_read(path, grants).map_err(broker_error)?;
125 let dir = std::path::Path::new(¤t)
126 .parent()
127 .ok_or_else(|| WorkspaceError::FileNotFound("image has no parent directory".into()))?
128 .to_path_buf();
129 let dir_canon = std::fs::canonicalize(&dir)?;
133 let mut images: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)?
134 .filter_map(|entry| entry.ok().map(|e| e.path()))
135 .filter(|p| p.is_file() && docs.format_of(&p.to_string_lossy()) == "image")
136 .filter_map(|p| std::fs::canonicalize(&p).ok()) .filter(|c| c.starts_with(&dir_canon)) .collect();
139 images.sort_by(|a, b| natural_cmp(&file_name_lossy(a), &file_name_lossy(b)));
140 images.dedup(); Ok(grants.grant_existing_files(&images))
142}
143
144fn file_name_lossy(p: &std::path::Path) -> String {
145 p.file_name()
146 .map(|n| n.to_string_lossy().into_owned())
147 .unwrap_or_default()
148}
149
150pub fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
154 use std::cmp::Ordering;
155 let mut ai = a.chars().peekable();
156 let mut bi = b.chars().peekable();
157 loop {
158 match (ai.peek().copied(), bi.peek().copied()) {
159 (None, None) => return Ordering::Equal,
160 (None, Some(_)) => return Ordering::Less,
161 (Some(_), None) => return Ordering::Greater,
162 (Some(ac), Some(bc)) => {
163 if ac.is_ascii_digit() && bc.is_ascii_digit() {
164 let an = take_digits(&mut ai);
165 let bn = take_digits(&mut bi);
166 let at = an.trim_start_matches('0');
167 let bt = bn.trim_start_matches('0');
168 let ord = at
169 .len()
170 .cmp(&bt.len())
171 .then_with(|| at.cmp(bt))
172 .then_with(|| an.len().cmp(&bn.len()));
173 if ord != Ordering::Equal {
174 return ord;
175 }
176 } else {
177 let ord = ac.to_ascii_lowercase().cmp(&bc.to_ascii_lowercase());
178 if ord != Ordering::Equal {
179 return ord;
180 }
181 ai.next();
182 bi.next();
183 }
184 }
185 }
186 }
187}
188
189fn take_digits(it: &mut std::iter::Peekable<std::str::Chars>) -> String {
190 let mut s = String::new();
191 while let Some(&c) = it.peek() {
192 if !c.is_ascii_digit() {
193 break;
194 }
195 s.push(c);
196 it.next();
197 }
198 s
199}
200
201pub fn file_fingerprint(
202 grants: &dyn PathGrants,
203 docs: &dyn DocumentBackend,
204 path: &str,
205) -> Result<FileFingerprint, WorkspaceError> {
206 let path = grants.require_existing_file(path).map_err(broker_error)?;
207 docs.fingerprint(&path).map_err(WorkspaceError::Io)
208}
209
210pub fn watch_file(
211 grants: &dyn PathGrants,
212 watcher: &dyn WorkspaceWatcher,
213 path: &str,
214) -> Result<(), WorkspaceError> {
215 let path = grants.require_existing_file(path).map_err(broker_error)?;
216 watcher.watch_files(&[path]).map_err(WorkspaceError::Watch)
217}
218
219pub fn watch_files(
220 grants: &dyn PathGrants,
221 watcher: &dyn WorkspaceWatcher,
222 paths: &[String],
223) -> Result<(), WorkspaceError> {
224 let authorized: Vec<String> = paths
227 .iter()
228 .filter_map(|p| grants.require_existing_file(p).ok())
229 .collect();
230 if authorized.is_empty() {
231 watcher.clear_files();
234 return Ok(());
235 }
236 watcher
237 .watch_files(&authorized)
238 .map_err(WorkspaceError::Watch)
239}