| 1 | //! The application's view of a notebook: sections opened through a local replica that |
| 2 | //! publishes their edits to the section file in the background. |
| 3 | |
| 4 | pub use crate::background::{Background, Known, Listener}; |
| 5 | pub use crate::merge::conflict; |
| 6 | use crate::{ |
| 7 | EditStatus, Error, PendingEdit, Remote, Replica, Resolution, Result, SyncWorker, discover, fs, |
| 8 | }; |
| 9 | use onestore::{ |
| 10 | CommitError, ExGuid, PageCreation, PageEdit, RevisionIndex, Stamp, Store, Transaction, |
| 11 | document::Document, |
| 12 | op::{Edit, Op, SectionOp}, |
| 13 | page::Page, |
| 14 | protected, |
| 15 | }; |
| 16 | use std::{ |
| 17 | collections::{BTreeMap, BTreeSet}, |
| 18 | io, |
| 19 | io::Write, |
| 20 | path::{Path, PathBuf}, |
| 21 | sync::{ |
| 22 | Arc, Mutex, |
| 23 | mpsc::{self, Receiver, Sender}, |
| 24 | }, |
| 25 | time::Duration, |
| 26 | }; |
| 27 | |
| 28 | /// A difference between two catalog reads of a notebook, in catalog paths. |
| 29 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 30 | pub enum Change { |
| 31 | /// A section or group appeared, including one replacing a file under an existing path. |
| 32 | Added(String), |
| 33 | /// A section or group is no longer in the notebook. |
| 34 | Removed(String), |
| 35 | /// The same file now lives at another path: a rename or a move between groups. |
| 36 | Moved { from: String, to: String }, |
| 37 | /// A folder's surviving sections and groups changed order. |
| 38 | Reordered(String), |
| 39 | } |
| 40 | |
| 41 | /// Sections and groups are followed by file identity; a group without a TOC only by path. |
| 42 | #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] |
| 43 | enum Key { |
| 44 | File([u8; 16]), |
| 45 | Folder(String), |
| 46 | } |
| 47 | |
| 48 | type Entries = (BTreeMap<Key, String>, BTreeMap<String, Vec<Key>>); |
| 49 | |
| 50 | fn entries(folder: &discover::Folder) -> Entries { |
| 51 | fn walk(folder: &discover::Folder, out: &mut Entries) { |
| 52 | let mut order = Vec::new(); |
| 53 | for section in &folder.sections { |
| 54 | let key = Key::File(section.file_id); |
| 55 | out.0.insert(key.clone(), section.path.clone()); |
| 56 | order.push(key); |
| 57 | } |
| 58 | for group in &folder.groups { |
| 59 | let key = match &group.toc { |
| 60 | Some(toc) => Key::File(toc.file_id), |
| 61 | None => Key::Folder(group.path.clone()), |
| 62 | }; |
| 63 | out.0.insert(key.clone(), group.path.clone()); |
| 64 | order.push(key); |
| 65 | walk(group, out); |
| 66 | } |
| 67 | out.1.insert(folder.path.clone(), order); |
| 68 | } |
| 69 | let mut out = Entries::default(); |
| 70 | walk(folder, &mut out); |
| 71 | out |
| 72 | } |
| 73 | |
| 74 | /// Where a notebook's files live: a mounted directory or an SMB share. Paths are catalog |
| 75 | /// paths, `/`-separated and relative to the notebook root. |
| 76 | pub trait Storage: Send + Sync { |
| 77 | /// Reads the notebook's catalog, reading only the files `cache` holds as listed otherwise. |
| 78 | fn discover( |
| 79 | &self, |
| 80 | cache: &mut discover::Cache, |
| 81 | limits: discover::Limits, |
| 82 | ) -> Result<discover::Folder>; |
| 83 | /// Where the notebook lives, which names its catalog's cache. |
| 84 | fn location(&self) -> String; |
| 85 | /// A folder's entries, as discovery lists them. |
| 86 | fn entries(&self, folder: &str) -> io::Result<Vec<discover::Entry>>; |
| 87 | fn exists(&self, path: &str) -> bool; |
| 88 | /// A section's or TOC's stamp, without reading its body or coordinating with writers. |
| 89 | fn stamp(&self, path: &str) -> io::Result<Stamp>; |
| 90 | fn read(&self, path: &str) -> Result<Vec<u8>>; |
| 91 | /// Reads a file of at most `limit` bytes as it stands, whatever it holds. |
| 92 | fn read_file(&self, path: &str, limit: usize) -> Result<Vec<u8>>; |
| 93 | /// Creates a file holding `bytes`; an existing file is an error. |
| 94 | fn create(&self, path: &str, bytes: &[u8]) -> Result<()>; |
| 95 | fn create_directory(&self, path: &str) -> Result<()>; |
| 96 | /// Gives a file or directory the Windows hidden attribute, where the storage keeps one. |
| 97 | fn hide(&self, path: &str) -> Result<()>; |
| 98 | /// Renames or moves a file or directory; an existing target is an error. |
| 99 | fn rename(&self, from: &str, to: &str) -> Result<()>; |
| 100 | /// Renames the notebook's own folder to `name` beside it once no other writer holds any |
| 101 | /// of `files`; the location it then has. |
| 102 | fn rename_root(&self, name: &str, files: &[String]) -> Result<String>; |
| 103 | /// Renames a file over another, replacing it. |
| 104 | fn replace(&self, from: &str, to: &str) -> Result<()>; |
| 105 | /// Deletes a file or an empty directory. |
| 106 | fn delete(&self, path: &str) -> Result<()>; |
| 107 | /// Names a section or TOC file for its notebook, as `onestore::place`. |
| 108 | fn place(&self, path: &str, ancestor: [u8; 16], name: &str) -> Result<()>; |
| 109 | /// Publishes a transaction made on the file's current image. |
| 110 | fn commit(&self, path: &str, transaction: &Transaction) -> Result<()>; |
| 111 | /// Confirms that the file still has `base`'s stamp and is durable (`onestore::confirm`). |
| 112 | fn confirm(&self, path: &str, base: &Stamp) -> std::result::Result<(), CommitError>; |
| 113 | /// Puts the file `with` in the place of the section or TOC at `path` under the coordination |
| 114 | /// its writers take, provided `path` still has `base`'s stamp. |
| 115 | fn supersede(&self, path: &str, base: &Stamp, with: &str) -> Result<()>; |
| 116 | /// Renames the section file `from` to `to` provided it still has `base`'s stamp, under the |
| 117 | /// coordination its writers take where the storage has one, else just after checking. |
| 118 | fn rename_unchanged(&self, from: &str, to: &str, base: &Stamp) -> Result<()> { |
| 119 | if self.stamp(from)? != *base { |
| 120 | return Err(changed()); |
| 121 | } |
| 122 | self.rename(from, to) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// Makes the entry naming `path` in its folder durable, where the volume lets a folder sync; |
| 127 | /// a mounted share may not. |
| 128 | fn synced_folder(path: &Path) { |
| 129 | #[cfg(unix)] |
| 130 | if let Some(folder) = path.parent() |
| 131 | && let Ok(folder) = fs::File::open(folder) |
| 132 | { |
| 133 | let _ = synced(&folder); |
| 134 | } |
| 135 | #[cfg(not(unix))] |
| 136 | let _ = path; |
| 137 | } |
| 138 | |
| 139 | /// `file.sync_all()`, which on a volume without macOS's F_FULLFSYNC, as an SMB mount is, falls |
| 140 | /// back to a plain fsync, as `onestore`'s commits do. |
| 141 | fn synced(file: &fs::File) -> io::Result<()> { |
| 142 | let result = file.sync_all(); |
| 143 | #[cfg(target_vendor = "apple")] |
| 144 | if result |
| 145 | .as_ref() |
| 146 | .is_err_and(|error| error.raw_os_error() == Some(nix::libc::ENOTSUP)) |
| 147 | { |
| 148 | return nix::unistd::fsync(file).map_err(io::Error::from); |
| 149 | } |
| 150 | result |
| 151 | } |
| 152 | |
| 153 | /// A section that changed while it moved, which stays where it was. |
| 154 | fn changed() -> Error { |
| 155 | io::Error::other("The section changed while it moved").into() |
| 156 | } |
| 157 | |
| 158 | struct Publication { |
| 159 | path: String, |
| 160 | transaction: Transaction, |
| 161 | } |
| 162 | |
| 163 | impl Publication { |
| 164 | async fn commit(self, storage: &dyn Storage) -> Result<()> { |
| 165 | match storage.commit(&self.path, &self.transaction) { |
| 166 | Err(Error::Remote(error)) |
| 167 | if error.state == onestore::CommitState::Unknown |
| 168 | && error.error.kind() == io::ErrorKind::WouldBlock => |
| 169 | { |
| 170 | let expected = self.transaction.stamp(); |
| 171 | fs::durable().await.map_err(|error| CommitError { |
| 172 | state: onestore::CommitState::Unknown, |
| 173 | error, |
| 174 | })?; |
| 175 | storage.confirm(&self.path, &expected)?; |
| 176 | Ok(()) |
| 177 | } |
| 178 | result => result, |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// A mounted notebook directory. |
| 184 | struct Directory(PathBuf); |
| 185 | |
| 186 | impl Directory { |
| 187 | fn path(&self, relative: &str) -> PathBuf { |
| 188 | if relative.is_empty() { |
| 189 | self.0.clone() |
| 190 | } else { |
| 191 | self.0.join(relative) |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | impl Storage for Directory { |
| 197 | fn discover( |
| 198 | &self, |
| 199 | cache: &mut discover::Cache, |
| 200 | limits: discover::Limits, |
| 201 | ) -> Result<discover::Folder> { |
| 202 | Ok(cache.discover(&mut discover::Local::open(&self.0)?, limits)?) |
| 203 | } |
| 204 | |
| 205 | fn location(&self) -> String { |
| 206 | self.0.to_string_lossy().into_owned() |
| 207 | } |
| 208 | |
| 209 | fn entries(&self, folder: &str) -> io::Result<Vec<discover::Entry>> { |
| 210 | use discover::Source; |
| 211 | discover::Local::open(&self.0)?.entries(folder, LIMITS.entries) |
| 212 | } |
| 213 | |
| 214 | fn exists(&self, path: &str) -> bool { |
| 215 | fs::metadata(self.path(path)).is_ok() |
| 216 | } |
| 217 | |
| 218 | fn stamp(&self, path: &str) -> io::Result<Stamp> { |
| 219 | FileRemote(self.path(path)).stamp() |
| 220 | } |
| 221 | |
| 222 | fn read(&self, path: &str) -> Result<Vec<u8>> { |
| 223 | Ok(fs::read_file(self.path(path))?) |
| 224 | } |
| 225 | |
| 226 | fn read_file(&self, path: &str, limit: usize) -> Result<Vec<u8>> { |
| 227 | use std::io::Read; |
| 228 | let mut bytes = Vec::new(); |
| 229 | fs::File::open(self.path(path))? |
| 230 | .take(limit as u64 + 1) |
| 231 | .read_to_end(&mut bytes)?; |
| 232 | if bytes.len() > limit { |
| 233 | return Err(io::Error::from(io::ErrorKind::FileTooLarge).into()); |
| 234 | } |
| 235 | Ok(bytes) |
| 236 | } |
| 237 | |
| 238 | fn create(&self, path: &str, bytes: &[u8]) -> Result<()> { |
| 239 | let path = self.path(path); |
| 240 | if discover::placeholder(&path).is_some_and(|placeholder| fs::metadata(placeholder).is_ok()) |
| 241 | { |
| 242 | return Err(io::Error::from(io::ErrorKind::AlreadyExists).into()); |
| 243 | } |
| 244 | let mut file = fs::File::create_new(&path)?; |
| 245 | file.write_all(bytes)?; |
| 246 | synced(&file)?; |
| 247 | synced_folder(&path); |
| 248 | Ok(()) |
| 249 | } |
| 250 | |
| 251 | fn create_directory(&self, path: &str) -> Result<()> { |
| 252 | Ok(fs::create_dir(self.path(path))?) |
| 253 | } |
| 254 | |
| 255 | /// macOS keeps the attribute as `UF_HIDDEN`, and passes it on to a share it mounted; |
| 256 | /// Linux has no attribute to set, a dot folder being hidden there already. |
| 257 | #[cfg_attr(windows, allow(unsafe_code))] |
| 258 | fn hide(&self, path: &str) -> Result<()> { |
| 259 | #[cfg(target_vendor = "apple")] |
| 260 | { |
| 261 | use nix::sys::stat::{FileFlag, stat}; |
| 262 | let path = self.path(path); |
| 263 | let flags = stat(&path).map_err(io::Error::from)?.st_flags; |
| 264 | let flags = FileFlag::from_bits_retain(flags); |
| 265 | if !flags.contains(FileFlag::UF_HIDDEN) { |
| 266 | nix::unistd::chflags(&path, flags | FileFlag::UF_HIDDEN) |
| 267 | .map_err(io::Error::from)?; |
| 268 | } |
| 269 | } |
| 270 | #[cfg(windows)] |
| 271 | { |
| 272 | use std::os::windows::ffi::OsStrExt; |
| 273 | use windows_sys::Win32::Storage::FileSystem::{ |
| 274 | FILE_ATTRIBUTE_HIDDEN, GetFileAttributesW, INVALID_FILE_ATTRIBUTES, |
| 275 | SetFileAttributesW, |
| 276 | }; |
| 277 | let path: Vec<u16> = self |
| 278 | .path(path) |
| 279 | .as_os_str() |
| 280 | .encode_wide() |
| 281 | .chain([0]) |
| 282 | .collect(); |
| 283 | // SAFETY: `path` is a NUL-terminated UTF-16 string that outlives both calls. |
| 284 | let attributes = unsafe { GetFileAttributesW(path.as_ptr()) }; |
| 285 | if attributes == INVALID_FILE_ATTRIBUTES |
| 286 | || unsafe { SetFileAttributesW(path.as_ptr(), attributes | FILE_ATTRIBUTE_HIDDEN) } |
| 287 | == 0 |
| 288 | { |
| 289 | return Err(io::Error::last_os_error().into()); |
| 290 | } |
| 291 | } |
| 292 | #[cfg(not(any(target_vendor = "apple", windows)))] |
| 293 | let _ = path; |
| 294 | Ok(()) |
| 295 | } |
| 296 | |
| 297 | /// Refuses a name taken by a file, or by one iCloud Drive keeps elsewhere as a placeholder. |
| 298 | fn rename(&self, from: &str, to: &str) -> Result<()> { |
| 299 | let to = self.path(to); |
| 300 | if fs::symlink_metadata(&to).is_ok() |
| 301 | || discover::placeholder(&to) |
| 302 | .is_some_and(|placeholder| fs::metadata(placeholder).is_ok()) |
| 303 | { |
| 304 | return Err(io::Error::from(io::ErrorKind::AlreadyExists).into()); |
| 305 | } |
| 306 | // A file takes a name nothing holds even should one appear meanwhile, where the volume |
| 307 | // can rename so; a mounted share that can't (macOS's smbfs refuses with ENOTSUP, and |
| 308 | // links none) takes a plain rename after the check above. |
| 309 | let from = self.path(from); |
| 310 | let renamed = match fs::metadata(&from)?.is_file() { |
| 311 | true => fs::rename_new(&from, &to), |
| 312 | false => fs::rename(&from, &to), |
| 313 | }; |
| 314 | match renamed { |
| 315 | Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return Err(error.into()), |
| 316 | Err(_) => fs::rename(&from, &to)?, |
| 317 | Ok(()) => {} |
| 318 | } |
| 319 | synced_folder(&to); |
| 320 | Ok(()) |
| 321 | } |
| 322 | |
| 323 | /// A local file system shows no other writer's hold; one that refuses to rename a folder |
| 324 | /// whose files are open says so as the rename fails. |
| 325 | fn rename_root(&self, name: &str, _: &[String]) -> Result<String> { |
| 326 | let to = self.0.with_file_name(name); |
| 327 | // A change of case alone finds the folder itself on a case-insensitive volume. |
| 328 | if fs::metadata(&to).is_ok() && fs::canonicalize(&to)? != self.0 { |
| 329 | return Err(io::Error::from(io::ErrorKind::AlreadyExists).into()); |
| 330 | } |
| 331 | fs::rename(&self.0, &to)?; |
| 332 | Ok(to.to_string_lossy().into_owned()) |
| 333 | } |
| 334 | |
| 335 | fn replace(&self, from: &str, to: &str) -> Result<()> { |
| 336 | Ok(fs::rename(self.path(from), self.path(to))?) |
| 337 | } |
| 338 | |
| 339 | fn delete(&self, path: &str) -> Result<()> { |
| 340 | let path = self.path(path); |
| 341 | if fs::metadata(&path).is_ok_and(|metadata| metadata.is_dir()) { |
| 342 | fs::remove_dir(path)?; |
| 343 | } else { |
| 344 | fs::remove_file(path)?; |
| 345 | } |
| 346 | Ok(()) |
| 347 | } |
| 348 | |
| 349 | fn place(&self, path: &str, ancestor: [u8; 16], name: &str) -> Result<()> { |
| 350 | Ok(fs::place_file(self.path(path), ancestor, name)?) |
| 351 | } |
| 352 | |
| 353 | fn commit(&self, path: &str, transaction: &Transaction) -> Result<()> { |
| 354 | Ok(fs::commit_file(transaction, self.path(path))?) |
| 355 | } |
| 356 | |
| 357 | fn confirm(&self, path: &str, base: &Stamp) -> std::result::Result<(), CommitError> { |
| 358 | fs::confirm_file(self.path(path), base) |
| 359 | } |
| 360 | |
| 361 | fn supersede(&self, path: &str, base: &Stamp, with: &str) -> Result<()> { |
| 362 | Ok(fs::supersede_file(self.path(path), base, self.path(with))?) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | /// A notebook directory on an SMB share, reached through the native-compatible client. |
| 367 | #[cfg(feature = "smb")] |
| 368 | pub struct Share { |
| 369 | client: Arc<crate::smb::Client>, |
| 370 | root: String, |
| 371 | /// Where the sections' replicas are. |
| 372 | copies: PathBuf, |
| 373 | } |
| 374 | |
| 375 | #[cfg(feature = "smb")] |
| 376 | impl Share { |
| 377 | fn path(&self, relative: &str) -> String { |
| 378 | match (self.root.is_empty(), relative.is_empty()) { |
| 379 | (_, true) => self.root.clone(), |
| 380 | (true, false) => relative.to_owned(), |
| 381 | (false, false) => format!("{}/{relative}", self.root), |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | #[cfg(feature = "smb")] |
| 387 | impl Storage for Share { |
| 388 | fn discover( |
| 389 | &self, |
| 390 | cache: &mut discover::Cache, |
| 391 | limits: discover::Limits, |
| 392 | ) -> Result<discover::Folder> { |
| 393 | let mut source = discover::Smb::new(&self.client, &self.root)?.copies(self.copies.clone()); |
| 394 | Ok(cache.discover(&mut source, limits)?) |
| 395 | } |
| 396 | |
| 397 | fn location(&self) -> String { |
| 398 | self.client.location(&self.root) |
| 399 | } |
| 400 | |
| 401 | fn entries(&self, folder: &str) -> io::Result<Vec<discover::Entry>> { |
| 402 | use discover::Source; |
| 403 | discover::Smb::new(&self.client, &self.root)?.entries(folder, LIMITS.entries) |
| 404 | } |
| 405 | |
| 406 | fn stamp(&self, path: &str) -> io::Result<Stamp> { |
| 407 | self.client.stamp(&self.path(path)) |
| 408 | } |
| 409 | |
| 410 | fn exists(&self, path: &str) -> bool { |
| 411 | let (folder, name) = split(path); |
| 412 | self.client |
| 413 | .read_dir(&self.path(folder), LIMITS.entries) |
| 414 | .is_ok_and(|entries| entries.iter().any(|entry| entry.name == name)) |
| 415 | } |
| 416 | |
| 417 | fn read(&self, path: &str) -> Result<Vec<u8>> { |
| 418 | Ok(self |
| 419 | .client |
| 420 | .read_storage(&self.path(path), crate::MAX_FILE_BYTES)?) |
| 421 | } |
| 422 | |
| 423 | fn read_file(&self, path: &str, limit: usize) -> Result<Vec<u8>> { |
| 424 | Ok(self.client.read_asset(&self.path(path), limit)?) |
| 425 | } |
| 426 | |
| 427 | fn create(&self, path: &str, bytes: &[u8]) -> Result<()> { |
| 428 | Ok(self.client.create(&self.path(path), bytes)?) |
| 429 | } |
| 430 | |
| 431 | fn create_directory(&self, path: &str) -> Result<()> { |
| 432 | Ok(self.client.create_directory(&self.path(path))?) |
| 433 | } |
| 434 | |
| 435 | fn hide(&self, path: &str) -> Result<()> { |
| 436 | Ok(self.client.hide(&self.path(path))?) |
| 437 | } |
| 438 | |
| 439 | fn rename(&self, from: &str, to: &str) -> Result<()> { |
| 440 | Ok(self.client.rename(&self.path(from), &self.path(to))?) |
| 441 | } |
| 442 | |
| 443 | fn rename_root(&self, name: &str, files: &[String]) -> Result<String> { |
| 444 | if self.root.is_empty() { |
| 445 | return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); |
| 446 | } |
| 447 | for file in files { |
| 448 | self.client.unheld(&self.path(file))?; |
| 449 | } |
| 450 | let (parent, _) = split(&self.root); |
| 451 | let taken = self |
| 452 | .client |
| 453 | .read_dir(parent, LIMITS.entries)? |
| 454 | .iter() |
| 455 | .any(|entry| { |
| 456 | entry.name.eq_ignore_ascii_case(name) && entry.name != split(&self.root).1 |
| 457 | }); |
| 458 | if taken { |
| 459 | return Err(io::Error::from(io::ErrorKind::AlreadyExists).into()); |
| 460 | } |
| 461 | let to = catalog_path(parent, name); |
| 462 | self.client.rename(&self.root, &to)?; |
| 463 | Ok(self.client.location(&to)) |
| 464 | } |
| 465 | |
| 466 | fn replace(&self, from: &str, to: &str) -> Result<()> { |
| 467 | Ok(self.client.replace(&self.path(from), &self.path(to))?) |
| 468 | } |
| 469 | |
| 470 | fn delete(&self, path: &str) -> Result<()> { |
| 471 | Ok(self.client.delete(&self.path(path))?) |
| 472 | } |
| 473 | |
| 474 | fn place(&self, path: &str, ancestor: [u8; 16], name: &str) -> Result<()> { |
| 475 | Ok(self.client.place(&self.path(path), ancestor, name)?) |
| 476 | } |
| 477 | |
| 478 | fn commit(&self, path: &str, transaction: &Transaction) -> Result<()> { |
| 479 | Ok(self |
| 480 | .client |
| 481 | .commit_transaction(&self.path(path), transaction)?) |
| 482 | } |
| 483 | |
| 484 | fn confirm(&self, path: &str, base: &Stamp) -> std::result::Result<(), CommitError> { |
| 485 | self.client.confirm(&self.path(path), base) |
| 486 | } |
| 487 | |
| 488 | fn supersede(&self, path: &str, base: &Stamp, with: &str) -> Result<()> { |
| 489 | Ok(self |
| 490 | .client |
| 491 | .supersede(&self.path(path), base, &self.path(with))?) |
| 492 | } |
| 493 | |
| 494 | fn rename_unchanged(&self, from: &str, to: &str, base: &Stamp) -> Result<()> { |
| 495 | Ok(self |
| 496 | .client |
| 497 | .rename_unchanged(&self.path(from), &self.path(to), base)?) |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | pub(crate) const LIMITS: discover::Limits = discover::Limits { |
| 502 | entries: 100_000, |
| 503 | bytes_per_file: crate::MAX_FILE_BYTES, |
| 504 | depth: 64, |
| 505 | }; |
| 506 | |
| 507 | const TOC: &str = "Open Notebook.onetoc2"; |
| 508 | /// The recycle bin's folder, a section group of the notebook's. |
| 509 | pub const RECYCLE_BIN: &str = "OneNote_RecycleBin"; |
| 510 | /// How long OneNote 2010 keeps what its recycle bin holds, its `DaysToKeepRecycledItems`. |
| 511 | pub const RECYCLE_DAYS: u32 = 60; |
| 512 | |
| 513 | /// A notebook's files and the cache directory holding its section replicas. |
| 514 | pub struct Notebook { |
| 515 | storage: Box<dyn Storage>, |
| 516 | /// The mounted directory, when sections open through local replicas. |
| 517 | root: Option<PathBuf>, |
| 518 | cache: PathBuf, |
| 519 | catalog: discover::Folder, |
| 520 | /// What reading the catalog took from each file, kept at `listing` in the cache. |
| 521 | read: discover::Cache, |
| 522 | listing: PathBuf, |
| 523 | } |
| 524 | |
| 525 | impl Notebook { |
| 526 | /// The colour OneNote 2010 gives each new notebook beside its default one, COLORREF |
| 527 | /// (`corpus/notebook-management/native/new-notebook`). |
| 528 | pub const NEW_COLOR: u32 = 0x00aeba91; |
| 529 | |
| 530 | pub fn open(root: impl AsRef<Path>, cache: impl AsRef<Path>) -> Result<Self> { |
| 531 | let root = fs::canonicalize(root)?; |
| 532 | Self::with(Box::new(Directory(root.clone())), Some(root), cache) |
| 533 | } |
| 534 | |
| 535 | /// Creates a notebook in the new folder `root`, as OneNote 2010 creates one: a table of |
| 536 | /// contents in the notebook colour `color` (COLORREF) and "New Section 1" holding the |
| 537 | /// page `page` creates. |
| 538 | pub fn create( |
| 539 | root: impl AsRef<Path>, |
| 540 | cache: impl AsRef<Path>, |
| 541 | color: u32, |
| 542 | page: &PageCreation, |
| 543 | ) -> Result<Self> { |
| 544 | fs::create_dir(root.as_ref())?; |
| 545 | let mut notebook = Self::open(root, cache)?; |
| 546 | notebook.edit_toc("", &[onestore::TocEdit::Color(color)])?; |
| 547 | notebook.refresh()?; |
| 548 | notebook.create_section("", "New Section 1", page)?; |
| 549 | Ok(notebook) |
| 550 | } |
| 551 | |
| 552 | /// Opens the notebook at `root` on the share `client` is connected to. Sections open |
| 553 | /// through `Section::resume_smb` with the catalog's paths. |
| 554 | #[cfg(feature = "smb")] |
| 555 | pub fn open_smb( |
| 556 | client: Arc<crate::smb::Client>, |
| 557 | root: &str, |
| 558 | cache: impl AsRef<Path>, |
| 559 | ) -> Result<Self> { |
| 560 | let root = root.replace('\\', "/"); |
| 561 | let copies = crate::location::folder(cache.as_ref(), &client.location(&root)); |
| 562 | Self::with( |
| 563 | Box::new(Share { |
| 564 | client, |
| 565 | root, |
| 566 | copies, |
| 567 | }), |
| 568 | None, |
| 569 | cache, |
| 570 | ) |
| 571 | } |
| 572 | |
| 573 | /// Opens the notebook a Live Share host serves to `guest`. Sections open through |
| 574 | /// `Section::resume_hosted` with the catalog's paths; while the host can't be reached, |
| 575 | /// the notebook opens as its folders were last listed. |
| 576 | #[cfg(feature = "live")] |
| 577 | pub fn open_hosted( |
| 578 | guest: Arc<crate::live::share::Guest>, |
| 579 | cache: impl AsRef<Path>, |
| 580 | ) -> Result<Self> { |
| 581 | let listed = listing(cache.as_ref(), &guest.location()).with_extension("entries.json"); |
| 582 | Self::with( |
| 583 | Box::new(crate::live::share::Hosted::new(guest, listed)), |
| 584 | None, |
| 585 | cache, |
| 586 | ) |
| 587 | } |
| 588 | |
| 589 | /// Opens the notebook whose folder is the root of `documents`. Sections open through |
| 590 | /// `Section::resume_provider` with the catalog's paths; while the provider can't be |
| 591 | /// reached, the notebook opens as its folders were last listed. |
| 592 | pub fn open_provider(documents: Arc<crate::provider::Documents>) -> Result<Self> { |
| 593 | let cache = documents.cache.clone(); |
| 594 | let location = documents.location(); |
| 595 | let listed = listing(&cache, &location).with_extension("entries.json"); |
| 596 | let notebook = Self::with( |
| 597 | Box::new(crate::provider::Tree { documents, listed }), |
| 598 | None, |
| 599 | cache, |
| 600 | )?; |
| 601 | let legacy = crate::location::folder(&notebook.cache, &location).join("published"); |
| 602 | crate::published::adopt(&legacy, |file| { |
| 603 | let section = notebook |
| 604 | .catalog |
| 605 | .sections() |
| 606 | .find(|section| section.file_id == *file)?; |
| 607 | notebook.replica_path(&section.path).ok() |
| 608 | })?; |
| 609 | Ok(notebook) |
| 610 | } |
| 611 | |
| 612 | /// The storage the notebook's files are in, for a Live Share host to serve. |
| 613 | pub fn into_storage(self) -> Box<dyn Storage> { |
| 614 | self.storage |
| 615 | } |
| 616 | |
| 617 | fn with( |
| 618 | storage: Box<dyn Storage>, |
| 619 | root: Option<PathBuf>, |
| 620 | cache: impl AsRef<Path>, |
| 621 | ) -> Result<Self> { |
| 622 | let cache = cache.as_ref().to_path_buf(); |
| 623 | let listing = listing(&cache, &storage.location()); |
| 624 | fs::create_dir_all(listing.parent().unwrap_or(&cache))?; |
| 625 | let mut read = fs::read(&listing) |
| 626 | .ok() |
| 627 | .and_then(|bytes| serde_json::from_slice(&bytes).ok()) |
| 628 | .unwrap_or_default(); |
| 629 | let catalog = storage.discover(&mut read, LIMITS)?; |
| 630 | let location = storage.location(); |
| 631 | let mut claims: BTreeMap<String, Vec<([u8; 16], &str)>> = BTreeMap::new(); |
| 632 | for section in catalog.sections() { |
| 633 | let identity = match (&root, &section.state) { |
| 634 | (Some(_), discover::SectionState::Readable { document, .. }) => *document, |
| 635 | (None, discover::SectionState::Readable { .. }) => section.file_id, |
| 636 | _ => continue, |
| 637 | }; |
| 638 | claims |
| 639 | .entry(replica_location(&location, &section.path, section.copy)) |
| 640 | .or_default() |
| 641 | .push((identity, &section.path)); |
| 642 | } |
| 643 | for (at, sections) in &claims { |
| 644 | let identities: Vec<[u8; 16]> = |
| 645 | sections.iter().map(|(identity, _)| *identity).collect(); |
| 646 | crate::location::claim(&cache, at, &identities, |identity| { |
| 647 | let (_, path) = sections.iter().find(|(held, _)| held == identity)?; |
| 648 | Stamp::of(&storage.read(path).ok()?).ok() |
| 649 | })?; |
| 650 | } |
| 651 | let notebook = Self { |
| 652 | storage, |
| 653 | root, |
| 654 | cache, |
| 655 | catalog, |
| 656 | read, |
| 657 | listing, |
| 658 | }; |
| 659 | notebook.keep_listing(); |
| 660 | notebook.forget_superseded(); |
| 661 | Ok(notebook) |
| 662 | } |
| 663 | |
| 664 | /// Keeps what the catalog read for the next time the notebook opens; failing costs only |
| 665 | /// reading the files again. |
| 666 | fn keep_listing(&self) { |
| 667 | let _ = (|| -> Result<()> { |
| 668 | let folder = self.listing.parent().unwrap_or(Path::new(".")); |
| 669 | let mut file = tempfile::NamedTempFile::new_in(folder)?; |
| 670 | // Whole, as a write per token takes seconds. |
| 671 | file.write_all(&serde_json::to_vec(&self.read).map_err(io::Error::from)?)?; |
| 672 | file.persist(&self.listing).map_err(|error| error.error)?; |
| 673 | Ok(()) |
| 674 | })(); |
| 675 | } |
| 676 | |
| 677 | pub fn catalog(&self) -> &discover::Folder { |
| 678 | &self.catalog |
| 679 | } |
| 680 | |
| 681 | /// The tags the notebook draws with Snowbound's art (`crate::sidecar`); none where it |
| 682 | /// maps none. |
| 683 | pub fn tag_art(&self) -> Result<Vec<crate::sidecar::TagMapping>> { |
| 684 | crate::sidecar::mappings(&*self.storage) |
| 685 | } |
| 686 | |
| 687 | /// The secret of the notebook's live presence room, made where it has none. |
| 688 | pub fn presence_room(&self) -> Result<[u8; 16]> { |
| 689 | crate::sidecar::room(&*self.storage) |
| 690 | } |
| 691 | |
| 692 | /// The picture a mapping names, once its bytes match its name. |
| 693 | pub fn tag_art_file(&self, art: &str) -> Result<Vec<u8>> { |
| 694 | crate::sidecar::art(&*self.storage, art) |
| 695 | } |
| 696 | |
| 697 | /// Maps tag `name` with symbol `shape` to picture `bytes`, a PNG or SVG as `extension` |
| 698 | /// says, making the notebook's hidden `.snowbound` folder where it has none. Returns the |
| 699 | /// notebook's mappings as they then stand. |
| 700 | pub fn map_tag_art( |
| 701 | &self, |
| 702 | name: &str, |
| 703 | shape: u16, |
| 704 | bytes: &[u8], |
| 705 | extension: &str, |
| 706 | ) -> Result<Vec<crate::sidecar::TagMapping>> { |
| 707 | crate::sidecar::map(&*self.storage, name, shape, bytes, extension) |
| 708 | } |
| 709 | |
| 710 | /// The notebook's style themes and which theme each scope takes (`sidecar::themes`). |
| 711 | pub fn themes(&self) -> Result<crate::sidecar::themes::Themes> { |
| 712 | crate::sidecar::themes::read(&*self.storage) |
| 713 | } |
| 714 | |
| 715 | /// Merges `change` into the notebook's themes, making its hidden `.snowbound` folder |
| 716 | /// where it has none; returns the themes as they then stand. |
| 717 | pub fn save_themes( |
| 718 | &self, |
| 719 | change: crate::sidecar::themes::Themes, |
| 720 | ) -> Result<crate::sidecar::themes::Themes> { |
| 721 | crate::sidecar::themes::write(&*self.storage, change) |
| 722 | } |
| 723 | |
| 724 | /// Rereads the notebook and reports what changed since the last catalog, keyed by |
| 725 | /// file identity so a renamed or moved section stays the same section. A failed read |
| 726 | /// keeps the previous catalog: an unreachable notebook is not an empty one. |
| 727 | pub fn refresh(&mut self) -> Result<Vec<Change>> { |
| 728 | let catalog = self.storage.discover(&mut self.read, LIMITS)?; |
| 729 | self.keep_listing(); |
| 730 | let (before, before_orders) = entries(&self.catalog); |
| 731 | let (after, after_orders) = entries(&catalog); |
| 732 | let mut changes = Vec::new(); |
| 733 | for key in before_orders.values().flatten() { |
| 734 | let from = &before[key]; |
| 735 | match after.get(key) { |
| 736 | None => changes.push(Change::Removed(from.clone())), |
| 737 | Some(to) if to != from => changes.push(Change::Moved { |
| 738 | from: from.clone(), |
| 739 | to: to.clone(), |
| 740 | }), |
| 741 | Some(_) => {} |
| 742 | } |
| 743 | } |
| 744 | for key in after_orders.values().flatten() { |
| 745 | if !before.contains_key(key) { |
| 746 | changes.push(Change::Added(after[key].clone())); |
| 747 | } |
| 748 | } |
| 749 | for (folder, order) in &after_orders { |
| 750 | let Some(previous) = before_orders.get(folder) else { |
| 751 | continue; |
| 752 | }; |
| 753 | let kept = |sequence: &[Key], other: &[Key]| -> Vec<Key> { |
| 754 | sequence |
| 755 | .iter() |
| 756 | .filter(|key| other.contains(key)) |
| 757 | .cloned() |
| 758 | .collect() |
| 759 | }; |
| 760 | if kept(previous, order) != kept(order, previous) { |
| 761 | changes.push(Change::Reordered(folder.clone())); |
| 762 | } |
| 763 | } |
| 764 | self.catalog = catalog; |
| 765 | self.forget_superseded(); |
| 766 | Ok(changes) |
| 767 | } |
| 768 | |
| 769 | fn folder(&self, path: &str) -> Result<&discover::Folder> { |
| 770 | self.catalog |
| 771 | .folders() |
| 772 | .find(|folder| folder.path == path) |
| 773 | .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound).into()) |
| 774 | } |
| 775 | |
| 776 | /// A catalog section's path, refusing paths the catalog does not list. |
| 777 | fn section_path(&self, path: &str) -> Result<&discover::Section> { |
| 778 | self.catalog |
| 779 | .sections() |
| 780 | .find(|section| section.path == path) |
| 781 | .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound).into()) |
| 782 | } |
| 783 | |
| 784 | /// A folder's TOC path and file identity, creating the TOC when the folder has none |
| 785 | /// (OneNote names it `Open Notebook.onetoc2`). |
| 786 | fn toc(&self, folder: &str) -> Result<(String, [u8; 16])> { |
| 787 | match &self.folder(folder)?.toc { |
| 788 | Some(toc) => Ok((catalog_path(folder, &toc.filename), toc.file_id)), |
| 789 | None => { |
| 790 | let path = catalog_path(folder, TOC); |
| 791 | // One this change already created, before the catalog was read again. |
| 792 | let bytes = if self.storage.exists(&path) { |
| 793 | self.storage.read(&path)? |
| 794 | } else { |
| 795 | let bytes = onestore::create_table_of_contents(TOC, &[])?; |
| 796 | self.storage.create(&path, &bytes)?; |
| 797 | bytes |
| 798 | }; |
| 799 | Ok((path, onestore::Store::parse(&bytes)?.header.file_id)) |
| 800 | } |
| 801 | } |
| 802 | } |
| 803 | |
| 804 | fn edit_toc(&self, folder: &str, edits: &[onestore::TocEdit]) -> Result<()> { |
| 805 | let (toc, _) = self.toc(folder)?; |
| 806 | self.commit_toc(&toc, edits) |
| 807 | } |
| 808 | |
| 809 | /// Commits `edits` to the TOC at `toc`. A name it still lists for a file gone from its |
| 810 | /// folder passes to the file an edit gives that name; the stale entry goes. |
| 811 | fn commit_toc(&self, toc: &str, edits: &[onestore::TocEdit]) -> Result<()> { |
| 812 | match self.toc_publication(toc, edits)? { |
| 813 | Some(commit) => self.storage.commit(&commit.path, &commit.transaction), |
| 814 | None => Ok(()), |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | fn toc_publication( |
| 819 | &self, |
| 820 | toc: &str, |
| 821 | edits: &[onestore::TocEdit], |
| 822 | ) -> Result<Option<Publication>> { |
| 823 | let unresolved = self |
| 824 | .folder(split(toc).0) |
| 825 | .ok() |
| 826 | .and_then(|folder| folder.toc.as_ref()) |
| 827 | .map_or(&[][..], |toc| &toc.unresolved[..]); |
| 828 | let mut superseded = Vec::new(); |
| 829 | for edit in edits { |
| 830 | if let onestore::TocEdit::Add { filename, .. } |
| 831 | | onestore::TocEdit::Rename { filename, .. } = edit |
| 832 | { |
| 833 | superseded.extend( |
| 834 | unresolved |
| 835 | .iter() |
| 836 | .filter(|entry| { |
| 837 | entry |
| 838 | .filename |
| 839 | .as_deref() |
| 840 | .is_some_and(|name| name.eq_ignore_ascii_case(filename)) |
| 841 | }) |
| 842 | .map(|entry| onestore::TocEdit::Remove { |
| 843 | identity: entry.file, |
| 844 | }), |
| 845 | ); |
| 846 | } |
| 847 | superseded.push(edit.clone()); |
| 848 | } |
| 849 | let source = self.storage.read(toc)?; |
| 850 | Ok( |
| 851 | onestore::edit_table_of_contents(&source, &superseded)?.map(|transaction| { |
| 852 | Publication { |
| 853 | path: toc.into(), |
| 854 | transaction, |
| 855 | } |
| 856 | }), |
| 857 | ) |
| 858 | } |
| 859 | |
| 860 | /// Creates `name.one` in `folder` holding the page `page` creates, in the next of |
| 861 | /// OneNote's section colours, and lists it last in the folder's TOC, as OneNote creates |
| 862 | /// a section. Returns the new catalog path. |
| 863 | pub fn create_section( |
| 864 | &mut self, |
| 865 | folder: &str, |
| 866 | name: &str, |
| 867 | page: &PageCreation, |
| 868 | ) -> Result<String> { |
| 869 | let filename = format!("{name}.one"); |
| 870 | let color = next_color(self.folder(folder)?); |
| 871 | let (_, ancestor) = self.toc(folder)?; |
| 872 | let mut bytes = onestore::create_empty_section(&filename, Some(color))?; |
| 873 | let transaction = { |
| 874 | let arena = onestore::Arena::default(); |
| 875 | let mut section = onestore::Section::open(&arena, bytes.clone())?; |
| 876 | let edit = Edit { |
| 877 | at: crate::now(), |
| 878 | ops: vec![Op::Section(SectionOp::Create(page.clone()))], |
| 879 | }; |
| 880 | section.apply(page.author(), &edit)?; |
| 881 | section.seal()? |
| 882 | }; |
| 883 | if let Some(transaction) = transaction { |
| 884 | transaction.apply(&mut bytes)?; |
| 885 | } |
| 886 | let path = catalog_path(folder, &filename); |
| 887 | self.storage.create(&path, &bytes)?; |
| 888 | self.storage.place(&path, ancestor, &filename)?; |
| 889 | let identity = onestore::Store::parse(&bytes)?.header.file_id; |
| 890 | self.edit_toc( |
| 891 | folder, |
| 892 | &[onestore::TocEdit::Add { |
| 893 | filename: filename.clone(), |
| 894 | identity, |
| 895 | group: false, |
| 896 | }], |
| 897 | )?; |
| 898 | self.refresh()?; |
| 899 | Ok(path) |
| 900 | } |
| 901 | |
| 902 | /// Creates a section group: a folder with its own TOC, listed last in the parent's TOC. |
| 903 | pub fn create_group(&mut self, folder: &str, name: &str) -> Result<String> { |
| 904 | self.folder(folder)?; |
| 905 | if !component(name) { |
| 906 | return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); |
| 907 | } |
| 908 | let (_, ancestor) = self.toc(folder)?; |
| 909 | let group = catalog_path(folder, name); |
| 910 | self.storage.create_directory(&group)?; |
| 911 | let bytes = onestore::create_table_of_contents(TOC, &[])?; |
| 912 | let path = catalog_path(&group, TOC); |
| 913 | self.storage.create(&path, &bytes)?; |
| 914 | self.storage.place(&path, ancestor, name)?; |
| 915 | let identity = onestore::Store::parse(&bytes)?.header.file_id; |
| 916 | self.edit_toc( |
| 917 | folder, |
| 918 | &[onestore::TocEdit::Add { |
| 919 | filename: name.to_owned(), |
| 920 | identity, |
| 921 | group: true, |
| 922 | }], |
| 923 | )?; |
| 924 | self.refresh()?; |
| 925 | Ok(group) |
| 926 | } |
| 927 | |
| 928 | /// Renames a section or section group: the file or folder and its TOC entry. |
| 929 | pub fn rename(&mut self, path: &str, name: &str) -> Result<String> { |
| 930 | let (folder, entry) = split(path); |
| 931 | let Entry { |
| 932 | filename, |
| 933 | identity, |
| 934 | copy, |
| 935 | } = self.entry(folder, entry)?; |
| 936 | let target = if filename.to_ascii_lowercase().ends_with(".one") { |
| 937 | format!("{name}.one") |
| 938 | } else { |
| 939 | name.to_owned() |
| 940 | }; |
| 941 | let renamed = catalog_path(folder, &target); |
| 942 | if !component(&target) || self.storage.exists(&renamed) { |
| 943 | return Err(io::Error::from(io::ErrorKind::AlreadyExists).into()); |
| 944 | } |
| 945 | self.storage |
| 946 | .rename(&catalog_path(folder, &filename), &renamed)?; |
| 947 | if !copy { |
| 948 | let (_, ancestor) = self.toc(folder)?; |
| 949 | let placed = if target.ends_with(".one") { |
| 950 | renamed.clone() |
| 951 | } else { |
| 952 | catalog_path(&renamed, TOC) |
| 953 | }; |
| 954 | self.storage.place(&placed, ancestor, &target)?; |
| 955 | } |
| 956 | if let Some(identity) = identity { |
| 957 | let (toc, _) = self.toc(folder)?; |
| 958 | let edit = if lists(&self.storage.read(&toc)?, identity)? { |
| 959 | onestore::TocEdit::Rename { |
| 960 | identity, |
| 961 | filename: target, |
| 962 | } |
| 963 | } else { |
| 964 | onestore::TocEdit::Add { |
| 965 | identity, |
| 966 | filename: target, |
| 967 | group: !filename.to_ascii_lowercase().ends_with(".one"), |
| 968 | } |
| 969 | }; |
| 970 | self.commit_toc(&toc, &[edit])?; |
| 971 | } |
| 972 | self.refresh()?; |
| 973 | Ok(renamed) |
| 974 | } |
| 975 | |
| 976 | /// Renames the notebook's folder to `name`, as OneNote 2010 finds a notebook folder renamed |
| 977 | /// outside it: no file inside changes, and it opens the folder again by its new name. Refused, |
| 978 | /// `WouldBlock`, while another writer holds one of its sections or tables of contents, and |
| 979 | /// `AlreadyExists` where `name` is taken. The replicas and the catalog's listing follow, so |
| 980 | /// edits waiting publish to the renamed folder; every replica must be closed. Returns the |
| 981 | /// notebook's new location, as `crate::location` names it. |
| 982 | pub fn rename_folder(mut self, name: &str) -> Result<String> { |
| 983 | if !folder_name(name) { |
| 984 | return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); |
| 985 | } |
| 986 | self.replicas_closed()?; |
| 987 | let from = self.storage.location(); |
| 988 | let files: Vec<String> = (self.catalog.folders()) |
| 989 | .flat_map(|folder| { |
| 990 | let toc = folder.toc.as_ref().map(|toc| &toc.filename); |
| 991 | (toc.map(|toc| catalog_path(&folder.path, toc)).into_iter()) |
| 992 | .chain(folder.sections.iter().map(|section| section.path.clone())) |
| 993 | }) |
| 994 | .collect(); |
| 995 | let to = self.storage.rename_root(name, &files)?; |
| 996 | crate::location::moved(&self.cache, &from, &to)?; |
| 997 | let _ = fs::remove_file(&self.listing); |
| 998 | self.listing = listing(&self.cache, &to); |
| 999 | self.keep_listing(); |
| 1000 | Ok(to) |
| 1001 | } |
| 1002 | |
| 1003 | /// Waits for browser cache receipts before moving the notebook and its replicas. |
| 1004 | pub async fn rename_folder_async(self, name: &str) -> Result<String> { |
| 1005 | #[cfg(target_arch = "wasm32")] |
| 1006 | { |
| 1007 | let deadline = web_time::Instant::now() + Duration::from_secs(30); |
| 1008 | let (_, retry) = crate::task::channel(); |
| 1009 | loop { |
| 1010 | match self.replicas_closed() { |
| 1011 | Err(error) if error.busy() && web_time::Instant::now() < deadline => { |
| 1012 | crate::task::wait(&retry, Some(Duration::from_millis(50))).await; |
| 1013 | } |
| 1014 | result => { |
| 1015 | result?; |
| 1016 | break; |
| 1017 | } |
| 1018 | } |
| 1019 | } |
| 1020 | } |
| 1021 | self.rename_folder(name) |
| 1022 | } |
| 1023 | |
| 1024 | fn replicas_closed(&self) -> Result<()> { |
| 1025 | let from = self.storage.location(); |
| 1026 | let locations = std::iter::once(from.clone()).chain( |
| 1027 | self.catalog |
| 1028 | .sections() |
| 1029 | .filter(|section| section.copy) |
| 1030 | .map(|section| replica_location(&from, &section.path, section.copy)), |
| 1031 | ); |
| 1032 | for location in locations { |
| 1033 | let entries = match fs::read_dir(crate::location::folder(&self.cache, &location)) { |
| 1034 | Ok(entries) => entries, |
| 1035 | Err(error) if error.kind() == io::ErrorKind::NotFound => continue, |
| 1036 | Err(error) => return Err(error.into()), |
| 1037 | }; |
| 1038 | for entry in entries { |
| 1039 | let path = entry?.path(); |
| 1040 | if path.extension() == Some("sqlite".as_ref()) { |
| 1041 | drop(crate::closed(&path)?); |
| 1042 | } |
| 1043 | } |
| 1044 | } |
| 1045 | Ok(()) |
| 1046 | } |
| 1047 | |
| 1048 | /// Sets a section's colour (COLORREF) in its own metadata, where OneNote keeps it. |
| 1049 | pub fn set_section_color(&mut self, path: &str, color: Option<u32>) -> Result<()> { |
| 1050 | let path = self.section_path(path)?.path.clone(); |
| 1051 | let arena = onestore::Arena::default(); |
| 1052 | let mut section = onestore::Section::open(&arena, self.storage.read(&path)?)?; |
| 1053 | let edit = Edit { |
| 1054 | at: crate::now(), |
| 1055 | ops: vec![Op::Section(SectionOp::Color(color))], |
| 1056 | }; |
| 1057 | section.apply("", &edit)?; |
| 1058 | if let Some(transaction) = section.seal()? { |
| 1059 | self.storage.commit(&path, &transaction)?; |
| 1060 | } |
| 1061 | self.refresh()?; |
| 1062 | Ok(()) |
| 1063 | } |
| 1064 | |
| 1065 | /// Sets the notebook's colour (COLORREF) in its root table of contents, as OneNote 2010's |
| 1066 | /// Notebook Properties does (`corpus/section-color`). |
| 1067 | pub fn set_color(&mut self, color: u32) -> Result<()> { |
| 1068 | self.edit_toc("", &[onestore::TocEdit::Color(color)])?; |
| 1069 | self.refresh().map(drop) |
| 1070 | } |
| 1071 | |
| 1072 | /// Orders a folder's sections and groups; entries left out follow in their current order. |
| 1073 | pub fn reorder(&mut self, folder: &str, paths: &[&str]) -> Result<()> { |
| 1074 | let mut identities = Vec::new(); |
| 1075 | for path in paths { |
| 1076 | let (parent, entry) = split(path); |
| 1077 | if parent != folder { |
| 1078 | return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); |
| 1079 | } |
| 1080 | identities.extend(self.entry(folder, entry)?.identity); |
| 1081 | } |
| 1082 | self.edit_toc(folder, &[onestore::TocEdit::Order(identities)])?; |
| 1083 | self.refresh().map(drop) |
| 1084 | } |
| 1085 | |
| 1086 | /// Deletes a section or section group the way OneNote 2010 does. A section's file moves |
| 1087 | /// into the notebook's `OneNote_RecycleBin` folder, a section group with its own TOC that |
| 1088 | /// lists it (and that the root TOC lists). A group's sections, in its groups too, move |
| 1089 | /// there the same way, then its folders go. Either way its folder's TOC entry goes. |
| 1090 | pub fn delete(&mut self, path: &str) -> Result<()> { |
| 1091 | let (folder, entry) = split(path); |
| 1092 | let deleted = self.entry(folder, entry)?; |
| 1093 | if path == RECYCLE_BIN { |
| 1094 | return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); |
| 1095 | } |
| 1096 | if deleted.filename.to_ascii_lowercase().ends_with(".one") { |
| 1097 | self.bin_section(path, &deleted)?; |
| 1098 | } else { |
| 1099 | // Sections first, then each folder once it is empty, deepest first. |
| 1100 | let mut sections = Vec::new(); |
| 1101 | let mut folders = Vec::new(); |
| 1102 | let mut pending = vec![self.folder(path)?]; |
| 1103 | while let Some(group) = pending.pop() { |
| 1104 | // Its folder could not be emptied, so nothing moves. |
| 1105 | if let Some(entry) = group.unavailable.first() { |
| 1106 | return Err(io::Error::new( |
| 1107 | io::ErrorKind::PermissionDenied, |
| 1108 | entry.error.clone(), |
| 1109 | ) |
| 1110 | .into()); |
| 1111 | } |
| 1112 | sections.extend( |
| 1113 | group |
| 1114 | .sections |
| 1115 | .iter() |
| 1116 | .map(|section| (section.path.clone(), Entry::of(group, section))), |
| 1117 | ); |
| 1118 | folders.push(( |
| 1119 | group.path.clone(), |
| 1120 | group.toc.as_ref().map(|toc| toc.filename.clone()), |
| 1121 | )); |
| 1122 | pending.extend(&group.groups); |
| 1123 | } |
| 1124 | for (section, entry) in sections { |
| 1125 | self.bin_section(&section, &entry)?; |
| 1126 | } |
| 1127 | for (group, toc) in folders.into_iter().rev() { |
| 1128 | if let Some(toc) = toc { |
| 1129 | self.storage.delete(&catalog_path(&group, &toc))?; |
| 1130 | } |
| 1131 | self.storage.delete(&group)?; |
| 1132 | } |
| 1133 | } |
| 1134 | if let Some(identity) = deleted.identity { |
| 1135 | self.edit_toc(folder, &[onestore::TocEdit::Remove { identity }])?; |
| 1136 | } |
| 1137 | self.refresh().map(drop) |
| 1138 | } |
| 1139 | |
| 1140 | /// The recycle bin's TOC path and file identity, creating the bin as OneNote does: a |
| 1141 | /// section group the root TOC lists. A bin the root TOC misses is listed again. |
| 1142 | fn bin(&self) -> Result<(String, [u8; 16])> { |
| 1143 | let (toc, identity, publication) = self.prepare_bin()?; |
| 1144 | if let Some(commit) = publication { |
| 1145 | self.storage.commit(&commit.path, &commit.transaction)?; |
| 1146 | } |
| 1147 | Ok((toc, identity)) |
| 1148 | } |
| 1149 | |
| 1150 | fn prepare_bin(&self) -> Result<(String, [u8; 16], Option<Publication>)> { |
| 1151 | if let Some(entry) = self |
| 1152 | .catalog |
| 1153 | .unavailable |
| 1154 | .iter() |
| 1155 | .find(|entry| entry.path == RECYCLE_BIN) |
| 1156 | { |
| 1157 | return Err( |
| 1158 | io::Error::new(io::ErrorKind::PermissionDenied, entry.error.clone()).into(), |
| 1159 | ); |
| 1160 | } |
| 1161 | // A bin OneNote made may name its TOC otherwise; a second TOC would hide the folder. |
| 1162 | let bin_toc = match self.folder(RECYCLE_BIN) { |
| 1163 | Ok(discover::Folder { toc: Some(toc), .. }) => catalog_path(RECYCLE_BIN, &toc.filename), |
| 1164 | _ => { |
| 1165 | let bin_toc = catalog_path(RECYCLE_BIN, TOC); |
| 1166 | if !self.storage.exists(&bin_toc) { |
| 1167 | if !self.storage.exists(RECYCLE_BIN) { |
| 1168 | self.storage.create_directory(RECYCLE_BIN)?; |
| 1169 | } |
| 1170 | let bytes = onestore::create_table_of_contents(TOC, &[])?; |
| 1171 | self.storage.create(&bin_toc, &bytes)?; |
| 1172 | } |
| 1173 | bin_toc |
| 1174 | } |
| 1175 | }; |
| 1176 | let identity = onestore::Store::parse(&self.storage.read(&bin_toc)?)? |
| 1177 | .header |
| 1178 | .file_id; |
| 1179 | let (root, root_identity) = self.toc("")?; |
| 1180 | // OneNote takes a TOC placed under another parent for a new one. |
| 1181 | let publication = if !lists(&self.storage.read(&root)?, identity)? { |
| 1182 | self.storage.place(&bin_toc, root_identity, RECYCLE_BIN)?; |
| 1183 | self.toc_publication( |
| 1184 | &root, |
| 1185 | &[onestore::TocEdit::Add { |
| 1186 | filename: RECYCLE_BIN.into(), |
| 1187 | identity, |
| 1188 | group: true, |
| 1189 | }], |
| 1190 | )? |
| 1191 | } else { |
| 1192 | None |
| 1193 | }; |
| 1194 | Ok((bin_toc, identity, publication)) |
| 1195 | } |
| 1196 | |
| 1197 | /// Moves the section file at `path`, its folder's `entry`, into the recycle bin, under a |
| 1198 | /// name no binned section has, and lists it there; its own folder's TOC is the caller's. |
| 1199 | fn bin_section(&self, path: &str, entry: &Entry) -> Result<()> { |
| 1200 | let binned = self.send_to_bin(path, &entry.filename, None)?; |
| 1201 | self.list_binned(binned, entry) |
| 1202 | } |
| 1203 | |
| 1204 | /// Moves the section file at `path`, named `filename`, into the recycle bin under a name no |
| 1205 | /// binned section has, provided it still has `base`'s stamp where one is given: the bin's |
| 1206 | /// TOC and identity, and the name it took there. |
| 1207 | fn send_to_bin( |
| 1208 | &self, |
| 1209 | path: &str, |
| 1210 | filename: &str, |
| 1211 | base: Option<&Stamp>, |
| 1212 | ) -> Result<(String, [u8; 16], String)> { |
| 1213 | let (bin_toc, bin_identity) = self.bin()?; |
| 1214 | let mut target = filename.to_owned(); |
| 1215 | let mut attempt = 1; |
| 1216 | while self.storage.exists(&catalog_path(RECYCLE_BIN, &target)) { |
| 1217 | attempt += 1; |
| 1218 | let (stem, extension) = filename.rsplit_once('.').unwrap_or((filename, "")); |
| 1219 | target = format!("{stem} ({attempt}).{extension}"); |
| 1220 | } |
| 1221 | let binned = catalog_path(RECYCLE_BIN, &target); |
| 1222 | let renamed = match base { |
| 1223 | Some(base) => self.storage.rename_unchanged(path, &binned, base), |
| 1224 | None => self.storage.rename(path, &binned), |
| 1225 | }; |
| 1226 | // A rename that landed before what followed it failed, a close or a folder's sync. |
| 1227 | if let Err(error) = renamed |
| 1228 | && (self.storage.exists(path) || !self.storage.exists(&binned)) |
| 1229 | { |
| 1230 | return Err(error); |
| 1231 | } |
| 1232 | Ok((bin_toc, bin_identity, target)) |
| 1233 | } |
| 1234 | |
| 1235 | /// Places and lists the section `entry`, which `send_to_bin` moved, in the recycle bin. |
| 1236 | fn list_binned( |
| 1237 | &self, |
| 1238 | (bin_toc, bin_identity, target): (String, [u8; 16], String), |
| 1239 | entry: &Entry, |
| 1240 | ) -> Result<()> { |
| 1241 | let (false, Some(identity)) = (entry.copy, entry.identity) else { |
| 1242 | return Ok(()); |
| 1243 | }; |
| 1244 | self.storage |
| 1245 | .place(&catalog_path(RECYCLE_BIN, &target), bin_identity, &target)?; |
| 1246 | self.commit_toc( |
| 1247 | &bin_toc, |
| 1248 | &[onestore::TocEdit::Add { |
| 1249 | filename: target, |
| 1250 | identity, |
| 1251 | group: false, |
| 1252 | }], |
| 1253 | ) |
| 1254 | } |
| 1255 | |
| 1256 | /// Keeps copies of `pages` in the notebook's recycle bin, as OneNote 2010 does with a |
| 1257 | /// page it deletes: in `OneNote_RecycleBin/OneNote_DeletedPages.one`, each at the top |
| 1258 | /// level with its identity, title, date and creation time. The caller then deletes the |
| 1259 | /// pages from their section. |
| 1260 | pub fn recycle_pages(&mut self, pages: &[Page], author: &str) -> Result<()> { |
| 1261 | crate::task::blocking(self.recycle_pages_async(pages, author))? |
| 1262 | } |
| 1263 | |
| 1264 | /// Recycles pages after the browser host acknowledges each destination append. |
| 1265 | pub async fn recycle_pages_async(&mut self, pages: &[Page], author: &str) -> Result<()> { |
| 1266 | const DELETED: &str = "OneNote_DeletedPages.one"; |
| 1267 | // A rejected host receipt leaves its append queued ahead of this retry. |
| 1268 | fs::durable().await?; |
| 1269 | let (bin_toc, bin_identity, publication) = self.prepare_bin()?; |
| 1270 | if let Some(commit) = publication { |
| 1271 | commit.commit(self.storage.as_ref()).await?; |
| 1272 | } |
| 1273 | let path = catalog_path(RECYCLE_BIN, DELETED); |
| 1274 | if !self.storage.exists(&path) { |
| 1275 | // OneNote's "Deleted Pages" section is grey. |
| 1276 | let bytes = onestore::create_empty_section(DELETED, Some(0x00e1e1e1))?; |
| 1277 | self.storage.create(&path, &bytes)?; |
| 1278 | } |
| 1279 | let mut bytes = self.storage.read(&path)?; |
| 1280 | // Listed and placed too when an earlier delete made the file but not its entry. |
| 1281 | let identity = onestore::Store::parse(&bytes)?.header.file_id; |
| 1282 | if !lists(&self.storage.read(&bin_toc)?, identity)? { |
| 1283 | self.storage.place(&path, bin_identity, DELETED)?; |
| 1284 | if let Some(commit) = self.toc_publication( |
| 1285 | &bin_toc, |
| 1286 | &[onestore::TocEdit::Add { |
| 1287 | filename: DELETED.into(), |
| 1288 | identity, |
| 1289 | group: false, |
| 1290 | }], |
| 1291 | )? { |
| 1292 | commit.commit(self.storage.as_ref()).await?; |
| 1293 | } |
| 1294 | bytes = self.storage.read(&path)?; |
| 1295 | } |
| 1296 | let transaction = { |
| 1297 | let arena = onestore::Arena::default(); |
| 1298 | let mut section = onestore::Section::open(&arena, bytes)?; |
| 1299 | let mut ops = Vec::new(); |
| 1300 | for page in pages { |
| 1301 | ops.push(moved(page, author)?); |
| 1302 | } |
| 1303 | section.apply( |
| 1304 | author, |
| 1305 | &Edit { |
| 1306 | at: crate::now(), |
| 1307 | ops, |
| 1308 | }, |
| 1309 | )?; |
| 1310 | section.seal()? |
| 1311 | }; |
| 1312 | if let Some(transaction) = transaction { |
| 1313 | Publication { path, transaction } |
| 1314 | .commit(self.storage.as_ref()) |
| 1315 | .await?; |
| 1316 | } |
| 1317 | fs::durable().await?; |
| 1318 | self.refresh().map(drop) |
| 1319 | } |
| 1320 | |
| 1321 | /// Takes the pages `identities` names out of the recycle bin's Deleted Pages in one |
| 1322 | /// revision, as OneNote 2010 does when Undo brings deleted pages back. Pages not there |
| 1323 | /// are passed over. |
| 1324 | pub fn unrecycle_pages(&mut self, identities: &[[u8; 16]]) -> Result<()> { |
| 1325 | crate::task::blocking(self.unrecycle_pages_async(identities))? |
| 1326 | } |
| 1327 | |
| 1328 | /// Removes recycled pages after the browser host acknowledges their deletion append. |
| 1329 | pub async fn unrecycle_pages_async(&mut self, identities: &[[u8; 16]]) -> Result<()> { |
| 1330 | fs::durable().await?; |
| 1331 | let path = catalog_path(RECYCLE_BIN, "OneNote_DeletedPages.one"); |
| 1332 | if !self.storage.exists(&path) { |
| 1333 | return Ok(()); |
| 1334 | } |
| 1335 | let bytes = self.storage.read(&path)?; |
| 1336 | let binned: Vec<ExGuid> = stored_pages(&bytes)? |
| 1337 | .into_iter() |
| 1338 | .filter(|stored| { |
| 1339 | stored |
| 1340 | .page |
| 1341 | .identity |
| 1342 | .is_some_and(|id| identities.contains(&id)) |
| 1343 | }) |
| 1344 | .map(|stored| stored.space) |
| 1345 | .collect(); |
| 1346 | if binned.is_empty() { |
| 1347 | return Ok(()); |
| 1348 | } |
| 1349 | let transaction = { |
| 1350 | let arena = onestore::Arena::default(); |
| 1351 | let mut section = onestore::Section::open(&arena, bytes)?; |
| 1352 | section.apply( |
| 1353 | "", |
| 1354 | &Edit { |
| 1355 | at: crate::now(), |
| 1356 | ops: vec![Op::Section(SectionOp::Delete(binned))], |
| 1357 | }, |
| 1358 | )?; |
| 1359 | section.seal()? |
| 1360 | }; |
| 1361 | if let Some(transaction) = transaction { |
| 1362 | Publication { path, transaction } |
| 1363 | .commit(self.storage.as_ref()) |
| 1364 | .await?; |
| 1365 | } |
| 1366 | fs::durable().await?; |
| 1367 | self.refresh().map(drop) |
| 1368 | } |
| 1369 | |
| 1370 | /// Deletes for good what OneNote 2010 prunes from the recycle bin at `now`, Time32 seconds |
| 1371 | /// since 1980: each page of Deleted Pages last changed over `RECYCLE_DAYS` before, in one |
| 1372 | /// revision, and each binned section none of whose pages changed since |
| 1373 | /// (`corpus/recycle-purge`). OneNote judges by the pages' own last change, not when they |
| 1374 | /// were deleted, and leaves a pruned section's entry in the bin's TOC, as this does. |
| 1375 | /// Returns how many pages and sections went. |
| 1376 | pub fn purge_recycle_bin(&mut self, now: u32) -> Result<usize> { |
| 1377 | const DELETED: &str = "OneNote_DeletedPages.one"; |
| 1378 | let now = (u64::from(now) + 11_960_006_400) * 10_000_000; |
| 1379 | let expired = |modified: Option<u64>| { |
| 1380 | modified.is_some_and(|modified| { |
| 1381 | now.saturating_sub(modified) > u64::from(RECYCLE_DAYS) * 86_400 * 10_000_000 |
| 1382 | }) |
| 1383 | }; |
| 1384 | let Ok(bin) = self.folder(RECYCLE_BIN) else { |
| 1385 | return Ok(0); |
| 1386 | }; |
| 1387 | let sections: Vec<String> = bin |
| 1388 | .sections |
| 1389 | .iter() |
| 1390 | .map(|section| section.path.clone()) |
| 1391 | .collect(); |
| 1392 | let mut purged = 0; |
| 1393 | for path in sections { |
| 1394 | let bytes = self.storage.read(&path)?; |
| 1395 | // A protected section, or one the model cannot read, stays. |
| 1396 | let Ok(pages) = stored_pages(&bytes) else { |
| 1397 | continue; |
| 1398 | }; |
| 1399 | if split(&path).1.eq_ignore_ascii_case(DELETED) { |
| 1400 | let old: Vec<ExGuid> = pages |
| 1401 | .iter() |
| 1402 | .filter(|page| expired(page.modified)) |
| 1403 | .map(|page| page.space) |
| 1404 | .collect(); |
| 1405 | if old.is_empty() { |
| 1406 | continue; |
| 1407 | } |
| 1408 | let arena = onestore::Arena::default(); |
| 1409 | let mut section = onestore::Section::open(&arena, bytes)?; |
| 1410 | section.apply( |
| 1411 | "", |
| 1412 | &Edit { |
| 1413 | at: crate::now(), |
| 1414 | ops: vec![Op::Section(SectionOp::Delete(old.clone()))], |
| 1415 | }, |
| 1416 | )?; |
| 1417 | if let Some(transaction) = section.seal()? { |
| 1418 | self.storage.commit(&path, &transaction)?; |
| 1419 | } |
| 1420 | purged += old.len(); |
| 1421 | } else if !pages.is_empty() && pages.iter().all(|page| expired(page.modified)) { |
| 1422 | self.storage.delete(&path)?; |
| 1423 | purged += 1; |
| 1424 | } |
| 1425 | } |
| 1426 | if purged > 0 { |
| 1427 | self.refresh()?; |
| 1428 | } |
| 1429 | Ok(purged) |
| 1430 | } |
| 1431 | |
| 1432 | /// Empties the recycle bin as OneNote 2010's Empty Recycle Bin does: every page of |
| 1433 | /// Deleted Pages goes in one revision, and every binned section's file goes, its entry |
| 1434 | /// left in the bin's TOC (`corpus/recycle-bin-view`). |
| 1435 | pub fn empty_recycle_bin(&mut self) -> Result<()> { |
| 1436 | let Ok(bin) = self.folder(RECYCLE_BIN) else { |
| 1437 | return Ok(()); |
| 1438 | }; |
| 1439 | let sections: Vec<String> = (bin.sections.iter()) |
| 1440 | .filter(|section| !section.copy) |
| 1441 | .map(|section| section.path.clone()) |
| 1442 | .collect(); |
| 1443 | for path in sections { |
| 1444 | if !split(&path) |
| 1445 | .1 |
| 1446 | .eq_ignore_ascii_case("OneNote_DeletedPages.one") |
| 1447 | { |
| 1448 | self.storage.delete(&path)?; |
| 1449 | continue; |
| 1450 | } |
| 1451 | let arena = onestore::Arena::default(); |
| 1452 | let mut section = onestore::Section::open(&arena, self.storage.read(&path)?)?; |
| 1453 | let pages: Vec<ExGuid> = section |
| 1454 | .pages()? |
| 1455 | .into_iter() |
| 1456 | .map(|(space, ..)| space) |
| 1457 | .collect(); |
| 1458 | if pages.is_empty() { |
| 1459 | continue; |
| 1460 | } |
| 1461 | section.apply( |
| 1462 | "", |
| 1463 | &Edit { |
| 1464 | at: crate::now(), |
| 1465 | ops: vec![Op::Section(SectionOp::Delete(pages))], |
| 1466 | }, |
| 1467 | )?; |
| 1468 | if let Some(transaction) = section.seal()? { |
| 1469 | self.storage.commit(&path, &transaction)?; |
| 1470 | } |
| 1471 | } |
| 1472 | self.refresh().map(drop) |
| 1473 | } |
| 1474 | |
| 1475 | /// The table of contents of the folder at catalog path `folder` as its file stores it. |
| 1476 | pub fn read_toc(&self, folder: &str) -> Result<Vec<u8>> { |
| 1477 | let toc = self.folder(folder)?.toc.as_ref(); |
| 1478 | let toc = toc.ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; |
| 1479 | self.storage.read(&catalog_path(folder, &toc.filename)) |
| 1480 | } |
| 1481 | |
| 1482 | /// Moves a section or section group into the folder at catalog path `folder`, last, as |
| 1483 | /// OneNote moves one dragged onto a group: the file or folder moves and each TOC's |
| 1484 | /// entry follows it. Returns its new catalog path. |
| 1485 | pub fn move_entry(&mut self, path: &str, folder: &str) -> Result<String> { |
| 1486 | let (from, entry) = split(path); |
| 1487 | let Entry { |
| 1488 | filename, |
| 1489 | identity, |
| 1490 | copy, |
| 1491 | } = self.entry(from, entry)?; |
| 1492 | self.folder(folder)?; |
| 1493 | let group = !filename.to_ascii_lowercase().ends_with(".one"); |
| 1494 | let target = catalog_path(folder, &filename); |
| 1495 | if from == folder |
| 1496 | || path == RECYCLE_BIN |
| 1497 | || group && (folder == path || folder.starts_with(&format!("{path}/"))) |
| 1498 | || self.storage.exists(&target) |
| 1499 | { |
| 1500 | return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); |
| 1501 | } |
| 1502 | let registered = if let (Some(identity), Some(toc)) = (identity, &self.folder(from)?.toc) { |
| 1503 | lists( |
| 1504 | &self.storage.read(&catalog_path(from, &toc.filename))?, |
| 1505 | identity, |
| 1506 | )? |
| 1507 | .then_some(identity) |
| 1508 | } else { |
| 1509 | None |
| 1510 | }; |
| 1511 | let (_, ancestor) = self.toc(folder)?; |
| 1512 | self.storage.rename(path, &target)?; |
| 1513 | if !copy { |
| 1514 | let placed = if group { |
| 1515 | catalog_path(&target, TOC) |
| 1516 | } else { |
| 1517 | target.clone() |
| 1518 | }; |
| 1519 | self.storage.place(&placed, ancestor, &filename)?; |
| 1520 | if let Some(identity) = identity { |
| 1521 | self.edit_toc( |
| 1522 | folder, |
| 1523 | &[onestore::TocEdit::Add { |
| 1524 | filename, |
| 1525 | identity, |
| 1526 | group, |
| 1527 | }], |
| 1528 | )?; |
| 1529 | } |
| 1530 | } |
| 1531 | if let Some(identity) = registered { |
| 1532 | self.edit_toc(from, &[onestore::TocEdit::Remove { identity }])?; |
| 1533 | } |
| 1534 | self.refresh()?; |
| 1535 | Ok(target) |
| 1536 | } |
| 1537 | |
| 1538 | /// Copies the section at catalog `path`, whose replica is `replica`, into the folder |
| 1539 | /// `folder` of `target`, after its section `after` or else last, as OneNote 2010's Move or |
| 1540 | /// Copy puts a section in another notebook: a file of its own under new identities |
| 1541 | /// (`protected::rekey`), named as the section is or with the first free number after it |
| 1542 | /// ("Beta 2"), with its colour, pages, versions and conflict pages, and the edits the |
| 1543 | /// replica holds that the file does not yet. Refused, `WouldBlock`, while those wait to be |
| 1544 | /// rebased onto a file another client changed, and while the file can't be reached, as the |
| 1545 | /// replica may be behind it. `target` may be this notebook opened again. The copy is listed |
| 1546 | /// once it reads back whole, and taken away again where it cannot be. Returns its catalog |
| 1547 | /// path in `target`. |
| 1548 | pub fn copy_section( |
| 1549 | &self, |
| 1550 | path: &str, |
| 1551 | replica: &Replica, |
| 1552 | target: &mut Notebook, |
| 1553 | folder: &str, |
| 1554 | after: Option<&str>, |
| 1555 | ) -> Result<String> { |
| 1556 | let (image, _) = self.copied(path, replica)?; |
| 1557 | target.place_copy(image, split(path).1, folder, after) |
| 1558 | } |
| 1559 | |
| 1560 | /// Moves the section at catalog `path`, open as `section`, as `copy_section` copies it, |
| 1561 | /// then sends it to this notebook's recycle bin as `delete` does, and deletes its replica, |
| 1562 | /// whose edits the copy holds. `section` stops first, so nothing publishes to or rebases it |
| 1563 | /// meanwhile. The section stays where the copy could not be made, and also, as |
| 1564 | /// `Moved::kept` then says, where it changed after it was copied or could not reach the bin. |
| 1565 | pub fn move_section( |
| 1566 | &mut self, |
| 1567 | path: &str, |
| 1568 | section: Section, |
| 1569 | target: &mut Notebook, |
| 1570 | folder: &str, |
| 1571 | after: Option<&str>, |
| 1572 | ) -> Result<Moved> { |
| 1573 | let replica = Arc::clone(section.replica()); |
| 1574 | section.close()?; |
| 1575 | let (from, name) = split(path); |
| 1576 | let (entry, file) = (self.entry(from, name)?, self.replica_path(path)); |
| 1577 | let (image, stamp) = self.copied(path, &replica)?; |
| 1578 | let newest = replica.pending()?.last().map(|edit| edit.id); |
| 1579 | let copy = target.place_copy(image, name, folder, after)?; |
| 1580 | let left = (|| { |
| 1581 | if replica.pending()?.last().map(|edit| edit.id) != newest { |
| 1582 | return Err(changed()); |
| 1583 | } |
| 1584 | self.send_to_bin(path, &entry.filename, Some(&stamp)) |
| 1585 | })(); |
| 1586 | let binned = match left { |
| 1587 | Ok(binned) => binned, |
| 1588 | Err(error) => { |
| 1589 | return Ok(Moved { |
| 1590 | path: copy, |
| 1591 | kept: Some(error), |
| 1592 | }); |
| 1593 | } |
| 1594 | }; |
| 1595 | // The section has left. What lists it is tidied as far as it can be: OneNote 2010 |
| 1596 | // leaves a moved section's TOC entry, and a catalog read failing now is the next one's. |
| 1597 | let _ = self |
| 1598 | .list_binned(binned, &entry) |
| 1599 | .and_then(|()| match entry.identity { |
| 1600 | Some(identity) => self.edit_toc(from, &[onestore::TocEdit::Remove { identity }]), |
| 1601 | None => Ok(()), |
| 1602 | }); |
| 1603 | let _ = self.refresh(); |
| 1604 | drop(replica); |
| 1605 | // Unless something else opened it meanwhile, or it keeps images of uploads the old |
| 1606 | // file may have lost, which name that file and stay with its replica. |
| 1607 | if let Ok(file) = file |
| 1608 | && crate::closed(&file).is_ok() |
| 1609 | && !crate::published::keeps(&file) |
| 1610 | { |
| 1611 | let _ = crate::remove_replica(&file); |
| 1612 | } |
| 1613 | Ok(Moved { |
| 1614 | path: copy, |
| 1615 | kept: None, |
| 1616 | }) |
| 1617 | } |
| 1618 | |
| 1619 | /// The section at catalog `path`, whose replica is `replica`, as a copy of it carries it, |
| 1620 | /// under new identities, and the stamp of the file it was taken from. |
| 1621 | fn copied(&self, path: &str, replica: &Replica) -> Result<(Vec<u8>, Stamp)> { |
| 1622 | replica.written()?; |
| 1623 | let stamp = self.storage.stamp(path)?; |
| 1624 | let (image, stamp) = if replica.pending()?.is_empty() { |
| 1625 | let image = self.storage.read(path)?; |
| 1626 | let stamp = Stamp::of(&image)?; |
| 1627 | (image, stamp) |
| 1628 | } else if stamp == crate::base::base_stamp(&*replica.lock()?)? { |
| 1629 | (replica.snapshot()?, stamp) |
| 1630 | } else { |
| 1631 | return Err(io::Error::new( |
| 1632 | io::ErrorKind::WouldBlock, |
| 1633 | "Edits to the section are still syncing", |
| 1634 | ) |
| 1635 | .into()); |
| 1636 | }; |
| 1637 | let key = replica.section.key.as_ref(); |
| 1638 | Ok((protected::rekey(&image, key, key)?, stamp)) |
| 1639 | } |
| 1640 | |
| 1641 | /// Lists the section file `image` holds in `folder`, after its section `after` or last, |
| 1642 | /// under `filename` or the first free number after its name; its catalog path. It is |
| 1643 | /// written under a name discovery passes over, and takes its own once it reads back whole, |
| 1644 | /// so that a copy cut short is never taken for a section. |
| 1645 | fn place_copy( |
| 1646 | &mut self, |
| 1647 | mut image: Vec<u8>, |
| 1648 | filename: &str, |
| 1649 | folder: &str, |
| 1650 | after: Option<&str>, |
| 1651 | ) -> Result<String> { |
| 1652 | let parent = self.folder(folder)?; |
| 1653 | let order: Vec<[u8; 16]> = match after { |
| 1654 | Some(after) => { |
| 1655 | let at = (parent.sections.iter()) |
| 1656 | .position(|section| section.path == after) |
| 1657 | .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; |
| 1658 | (parent.sections[..=at].iter()) |
| 1659 | .filter_map(|section| Entry::of(parent, section).identity) |
| 1660 | .collect() |
| 1661 | } |
| 1662 | None => Vec::new(), |
| 1663 | }; |
| 1664 | let stem = match filename.len().checked_sub(4) { |
| 1665 | Some(at) |
| 1666 | if filename |
| 1667 | .get(at..) |
| 1668 | .is_some_and(|end| end.eq_ignore_ascii_case(".one")) => |
| 1669 | { |
| 1670 | &filename[..at] |
| 1671 | } |
| 1672 | _ => filename, |
| 1673 | }; |
| 1674 | let name = |n| match n { |
| 1675 | 1 => format!("{stem}.one"), |
| 1676 | n => format!("{stem} {n}.one"), |
| 1677 | }; |
| 1678 | let (_, ancestor) = self.toc(folder)?; |
| 1679 | onestore::place_image(&mut image, Some((ancestor, &name(1))))?; |
| 1680 | let identity = onestore::Store::parse(&image)?.header.file_id; |
| 1681 | // A name of its own, should another client copy a section so named here meanwhile. |
| 1682 | let mut unique = [0; 8]; |
| 1683 | getrandom::fill(&mut unique) |
| 1684 | .map_err(|_| io::Error::other("System random source failed"))?; |
| 1685 | let unique: String = unique.iter().map(|byte| format!("{byte:02x}")).collect(); |
| 1686 | let written = catalog_path(folder, &format!(".{stem}.one.{unique}.snowbound")); |
| 1687 | self.storage.create(&written, &image)?; |
| 1688 | let named = (|| { |
| 1689 | if self.storage.read(&written)? != image { |
| 1690 | return Err(io::Error::new( |
| 1691 | io::ErrorKind::InvalidData, |
| 1692 | "The copy didn't read back as it was written", |
| 1693 | ) |
| 1694 | .into()); |
| 1695 | } |
| 1696 | for n in 1.. { |
| 1697 | if n > 1 { |
| 1698 | self.storage.place(&written, ancestor, &name(n))?; |
| 1699 | } |
| 1700 | match self |
| 1701 | .storage |
| 1702 | .rename(&written, &catalog_path(folder, &name(n))) |
| 1703 | { |
| 1704 | Err(Error::Io(error)) if error.kind() == io::ErrorKind::AlreadyExists => {} |
| 1705 | renamed => return renamed.map(|()| name(n)), |
| 1706 | } |
| 1707 | } |
| 1708 | unreachable!("a free name") |
| 1709 | })(); |
| 1710 | let filename = match named { |
| 1711 | Ok(filename) => filename, |
| 1712 | Err(error) => { |
| 1713 | let _ = self.storage.delete(&written); |
| 1714 | return Err(error); |
| 1715 | } |
| 1716 | }; |
| 1717 | let path = catalog_path(folder, &filename); |
| 1718 | let mut edits = vec![onestore::TocEdit::Add { |
| 1719 | filename, |
| 1720 | identity, |
| 1721 | group: false, |
| 1722 | }]; |
| 1723 | if !order.is_empty() { |
| 1724 | edits.push(onestore::TocEdit::Order([order, vec![identity]].concat())); |
| 1725 | } |
| 1726 | if let Err(error) = self.edit_toc(folder, &edits) { |
| 1727 | let _ = self.storage.delete(&path); |
| 1728 | return Err(error); |
| 1729 | } |
| 1730 | // The copy stands listed; a catalog read failing now is the next one's to repair. |
| 1731 | let _ = self.refresh(); |
| 1732 | Ok(path) |
| 1733 | } |
| 1734 | |
| 1735 | /// The stored filename and TOC identity of a folder's section or group. |
| 1736 | fn entry(&self, folder: &str, name: &str) -> Result<Entry> { |
| 1737 | let parent = self.folder(folder)?; |
| 1738 | if let Some(section) = parent |
| 1739 | .sections |
| 1740 | .iter() |
| 1741 | .find(|section| split(&section.path).1 == name) |
| 1742 | { |
| 1743 | return Ok(Entry::of(parent, section)); |
| 1744 | } |
| 1745 | if let Some(group) = parent |
| 1746 | .groups |
| 1747 | .iter() |
| 1748 | .find(|group| split(&group.path).1 == name) |
| 1749 | { |
| 1750 | let toc = group |
| 1751 | .toc |
| 1752 | .as_ref() |
| 1753 | .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; |
| 1754 | return Ok(Entry { |
| 1755 | filename: name.to_owned(), |
| 1756 | identity: Some(toc.file_id), |
| 1757 | copy: false, |
| 1758 | }); |
| 1759 | } |
| 1760 | Err(io::Error::from(io::ErrorKind::NotFound).into()) |
| 1761 | } |
| 1762 | |
| 1763 | /// The section path and page space a stored internal link opens, found by identity: |
| 1764 | /// in the linked section first, then in every other readable section, so a link |
| 1765 | /// follows its page across sections. `None` for other URLs and unknown targets. |
| 1766 | pub fn find_page(&self, url: &str) -> Result<Option<(String, Option<ExGuid>)>> { |
| 1767 | let Some(link) = onestore::page::link::parse_internal_link(url) else { |
| 1768 | return Ok(None); |
| 1769 | }; |
| 1770 | let mut sections: Vec<_> = self |
| 1771 | .catalog |
| 1772 | .sections() |
| 1773 | .filter(|section| matches!(section.state, discover::SectionState::Readable { .. })) |
| 1774 | .collect(); |
| 1775 | sections.sort_by_key(|section| section.file_id != link.section); |
| 1776 | let Some(page) = link.page else { |
| 1777 | return Ok(sections |
| 1778 | .first() |
| 1779 | .filter(|section| section.file_id == link.section) |
| 1780 | .map(|section| (section.path.clone(), None))); |
| 1781 | }; |
| 1782 | for section in sections { |
| 1783 | let bytes = self.storage.read(&section.path)?; |
| 1784 | let store = Store::parse(&bytes)?; |
| 1785 | let index = RevisionIndex::parse(&store)?; |
| 1786 | let document = Document::parse(&index)?; |
| 1787 | for (space, _) in document.pages()? { |
| 1788 | if Page::identity_of(document.active(space)?) == Some(page) { |
| 1789 | return Ok(Some((section.path.clone(), Some(space)))); |
| 1790 | } |
| 1791 | } |
| 1792 | } |
| 1793 | Ok(None) |
| 1794 | } |
| 1795 | |
| 1796 | /// The section at catalog `path` as its file stores it, without the edits a replica |
| 1797 | /// may hold (`stored_pages` reads it). |
| 1798 | pub fn read_section(&self, path: &str) -> Result<Vec<u8>> { |
| 1799 | self.storage.read(&self.section_path(path)?.path) |
| 1800 | } |
| 1801 | |
| 1802 | /// The key of the password-protected section at catalog `path`, opened with `password`. |
| 1803 | /// Edits this device queued before the section was protected elsewhere, held since, are |
| 1804 | /// queued again under the key: each page they changed comes back as a copy, as a page |
| 1805 | /// another client removed does, the section's pages having taken new identities. |
| 1806 | pub fn unlock(&self, path: &str, password: &str) -> Result<protected::Key> { |
| 1807 | crate::task::blocking(self.unlock_async(path, password))? |
| 1808 | } |
| 1809 | |
| 1810 | pub async fn unlock_async(&self, path: &str, password: &str) -> Result<protected::Key> { |
| 1811 | let section = self.section_path(path)?; |
| 1812 | let image = self.storage.read(&section.path)?; |
| 1813 | let key = protected::Key::open(&image, password)?; |
| 1814 | let held: Vec<PathBuf> = self |
| 1815 | .superseded(&[section]) |
| 1816 | .into_iter() |
| 1817 | .filter(|(.., queued)| *queued > 0) |
| 1818 | .map(|(replica, ..)| replica) |
| 1819 | .collect(); |
| 1820 | if !held.is_empty() { |
| 1821 | let replica = |
| 1822 | Replica::open_or_create(self.replica_path(path)?, Some(&key), || Ok(image))?; |
| 1823 | for path in held { |
| 1824 | // A queue sealed under an earlier password waits for that password. |
| 1825 | let Ok(old) = Replica::open(&path) else { |
| 1826 | continue; |
| 1827 | }; |
| 1828 | for (author, edit) in old.copies()? { |
| 1829 | replica.apply_async(&author, edit).await?; |
| 1830 | } |
| 1831 | drop(old); |
| 1832 | crate::remove_replica(&path)?; |
| 1833 | } |
| 1834 | } |
| 1835 | Ok(key) |
| 1836 | } |
| 1837 | |
| 1838 | /// The replicas of the files the protected `locked` sections superseded when their |
| 1839 | /// passwords were set (`onestore::protected::rekey` keeps the placement a file's header |
| 1840 | /// names), each held so that no one opens it meanwhile, with how many edits it queues. Only |
| 1841 | /// replicas no readable section names are read; one in use is left. |
| 1842 | fn superseded( |
| 1843 | &self, |
| 1844 | locked: &[&discover::Section], |
| 1845 | ) -> Vec<(PathBuf, rusqlite::Connection, u64)> { |
| 1846 | let named: BTreeSet<PathBuf> = self |
| 1847 | .catalog |
| 1848 | .sections() |
| 1849 | .filter(|section| matches!(section.state, discover::SectionState::Readable { .. })) |
| 1850 | .filter_map(|section| self.replica_path(&section.path).ok()) |
| 1851 | .collect(); |
| 1852 | let placed: Vec<_> = locked |
| 1853 | .iter() |
| 1854 | .filter_map(|section| { |
| 1855 | let (_, stamp) = self.read.found(&section.path)?; |
| 1856 | Some((section.file_id, stamp.header, self.replica_folder(section))) |
| 1857 | }) |
| 1858 | .collect(); |
| 1859 | let folders: BTreeSet<&PathBuf> = placed.iter().map(|(.., folder)| folder).collect(); |
| 1860 | let mut superseded = Vec::new(); |
| 1861 | for folder in folders { |
| 1862 | let Ok(entries) = fs::read_dir(folder) else { |
| 1863 | continue; |
| 1864 | }; |
| 1865 | for path in entries.filter_map(|entry| Some(entry.ok()?.path())) { |
| 1866 | if path |
| 1867 | .extension() |
| 1868 | .is_none_or(|extension| extension != "sqlite") |
| 1869 | || named.contains(&path) |
| 1870 | { |
| 1871 | continue; |
| 1872 | } |
| 1873 | let Ok(held) = crate::closed(&path) else { |
| 1874 | continue; |
| 1875 | }; |
| 1876 | let Ok((base, queued)) = crate::peek(&held) else { |
| 1877 | continue; |
| 1878 | }; |
| 1879 | let Ok(header) = onestore::Header::parse(&base.header) else { |
| 1880 | continue; |
| 1881 | }; |
| 1882 | if placed.iter().any(|(file, stamp, at)| { |
| 1883 | at == folder |
| 1884 | && base.header[128..148] == stamp[128..148] |
| 1885 | && header.file_id != *file |
| 1886 | }) { |
| 1887 | superseded.push((path, held, queued)); |
| 1888 | } |
| 1889 | } |
| 1890 | } |
| 1891 | superseded |
| 1892 | } |
| 1893 | |
| 1894 | /// Deletes the replicas holding nothing unpublished of files a protected section |
| 1895 | /// superseded: their plaintext is the section's before its password. |
| 1896 | fn forget_superseded(&self) { |
| 1897 | let locked: Vec<_> = self |
| 1898 | .catalog |
| 1899 | .sections() |
| 1900 | .filter(|section| matches!(section.state, discover::SectionState::Locked)) |
| 1901 | .collect(); |
| 1902 | if locked.is_empty() { |
| 1903 | return; |
| 1904 | } |
| 1905 | for (replica, held, queued) in self.superseded(&locked) { |
| 1906 | drop(held); |
| 1907 | if queued == 0 { |
| 1908 | let _ = crate::remove_replica(&replica); |
| 1909 | } |
| 1910 | } |
| 1911 | } |
| 1912 | |
| 1913 | /// Sets, changes or removes the password of the section at catalog `path`, as OneNote |
| 1914 | /// 2010 does: the section is written anew under new identities (`onestore::protected:: |
| 1915 | /// rekey`), the file replaces the old one and its folder's TOC follows it. `key` opens |
| 1916 | /// it as it stands; `password` protects it anew, or `None` leaves it unprotected. Its |
| 1917 | /// replica, a cache of the old file, goes too, so its session must be closed and its |
| 1918 | /// edits published first. Returns the new key. |
| 1919 | pub fn set_password( |
| 1920 | &mut self, |
| 1921 | path: &str, |
| 1922 | key: Option<&protected::Key>, |
| 1923 | password: Option<&str>, |
| 1924 | ) -> Result<Option<protected::Key>> { |
| 1925 | let section = self.section_path(path)?; |
| 1926 | let replica = self.replica_path(path)?; |
| 1927 | // Held until the file is replaced, so that no session queues edits to the old file. |
| 1928 | let held = fs::metadata(&replica) |
| 1929 | .is_ok() |
| 1930 | .then(|| crate::closed(&replica)) |
| 1931 | .transpose()?; |
| 1932 | if let Some(held) = &held |
| 1933 | && crate::peek(held)?.1 > 0 |
| 1934 | { |
| 1935 | return Err(io::Error::new( |
| 1936 | io::ErrorKind::WouldBlock, |
| 1937 | "Edits to the section wait to be published", |
| 1938 | ) |
| 1939 | .into()); |
| 1940 | } |
| 1941 | let source = self.storage.read(&section.path)?; |
| 1942 | let new = password.map(protected::Key::new).transpose()?; |
| 1943 | let image = onestore::protected::rekey(&source, key, new.as_ref())?; |
| 1944 | let (folder, filename) = split(&section.path); |
| 1945 | // A dot file, which discovery and OneNote pass over, until it replaces the section. |
| 1946 | let written = catalog_path(folder, &format!(".{filename}.snowbound")); |
| 1947 | if self.storage.exists(&written) { |
| 1948 | self.storage.delete(&written)?; |
| 1949 | } |
| 1950 | self.storage.create(&written, &image)?; |
| 1951 | if let Err(error) = self |
| 1952 | .storage |
| 1953 | .supersede(&section.path, &Stamp::of(&source)?, &written) |
| 1954 | { |
| 1955 | let _ = self.storage.delete(&written); |
| 1956 | return Err(error); |
| 1957 | } |
| 1958 | drop(held); |
| 1959 | crate::remove_replica(&replica)?; |
| 1960 | let parent = self.folder(folder)?; |
| 1961 | if let Some(identity) = Entry::of(parent, section).identity { |
| 1962 | self.edit_toc( |
| 1963 | folder, |
| 1964 | &[onestore::TocEdit::Reidentify { |
| 1965 | identity, |
| 1966 | with: Store::parse(&image)?.header.file_id, |
| 1967 | }], |
| 1968 | )?; |
| 1969 | } |
| 1970 | self.refresh()?; |
| 1971 | Ok(new) |
| 1972 | } |
| 1973 | |
| 1974 | /// Where the replica of the section at catalog `path` lives, in the notebook's |
| 1975 | /// `location::folder`: named by the section's document identity in a mounted notebook |
| 1976 | /// (`Section::open`), by its file identity on a share. It exists once the section has |
| 1977 | /// been opened. |
| 1978 | pub fn replica_path(&self, path: &str) -> Result<PathBuf> { |
| 1979 | let section = self.section_path(path)?; |
| 1980 | let folder = self.replica_folder(section); |
| 1981 | Ok(match (&self.root, &section.state) { |
| 1982 | (Some(_), discover::SectionState::Readable { document, .. }) => { |
| 1983 | replica_file(&folder, document) |
| 1984 | } |
| 1985 | (Some(_), _) => { |
| 1986 | let image = self.storage.read(&section.path)?; |
| 1987 | let root = RevisionIndex::parse(&Store::parse(&image)?)?.root; |
| 1988 | replica_file(&folder, &root.guid) |
| 1989 | } |
| 1990 | (None, _) => replica_file(&folder, &section.file_id), |
| 1991 | }) |
| 1992 | } |
| 1993 | |
| 1994 | /// The `location::folder` holding the replica of `section`. |
| 1995 | /// A copy's is labelled with its location as it is first named, as one found after the |
| 1996 | /// notebook opened is, so that it moves and goes with the notebook (`location::moved`). |
| 1997 | fn replica_folder(&self, section: &discover::Section) -> PathBuf { |
| 1998 | let location = replica_location(&self.storage.location(), &section.path, section.copy); |
| 1999 | match section.copy { |
| 2000 | true => crate::location::claimed(&self.cache, &location) |
| 2001 | .unwrap_or_else(|_| crate::location::folder(&self.cache, &location)), |
| 2002 | false => crate::location::folder(&self.cache, &location), |
| 2003 | } |
| 2004 | } |
| 2005 | |
| 2006 | /// Every readable section, for `Background::watch`, handing on the files the last |
| 2007 | /// discovery read so that each is read once. |
| 2008 | pub fn replicas(&mut self) -> Vec<Known> { |
| 2009 | let mut images = self.read.take(); |
| 2010 | self.catalog |
| 2011 | .sections() |
| 2012 | .filter(|section| matches!(section.state, discover::SectionState::Readable { .. })) |
| 2013 | .map(|section| Known { |
| 2014 | path: section.path.clone(), |
| 2015 | replica: self.replica_path(&section.path).ok(), |
| 2016 | found: self.read.found(&section.path), |
| 2017 | image: images.remove(&section.path), |
| 2018 | }) |
| 2019 | .collect() |
| 2020 | } |
| 2021 | |
| 2022 | /// Keeps the sections of a mounted notebook in sync while they are not open |
| 2023 | /// (`Background`): a file is checked when `Background::touched` reports it changed, and |
| 2024 | /// otherwise every `Background::BACKSTOP` when `watched`, as a host that watches the |
| 2025 | /// folder reports every change, or else every `Background::UNWATCHED`. `copies` keeps an |
| 2026 | /// offline copy of every section, for a folder that is not on this computer. |
| 2027 | pub fn background( |
| 2028 | &self, |
| 2029 | watched: bool, |
| 2030 | copies: bool, |
| 2031 | notify: impl Fn() + Send + 'static, |
| 2032 | ) -> Result<Background> { |
| 2033 | self.background_with( |
| 2034 | watched, |
| 2035 | copies, |
| 2036 | |file, _| FileRemote(file.to_owned()), |
| 2037 | notify, |
| 2038 | ) |
| 2039 | } |
| 2040 | |
| 2041 | /// `background`, reaching each section file through the remote `remote` makes for it and |
| 2042 | /// its replica, where it has one (`section_with`). |
| 2043 | pub fn background_with<R: Remote + 'static>( |
| 2044 | &self, |
| 2045 | watched: bool, |
| 2046 | copies: bool, |
| 2047 | remote: impl Fn(&Path, Option<&Path>) -> R + Clone + Send + 'static, |
| 2048 | notify: impl Fn() + Send + 'static, |
| 2049 | ) -> Result<Background> { |
| 2050 | let Some(root) = self.root.clone() else { |
| 2051 | return Err(io::Error::new( |
| 2052 | io::ErrorKind::Unsupported, |
| 2053 | "Sections on a share sync through Background::smb", |
| 2054 | ) |
| 2055 | .into()); |
| 2056 | }; |
| 2057 | Background::start( |
| 2058 | copies, |
| 2059 | move |_| { |
| 2060 | let (folder, remote) = (root.clone(), remote.clone()); |
| 2061 | let bind = |
| 2062 | move |path: &str, replica: Option<&Path>| remote(&folder.join(path), replica); |
| 2063 | let mut local = discover::Local::open(&root)?; |
| 2064 | let list = move |folder: String| { |
| 2065 | use discover::Source; |
| 2066 | std::future::ready(local.entries(&folder, LIMITS.entries)) |
| 2067 | }; |
| 2068 | Ok(((bind, list), watched)) |
| 2069 | }, |
| 2070 | notify, |
| 2071 | ) |
| 2072 | } |
| 2073 | |
| 2074 | /// Opens a section of a mounted notebook by its catalog path. |
| 2075 | pub fn section( |
| 2076 | &self, |
| 2077 | path: &str, |
| 2078 | offline: bool, |
| 2079 | notify: impl Fn() + Send + 'static, |
| 2080 | ) -> Result<Section> { |
| 2081 | self.section_with( |
| 2082 | path, |
| 2083 | |file, _| Ok(FileRemote(file.to_owned())), |
| 2084 | offline, |
| 2085 | notify, |
| 2086 | ) |
| 2087 | } |
| 2088 | |
| 2089 | /// `section`, reading and publishing through the remote `connect` makes for its file and |
| 2090 | /// its replica, which it reads through before there is one (`Section::open_with`). |
| 2091 | pub fn section_with<R: Remote + 'static>( |
| 2092 | &self, |
| 2093 | path: &str, |
| 2094 | connect: impl FnMut(&Path, Option<&Path>) -> io::Result<R> + Send + 'static, |
| 2095 | offline: bool, |
| 2096 | notify: impl Fn() + Send + 'static, |
| 2097 | ) -> Result<Section> { |
| 2098 | self.open_section(path, None, connect, offline, notify) |
| 2099 | } |
| 2100 | |
| 2101 | /// `section` for a password-protected section, under the `key` `unlock` gave. |
| 2102 | pub fn section_unlocked( |
| 2103 | &self, |
| 2104 | path: &str, |
| 2105 | key: &protected::Key, |
| 2106 | offline: bool, |
| 2107 | notify: impl Fn() + Send + 'static, |
| 2108 | ) -> Result<Section> { |
| 2109 | self.section_unlocked_with( |
| 2110 | path, |
| 2111 | key, |
| 2112 | |file, _| Ok(FileRemote(file.to_owned())), |
| 2113 | offline, |
| 2114 | notify, |
| 2115 | ) |
| 2116 | } |
| 2117 | |
| 2118 | /// `section_with` for a password-protected section, under its `key`. |
| 2119 | pub fn section_unlocked_with<R: Remote + 'static>( |
| 2120 | &self, |
| 2121 | path: &str, |
| 2122 | key: &protected::Key, |
| 2123 | connect: impl FnMut(&Path, Option<&Path>) -> io::Result<R> + Send + 'static, |
| 2124 | offline: bool, |
| 2125 | notify: impl Fn() + Send + 'static, |
| 2126 | ) -> Result<Section> { |
| 2127 | self.open_section(path, Some(key), connect, offline, notify) |
| 2128 | } |
| 2129 | |
| 2130 | fn open_section<R: Remote + 'static>( |
| 2131 | &self, |
| 2132 | path: &str, |
| 2133 | key: Option<&protected::Key>, |
| 2134 | connect: impl FnMut(&Path, Option<&Path>) -> io::Result<R> + Send + 'static, |
| 2135 | offline: bool, |
| 2136 | notify: impl Fn() + Send + 'static, |
| 2137 | ) -> Result<Section> { |
| 2138 | let section = self.section_path(path)?; |
| 2139 | let (path, replicas) = (section.path.clone(), self.replica_folder(section)); |
| 2140 | let Some(root) = &self.root else { |
| 2141 | return Err(io::Error::new( |
| 2142 | io::ErrorKind::Unsupported, |
| 2143 | "Sections on a share open through Section::resume_smb", |
| 2144 | ) |
| 2145 | .into()); |
| 2146 | }; |
| 2147 | let file = root.join(path); |
| 2148 | // Evicted files resume their replicas; existing links still resolve within the root. |
| 2149 | let file = match fs::symlink_metadata(&file) { |
| 2150 | Err(error) if error.kind() == io::ErrorKind::NotFound => fs::canonicalize( |
| 2151 | file.parent() |
| 2152 | .ok_or(io::Error::from(io::ErrorKind::InvalidInput))?, |
| 2153 | )? |
| 2154 | .join( |
| 2155 | file.file_name() |
| 2156 | .ok_or(io::Error::from(io::ErrorKind::InvalidInput))?, |
| 2157 | ), |
| 2158 | _ => fs::canonicalize(&file)?, |
| 2159 | }; |
| 2160 | if !file.starts_with(root) { |
| 2161 | return Err(io::Error::from(io::ErrorKind::PermissionDenied).into()); |
| 2162 | } |
| 2163 | // A replica the catalog's identity names resumes without reading the file, which its |
| 2164 | // worker checks next, as a share's does. |
| 2165 | if let discover::SectionState::Readable { document, .. } = &section.state { |
| 2166 | let cache = replica_file(&replicas, document); |
| 2167 | if fs::metadata(&cache).is_ok() { |
| 2168 | let (replica, remote, mut connect) = |
| 2169 | (Replica::open(&cache)?, file.clone(), connect); |
| 2170 | return Section::start( |
| 2171 | file, |
| 2172 | replica, |
| 2173 | move || connect(&remote, Some(&cache)), |
| 2174 | CHECK, |
| 2175 | offline, |
| 2176 | notify, |
| 2177 | ); |
| 2178 | } |
| 2179 | } |
| 2180 | let replica = |identity: &[u8; 16], _: &[u8]| { |
| 2181 | fs::create_dir_all(&replicas)?; |
| 2182 | Ok(replica_file(&replicas, identity)) |
| 2183 | }; |
| 2184 | Section::open_in(file, key, replica, connect, CHECK, offline, notify) |
| 2185 | } |
| 2186 | } |
| 2187 | |
| 2188 | /// A section `Notebook::move_section` moved: its catalog path in the notebook it went to, |
| 2189 | /// and why it also stayed where it was, where it could not leave once copied. |
| 2190 | #[derive(Debug)] |
| 2191 | pub struct Moved { |
| 2192 | pub path: String, |
| 2193 | pub kept: Option<Error>, |
| 2194 | } |
| 2195 | |
| 2196 | /// A section or group as its folder holds it, for the structure operations. |
| 2197 | struct Entry { |
| 2198 | filename: String, |
| 2199 | /// What its folder's TOC lists it under, if anything. |
| 2200 | identity: Option<[u8; 16]>, |
| 2201 | /// A copy of another section of the notebook (`discover::Section::copy`). Its header names |
| 2202 | /// the other's file, so it is never placed or listed anew: OneNote lists a copy it finds |
| 2203 | /// under an identity of its own, leaving the file as it is. |
| 2204 | copy: bool, |
| 2205 | } |
| 2206 | |
| 2207 | impl Entry { |
| 2208 | /// `section` of the folder `parent`: a copy has only the entry its folder's TOC lists |
| 2209 | /// under its name. |
| 2210 | fn of(parent: &discover::Folder, section: &discover::Section) -> Self { |
| 2211 | let filename = split(&section.path).1.to_owned(); |
| 2212 | let identity = if section.copy { |
| 2213 | parent |
| 2214 | .toc |
| 2215 | .iter() |
| 2216 | .flat_map(|toc| &toc.unresolved) |
| 2217 | .find(|entry| { |
| 2218 | entry |
| 2219 | .filename |
| 2220 | .as_deref() |
| 2221 | .is_some_and(|name| name.eq_ignore_ascii_case(&filename)) |
| 2222 | }) |
| 2223 | .map(|entry| entry.file) |
| 2224 | } else { |
| 2225 | Some(section.file_id) |
| 2226 | }; |
| 2227 | Self { |
| 2228 | filename, |
| 2229 | identity, |
| 2230 | copy: section.copy, |
| 2231 | } |
| 2232 | } |
| 2233 | } |
| 2234 | |
| 2235 | /// A page as a section file stores it. |
| 2236 | pub struct StoredPage { |
| 2237 | pub space: ExGuid, |
| 2238 | pub page: Page, |
| 2239 | /// The revision metadata's timestamp, or the page's `LastModifiedTime`, as FILETIME. |
| 2240 | pub modified: Option<u64>, |
| 2241 | /// Who changed it last: revision metadata, or the latest modified object in older files. |
| 2242 | pub author: Option<String>, |
| 2243 | } |
| 2244 | |
| 2245 | /// The pages of the section file `image` holds, in section order; pages the model cannot |
| 2246 | /// build are left out. |
| 2247 | pub fn stored_pages(image: &[u8]) -> Result<Vec<StoredPage>> { |
| 2248 | let store = Store::parse(image)?; |
| 2249 | let index = RevisionIndex::parse(&store)?; |
| 2250 | pages_of(&Document::parse(&index)?) |
| 2251 | } |
| 2252 | |
| 2253 | /// `stored_pages` of a password-protected section, under its `key`. |
| 2254 | pub fn stored_pages_unlocked(image: &[u8], key: &protected::Key) -> Result<Vec<StoredPage>> { |
| 2255 | let store = Store::parse(image)?; |
| 2256 | let index = RevisionIndex::parse(&store)?; |
| 2257 | let unlocked = protected::UnlockedSection::unlock(&index, key, Default::default())?; |
| 2258 | pages_of(&unlocked.document()?) |
| 2259 | } |
| 2260 | |
| 2261 | fn pages_of(document: &Document<'_>) -> Result<Vec<StoredPage>> { |
| 2262 | Ok(document |
| 2263 | .pages()? |
| 2264 | .into_iter() |
| 2265 | .filter_map(|(space, id)| { |
| 2266 | let revision = document.active(space).ok()?; |
| 2267 | let latest = (revision.nodes.values()) |
| 2268 | .filter(|node| node.latest_author.is_some()) |
| 2269 | .max_by_key(|node| node.modified); |
| 2270 | let metadata = revision.roots.get(&4).and_then(|id| revision.nodes.get(id)); |
| 2271 | let author = metadata |
| 2272 | .filter(|node| { |
| 2273 | matches!(node.kind, onestore::document::Kind::RevisionMetadata { .. }) |
| 2274 | }) |
| 2275 | .filter(|node| node.latest_author.is_some()) |
| 2276 | .or(latest) |
| 2277 | .and_then(|node| revision.nodes.get(&node.latest_author?)) |
| 2278 | .and_then(|node| match &node.kind { |
| 2279 | onestore::document::Kind::Author { name } => name.clone(), |
| 2280 | _ => None, |
| 2281 | }); |
| 2282 | Some(StoredPage { |
| 2283 | space, |
| 2284 | page: Page::from_revision(revision, id).ok()?, |
| 2285 | modified: metadata |
| 2286 | .and_then(|node| match node.kind { |
| 2287 | onestore::document::Kind::RevisionMetadata { modified_filetime } => { |
| 2288 | modified_filetime |
| 2289 | } |
| 2290 | _ => None, |
| 2291 | }) |
| 2292 | .or_else(|| { |
| 2293 | revision |
| 2294 | .nodes |
| 2295 | .get(&id) |
| 2296 | .and_then(|node| node.modified) |
| 2297 | .map(|seconds| (u64::from(seconds) + 11_960_006_400) * 10_000_000) |
| 2298 | }), |
| 2299 | author, |
| 2300 | }) |
| 2301 | }) |
| 2302 | .collect()) |
| 2303 | } |
| 2304 | |
| 2305 | /// The colours OneNote 2010 gives a folder's first sixteen new sections, COLORREF, in the |
| 2306 | /// order it gives them (`corpus/notebook-management/native/section-colors`: sixteen sections |
| 2307 | /// made with New Section in a new notebook). |
| 2308 | const SECTION_COLORS: [u32; 16] = [ |
| 2309 | 0x00e4a88a, 0x0078b0f6, 0x00bba4d5, 0x00d2bb9b, 0x00b79cab, 0x0099d1e8, 0x006ff9f5, 0x0092e7ad, |
| 2310 | 0x00cabc4d, 0x007575ba, 0x00aa9595, 0x00e4a88a, 0x0069d8ff, 0x0097c9b7, 0x009795ee, 0x00de9eb4, |
| 2311 | ]; |
| 2312 | |
| 2313 | /// The colour OneNote gives a new section in `folder`, by how many sections it holds. |
| 2314 | fn next_color(folder: &discover::Folder) -> u32 { |
| 2315 | SECTION_COLORS[folder.sections.len() % SECTION_COLORS.len()] |
| 2316 | } |
| 2317 | |
| 2318 | /// The op putting `page` into another section as OneNote moves a page there, into the |
| 2319 | /// recycle bin or another section: last, under fresh object identities, keeping its page |
| 2320 | /// identity, title, date and creation time. |
| 2321 | pub fn moved(page: &Page, author: &str) -> Result<Op> { |
| 2322 | let mut creation = PageCreation::new(None, Some(&page.title), author)?; |
| 2323 | if let (Some(identity), Some(created)) = (page.identity, page.created) { |
| 2324 | creation = creation.keeping(identity, created)?; |
| 2325 | } |
| 2326 | if let Some([date, time]) = page.date_text() { |
| 2327 | creation = creation.dated(&date, &time)?; |
| 2328 | } |
| 2329 | Ok(Op::Section(SectionOp::Import { |
| 2330 | creation, |
| 2331 | page: page.copy()?, |
| 2332 | })) |
| 2333 | } |
| 2334 | |
| 2335 | /// The op putting a copy of `page` last in another section, as OneNote copies a page: under |
| 2336 | /// fresh identities, its page identity too, and titled as it is. |
| 2337 | pub fn copied(page: &Page, author: &str) -> Result<Op> { |
| 2338 | Ok(Op::Section(SectionOp::Import { |
| 2339 | creation: PageCreation::new(None, Some(&page.title), author)?, |
| 2340 | page: page.copy()?, |
| 2341 | })) |
| 2342 | } |
| 2343 | |
| 2344 | /// The edits putting the pages `moved` where `order` lists them, with their levels, in a |
| 2345 | /// section now listing `listed`: each goes before the next page of `order` that stays put |
| 2346 | /// and is still listed. Pages gone from the section are left out. |
| 2347 | pub fn arrange( |
| 2348 | listed: &[(ExGuid, String, u32)], |
| 2349 | order: &[(ExGuid, u32)], |
| 2350 | moved: &[ExGuid], |
| 2351 | ) -> Result<Vec<PageEdit>> { |
| 2352 | let present = |space: &ExGuid| listed.iter().any(|(listed, ..)| listed == space); |
| 2353 | let mut edits = Vec::new(); |
| 2354 | for (index, (space, level)) in order.iter().enumerate() { |
| 2355 | if !moved.contains(space) || !present(space) { |
| 2356 | continue; |
| 2357 | } |
| 2358 | let before = order[index + 1..] |
| 2359 | .iter() |
| 2360 | .map(|(space, _)| *space) |
| 2361 | .find(|space| !moved.contains(space) && present(space)); |
| 2362 | edits.push(PageEdit::move_to(*space, before, *level)?); |
| 2363 | } |
| 2364 | Ok(edits) |
| 2365 | } |
| 2366 | |
| 2367 | /// Whether `page` holds nothing but an empty title, as the page a section left without |
| 2368 | /// pages gains does. |
| 2369 | pub fn blank(page: &Page) -> bool { |
| 2370 | page.title.trim().is_empty() |
| 2371 | && page |
| 2372 | .objects |
| 2373 | .iter() |
| 2374 | .all(|object| matches!(object, onestore::page::PageObject::Title(_))) |
| 2375 | } |
| 2376 | |
| 2377 | fn component(name: &str) -> bool { |
| 2378 | !name.is_empty() && !name.contains(['/', '\\', '\0']) && name != "." && name != ".." |
| 2379 | } |
| 2380 | |
| 2381 | /// Whether the TOC `image` holds has an entry for the file identity `file`. |
| 2382 | pub(crate) fn lists(image: &[u8], file: [u8; 16]) -> Result<bool> { |
| 2383 | let store = Store::parse(image)?; |
| 2384 | let index = RevisionIndex::parse(&store)?; |
| 2385 | let document = Document::parse(&index)?; |
| 2386 | let revision = document.active(document.root)?; |
| 2387 | let entries = revision |
| 2388 | .roots |
| 2389 | .get(&1) |
| 2390 | .and_then(|id| revision.nodes.get(id)) |
| 2391 | .map_or(&[][..], |node| match &node.kind { |
| 2392 | onestore::document::Kind::Toc { entries, .. } => &entries[..], |
| 2393 | _ => &[], |
| 2394 | }); |
| 2395 | Ok(entries.iter().any(|id| { |
| 2396 | matches!( |
| 2397 | revision.nodes.get(id).map(|node| &node.kind), |
| 2398 | Some(onestore::document::Kind::Toc { identity: Some(identity), .. }) if *identity == file |
| 2399 | ) |
| 2400 | })) |
| 2401 | } |
| 2402 | |
| 2403 | /// Where the cache keeps what reading the catalog of the notebook at `location` took. |
| 2404 | pub(crate) fn listing(cache: &Path, location: &str) -> PathBuf { |
| 2405 | let name: String = <sha2::Sha256 as sha2::Digest>::digest(location)[..16] |
| 2406 | .iter() |
| 2407 | .map(|byte| format!("{byte:02x}")) |
| 2408 | .collect(); |
| 2409 | cache.join("listings").join(format!("{name}.json")) |
| 2410 | } |
| 2411 | |
| 2412 | /// Whether `name` can name a folder on every system a notebook's readers use, Windows's |
| 2413 | /// included. |
| 2414 | fn folder_name(name: &str) -> bool { |
| 2415 | component(name) |
| 2416 | && !name.contains(['<', '>', ':', '"', '|', '?', '*']) |
| 2417 | && !name.chars().any(char::is_control) |
| 2418 | && !name.ends_with(['.', ' ']) |
| 2419 | } |
| 2420 | |
| 2421 | fn split(path: &str) -> (&str, &str) { |
| 2422 | match path.rsplit_once('/') { |
| 2423 | Some((folder, name)) => (folder, name), |
| 2424 | None => ("", path), |
| 2425 | } |
| 2426 | } |
| 2427 | |
| 2428 | fn catalog_path(folder: &str, name: &str) -> String { |
| 2429 | if folder.is_empty() { |
| 2430 | name.to_owned() |
| 2431 | } else { |
| 2432 | format!("{folder}/{name}") |
| 2433 | } |
| 2434 | } |
| 2435 | |
| 2436 | /// The location keying the replica of `section` in the notebook at `notebook`: the notebook's, |
| 2437 | /// so that a section renamed or moved within it keeps its replica, or for a copy of another |
| 2438 | /// section of the notebook its own file's. |
| 2439 | pub fn replica_location(notebook: &str, path: &str, copy: bool) -> String { |
| 2440 | if copy { |
| 2441 | format!("{notebook}/{path}") |
| 2442 | } else { |
| 2443 | notebook.to_owned() |
| 2444 | } |
| 2445 | } |
| 2446 | |
| 2447 | /// How often an open section's file is checked where nothing watches it. |
| 2448 | const CHECK: Duration = Duration::from_secs(2); |
| 2449 | |
| 2450 | /// Names a lone section's replica in the folder of `location` by its identity, taking one a |
| 2451 | /// moved file left behind (`location::claim`). |
| 2452 | fn claimed<'a>( |
| 2453 | cache: &'a Path, |
| 2454 | location: &'a str, |
| 2455 | ) -> impl FnOnce(&[u8; 16], &[u8]) -> Result<PathBuf> + 'a { |
| 2456 | move |identity, source| { |
| 2457 | let folder = |
| 2458 | crate::location::claim(cache, location, &[*identity], |_| Stamp::of(source).ok())?; |
| 2459 | Ok(replica_file(&folder, identity)) |
| 2460 | } |
| 2461 | } |
| 2462 | |
| 2463 | /// The replica in `cache` of the section `identity` names. |
| 2464 | pub(crate) fn replica_file(cache: &Path, identity: &[u8; 16]) -> PathBuf { |
| 2465 | let name: String = identity.iter().map(|byte| format!("{byte:02x}")).collect(); |
| 2466 | cache.join(format!("{name}.sqlite")) |
| 2467 | } |
| 2468 | |
| 2469 | /// Why a synchronization step did not reach the section file, as the host shows it. |
| 2470 | pub(crate) fn reached(error: &Error) -> io::Error { |
| 2471 | match error { |
| 2472 | Error::RemoteIo(error) => io::Error::new(error.kind(), error.to_string()), |
| 2473 | Error::Remote(error) => io::Error::new(error.error.kind(), error.to_string()), |
| 2474 | error => io::Error::other(error.to_string()), |
| 2475 | } |
| 2476 | } |
| 2477 | |
| 2478 | /// What happened to the section since the last poll. |
| 2479 | #[derive(Debug)] |
| 2480 | pub enum Event { |
| 2481 | /// A remote change reached these pages; reload them where they are open. |
| 2482 | Changed(Vec<ExGuid>), |
| 2483 | /// The section refused an edit `apply` handed it; the pages it names are as they were |
| 2484 | /// before it, so an editor showing them should reload them. |
| 2485 | Rejected { spaces: Vec<ExGuid>, error: String }, |
| 2486 | /// A publication attempt finished with this durable state. |
| 2487 | Attempt { id: u64, status: EditStatus }, |
| 2488 | /// The section file could not be reached; the replica keeps its state. |
| 2489 | Unreachable(io::Error), |
| 2490 | /// The replica itself failed and the worker stopped, or edits wait in memory for the cache. |
| 2491 | Failed(String), |
| 2492 | } |
| 2493 | |
| 2494 | type Notify = Arc<dyn Fn() + Send + Sync>; |
| 2495 | |
| 2496 | /// How a section's synchronization stands, for the host to show. |
| 2497 | #[derive(Debug)] |
| 2498 | pub struct SyncStatus { |
| 2499 | /// FILETIME of the last synchronization step that reached the section file. |
| 2500 | pub synced: Option<u64>, |
| 2501 | /// Why the last step failed, until one reaches the section file again. |
| 2502 | pub error: Option<io::Error>, |
| 2503 | /// Edits the section file does not hold yet, uncertain attempts and edits waiting for the |
| 2504 | /// cache included; while a failed commit keeps the cache closed, those queued before it. |
| 2505 | pub queued: u64, |
| 2506 | } |
| 2507 | |
| 2508 | /// What a `SyncStatus` comes to for the reader, from the best to the worst. |
| 2509 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] |
| 2510 | pub enum SyncState { |
| 2511 | UpToDate, |
| 2512 | /// Not reached yet, or edits wait. |
| 2513 | Syncing, |
| 2514 | /// Another client holds the section file. |
| 2515 | InUse, |
| 2516 | /// The file or its server cannot be reached; edits wait until it can. |
| 2517 | NotConnected, |
| 2518 | /// The file cannot be written where it is stored. |
| 2519 | ReadOnly, |
| 2520 | /// The section is password protected, which Snowbound cannot open. |
| 2521 | Protected, |
| 2522 | /// The file is stably not a section Snowbound can read. |
| 2523 | Unreadable, |
| 2524 | Failed, |
| 2525 | } |
| 2526 | |
| 2527 | impl SyncStatus { |
| 2528 | pub fn state(&self) -> SyncState { |
| 2529 | use io::ErrorKind::*; |
| 2530 | match self.error.as_ref().map(io::Error::kind) { |
| 2531 | Some(PermissionDenied | ReadOnlyFilesystem) => SyncState::ReadOnly, |
| 2532 | Some(WouldBlock | ResourceBusy) => SyncState::InUse, |
| 2533 | Some(Unsupported) => SyncState::Protected, |
| 2534 | Some(InvalidData) => SyncState::Unreadable, |
| 2535 | Some( |
| 2536 | NotFound | ConnectionRefused | ConnectionReset | ConnectionAborted | NotConnected |
| 2537 | | TimedOut | HostUnreachable | NetworkUnreachable | NetworkDown | BrokenPipe |
| 2538 | | AddrNotAvailable, |
| 2539 | ) => SyncState::NotConnected, |
| 2540 | Some(_) => SyncState::Failed, |
| 2541 | None if self.synced.is_none() || self.queued > 0 => SyncState::Syncing, |
| 2542 | None => SyncState::UpToDate, |
| 2543 | } |
| 2544 | } |
| 2545 | } |
| 2546 | |
| 2547 | /// The last attempt's outcome; `None` before the first. |
| 2548 | pub(crate) type Observed = Option<Option<io::Error>>; |
| 2549 | |
| 2550 | pub(crate) fn sync_status( |
| 2551 | replica: &Replica, |
| 2552 | synced: impl FnOnce() -> Option<u64>, |
| 2553 | observed: &Mutex<Observed>, |
| 2554 | ) -> Result<SyncStatus> { |
| 2555 | let waiting = replica |
| 2556 | .section |
| 2557 | .waiting |
| 2558 | .load(std::sync::atomic::Ordering::Relaxed) as u64; |
| 2559 | let (queued, failed) = match &*(replica.section.cache.lock()) |
| 2560 | .map_err(|_| io::Error::other("Cache owner panicked"))? |
| 2561 | { |
| 2562 | crate::working::Cache::Open(connection) => { |
| 2563 | let queued: i64 = |
| 2564 | connection.query_row("SELECT count(*) FROM edits", [], |row| row.get(0))?; |
| 2565 | (crate::unsigned(queued)?, None) |
| 2566 | } |
| 2567 | crate::working::Cache::Closed { queued, .. } => { |
| 2568 | (*queued, Some("The cache reopens once it can".to_owned())) |
| 2569 | } |
| 2570 | crate::working::Cache::Lost(error) => (0, Some(error.clone())), |
| 2571 | }; |
| 2572 | let observed = observed |
| 2573 | .lock() |
| 2574 | .map_err(|_| io::Error::other("Synchronization observer panicked"))?; |
| 2575 | Ok(SyncStatus { |
| 2576 | // Read after `observed`: the worker stores the time before it clears the error, so a |
| 2577 | // cleared error never shows beside the time of the step before it. |
| 2578 | synced: synced(), |
| 2579 | error: failed.map(io::Error::other).or_else(|| { |
| 2580 | (observed.as_ref().and_then(Option::as_ref)) |
| 2581 | .map(|error| io::Error::new(error.kind(), error.to_string())) |
| 2582 | }), |
| 2583 | queued: queued + waiting, |
| 2584 | }) |
| 2585 | } |
| 2586 | |
| 2587 | /// A section file with its replica and background publication. `Send + Sync`: edits |
| 2588 | /// arrive from any thread without waiting, and `notify` wakes the host when events wait. |
| 2589 | pub struct Section { |
| 2590 | file: PathBuf, |
| 2591 | replica: Arc<Replica>, |
| 2592 | worker: Option<SyncWorker>, |
| 2593 | events: Mutex<Receiver<Event>>, |
| 2594 | sender: Sender<Event>, |
| 2595 | notify: Notify, |
| 2596 | pub(crate) observed: Arc<Mutex<Observed>>, |
| 2597 | } |
| 2598 | |
| 2599 | impl Section { |
| 2600 | /// Opens the lone section file through a replica in `cache`, in the file's |
| 2601 | /// `location::folder`, creating the replica from the file on first use and converting an |
| 2602 | /// older one. `notify` runs on a background thread whenever an event is available. |
| 2603 | pub fn open( |
| 2604 | file: impl AsRef<Path>, |
| 2605 | cache: impl AsRef<Path>, |
| 2606 | offline: bool, |
| 2607 | notify: impl Fn() + Send + 'static, |
| 2608 | ) -> Result<Self> { |
| 2609 | Self::open_with( |
| 2610 | file, |
| 2611 | cache, |
| 2612 | |file, _| Ok(FileRemote(file.to_owned())), |
| 2613 | offline, |
| 2614 | notify, |
| 2615 | ) |
| 2616 | } |
| 2617 | |
| 2618 | /// `open`, reading and publishing the file through the remote `connect` makes for it, |
| 2619 | /// as a host that coordinates file access with other processes (iOS's file providers) |
| 2620 | /// needs. |
| 2621 | pub fn open_with<R: Remote + 'static>( |
| 2622 | file: impl AsRef<Path>, |
| 2623 | cache: impl AsRef<Path>, |
| 2624 | connect: impl FnMut(&Path, Option<&Path>) -> io::Result<R> + Send + 'static, |
| 2625 | offline: bool, |
| 2626 | notify: impl Fn() + Send + 'static, |
| 2627 | ) -> Result<Self> { |
| 2628 | let file = fs::canonicalize(file)?; |
| 2629 | let location = file.to_string_lossy().into_owned(); |
| 2630 | let replicas = claimed(cache.as_ref(), &location); |
| 2631 | Self::open_in(file, None, replicas, connect, CHECK, offline, notify) |
| 2632 | } |
| 2633 | |
| 2634 | /// Opens the canonical section `file`, a protected one under `key`, through the replica |
| 2635 | /// `replica` names for its document identity and image. |
| 2636 | fn open_in<R: Remote + 'static>( |
| 2637 | file: PathBuf, |
| 2638 | key: Option<&protected::Key>, |
| 2639 | replica: impl FnOnce(&[u8; 16], &[u8]) -> Result<PathBuf>, |
| 2640 | mut connect: impl FnMut(&Path, Option<&Path>) -> io::Result<R> + Send + 'static, |
| 2641 | interval: Duration, |
| 2642 | offline: bool, |
| 2643 | notify: impl Fn() + Send + 'static, |
| 2644 | ) -> Result<Self> { |
| 2645 | let source = connect(&file, None)?.read()?; |
| 2646 | let store = Store::parse(&source)?; |
| 2647 | let identity = RevisionIndex::parse(&store)?.root; |
| 2648 | let cache = replica(&identity.guid, &source)?; |
| 2649 | let replica = Replica::open_or_create(&cache, key, || Ok(source))?; |
| 2650 | let remote = file.clone(); |
| 2651 | Self::start( |
| 2652 | file, |
| 2653 | replica, |
| 2654 | move || connect(&remote, Some(&cache)), |
| 2655 | interval, |
| 2656 | offline, |
| 2657 | notify, |
| 2658 | ) |
| 2659 | } |
| 2660 | |
| 2661 | /// Resumes an owned local replica without reading the publication target. |
| 2662 | /// A target with a different document identity is rejected by synchronization. |
| 2663 | pub fn resume( |
| 2664 | file: impl AsRef<Path>, |
| 2665 | replica: Replica, |
| 2666 | offline: bool, |
| 2667 | notify: impl Fn() + Send + 'static, |
| 2668 | ) -> Result<Self> { |
| 2669 | let file = fs::absolute(file)?; |
| 2670 | let remote = file.clone(); |
| 2671 | Self::start( |
| 2672 | file, |
| 2673 | replica, |
| 2674 | move || Ok(FileRemote(remote.clone())), |
| 2675 | CHECK, |
| 2676 | offline, |
| 2677 | notify, |
| 2678 | ) |
| 2679 | } |
| 2680 | |
| 2681 | /// Resumes a replica against a share-relative section path. Credentials remain in |
| 2682 | /// `connect`, which is called on the worker again after transport failures. |
| 2683 | #[cfg(feature = "smb")] |
| 2684 | pub fn resume_smb( |
| 2685 | path: String, |
| 2686 | replica: Replica, |
| 2687 | limit: usize, |
| 2688 | mut connect: impl FnMut() -> io::Result<crate::smb::Client> + Send + 'static, |
| 2689 | offline: bool, |
| 2690 | notify: impl Fn() + Send + 'static, |
| 2691 | ) -> Result<Self> { |
| 2692 | Self::start( |
| 2693 | PathBuf::from(&path), |
| 2694 | replica, |
| 2695 | move || Ok(crate::SmbRemote::new(connect()?, path.clone(), limit)), |
| 2696 | CHECK, |
| 2697 | offline, |
| 2698 | notify, |
| 2699 | ) |
| 2700 | } |
| 2701 | |
| 2702 | /// Resumes a replica against a section a Live Share host serves at catalog `path`. |
| 2703 | #[cfg(feature = "live")] |
| 2704 | pub fn resume_hosted( |
| 2705 | path: String, |
| 2706 | replica: Replica, |
| 2707 | guest: Arc<crate::live::share::Guest>, |
| 2708 | offline: bool, |
| 2709 | notify: impl Fn() + Send + 'static, |
| 2710 | ) -> Result<Self> { |
| 2711 | Self::start( |
| 2712 | PathBuf::from(&path), |
| 2713 | replica, |
| 2714 | move || Ok(crate::live::share::HostedRemote::new(&guest, &path)), |
| 2715 | CHECK, |
| 2716 | offline, |
| 2717 | notify, |
| 2718 | ) |
| 2719 | } |
| 2720 | |
| 2721 | /// Resumes a replica against the section at catalog `path` of a notebook a document |
| 2722 | /// provider keeps (`Notebook::open_provider`). Its file is checked every |
| 2723 | /// `Background::UNWATCHED`, and when `wake` passes on what the host hears of changes. |
| 2724 | pub fn resume_provider( |
| 2725 | path: String, |
| 2726 | replica: Replica, |
| 2727 | documents: Arc<crate::provider::Documents>, |
| 2728 | offline: bool, |
| 2729 | notify: impl Fn() + Send + 'static, |
| 2730 | ) -> Result<Self> { |
| 2731 | let cache = replica.path(); |
| 2732 | Self::start( |
| 2733 | PathBuf::from(&path), |
| 2734 | replica, |
| 2735 | move || { |
| 2736 | let remote = |
| 2737 | crate::provider::ProviderRemote::new(&documents, &path, cache.as_deref()); |
| 2738 | Ok(remote) |
| 2739 | }, |
| 2740 | Background::UNWATCHED, |
| 2741 | offline, |
| 2742 | notify, |
| 2743 | ) |
| 2744 | } |
| 2745 | |
| 2746 | /// Opens the lone section that is the root of `documents` as `open` opens a file, checked |
| 2747 | /// as `resume_provider`'s is; while the provider can't be reached, from the only replica |
| 2748 | /// its location has. |
| 2749 | pub fn open_provider( |
| 2750 | documents: Arc<crate::provider::Documents>, |
| 2751 | offline: bool, |
| 2752 | notify: impl Fn() + Send + Sync + 'static, |
| 2753 | ) -> Result<Self> { |
| 2754 | let (cache, location) = (documents.cache.clone(), documents.location()); |
| 2755 | let cache = cache.as_path(); |
| 2756 | let file = PathBuf::from(&documents.root); |
| 2757 | let remote = move |replica: Option<&Path>| { |
| 2758 | Ok(crate::provider::ProviderRemote::new( |
| 2759 | &documents, "", replica, |
| 2760 | )) |
| 2761 | }; |
| 2762 | let notify = Arc::new(notify); |
| 2763 | let (connect, woken) = (remote.clone(), Arc::clone(&notify)); |
| 2764 | let replicas = claimed(cache, &location); |
| 2765 | let opened = Self::open_in( |
| 2766 | file.clone(), |
| 2767 | None, |
| 2768 | replicas, |
| 2769 | move |_, replica| connect(replica), |
| 2770 | Background::UNWATCHED, |
| 2771 | offline, |
| 2772 | move || woken(), |
| 2773 | ); |
| 2774 | let section = match opened { |
| 2775 | Err(Error::Io(error)) if error.kind() == io::ErrorKind::NotConnected => { |
| 2776 | let mut replicas = fs::read_dir(crate::location::folder(cache, &location)) |
| 2777 | .into_iter() |
| 2778 | .flatten() |
| 2779 | .filter_map(|entry| Some(entry.ok()?.path())) |
| 2780 | .filter(|path| path.extension() == Some("sqlite".as_ref())); |
| 2781 | match (replicas.next(), replicas.next()) { |
| 2782 | (Some(only), None) => Self::start( |
| 2783 | file, |
| 2784 | Replica::open(&only)?, |
| 2785 | move || remote(Some(&only)), |
| 2786 | Background::UNWATCHED, |
| 2787 | offline, |
| 2788 | move || notify(), |
| 2789 | ), |
| 2790 | _ => Err(Error::Io(error)), |
| 2791 | } |
| 2792 | } |
| 2793 | opened => opened, |
| 2794 | }?; |
| 2795 | let legacy = crate::location::folder(cache, &location).join("published"); |
| 2796 | crate::published::adopt(&legacy, |_| section.replica.path())?; |
| 2797 | Ok(section) |
| 2798 | } |
| 2799 | |
| 2800 | fn start<R: Remote + 'static>( |
| 2801 | file: PathBuf, |
| 2802 | replica: Replica, |
| 2803 | connect: impl FnMut() -> io::Result<R> + Send + 'static, |
| 2804 | interval: Duration, |
| 2805 | offline: bool, |
| 2806 | notify: impl Fn() + Send + 'static, |
| 2807 | ) -> Result<Self> { |
| 2808 | let replica = Arc::new(replica); |
| 2809 | let (sender, events) = mpsc::channel(); |
| 2810 | let notify = Mutex::new(notify); |
| 2811 | let notify: Notify = Arc::new(move || { |
| 2812 | if let Ok(notify) = notify.lock() { |
| 2813 | notify(); |
| 2814 | } |
| 2815 | }); |
| 2816 | let observed: Arc<Mutex<Observed>> = Arc::new(Mutex::new(None)); |
| 2817 | if let Ok(mut reread) = replica.section.reread.lock() { |
| 2818 | let (sender, notify) = (sender.clone(), Arc::clone(&notify)); |
| 2819 | *reread = Some(Box::new(move |spaces| { |
| 2820 | if sender.send(Event::Changed(spaces)).is_ok() { |
| 2821 | notify(); |
| 2822 | } |
| 2823 | })); |
| 2824 | } |
| 2825 | let mut section = Self { |
| 2826 | file, |
| 2827 | replica, |
| 2828 | worker: None, |
| 2829 | events: Mutex::new(events), |
| 2830 | sender, |
| 2831 | notify, |
| 2832 | observed, |
| 2833 | }; |
| 2834 | section.worker = Some(section.start_worker(connect, interval, offline, None)?); |
| 2835 | Ok(section) |
| 2836 | } |
| 2837 | |
| 2838 | fn start_worker<R: Remote + 'static>( |
| 2839 | &self, |
| 2840 | connect: impl FnMut() -> io::Result<R> + Send + 'static, |
| 2841 | interval: Duration, |
| 2842 | offline: bool, |
| 2843 | replacing: Option<&SyncWorker>, |
| 2844 | ) -> Result<SyncWorker> { |
| 2845 | let (sender, notify) = (self.sender.clone(), Arc::clone(&self.notify)); |
| 2846 | let observed = Arc::clone(&self.observed); |
| 2847 | Ok(self.replica.start_sync_replacing( |
| 2848 | interval, |
| 2849 | offline, |
| 2850 | connect, |
| 2851 | move |result| { |
| 2852 | let error = result.as_ref().err().map(reached); |
| 2853 | // Reaching the file as the last attempt did is no news to the host. |
| 2854 | let mut changed = false; |
| 2855 | if let Ok(mut observed) = observed.lock() { |
| 2856 | changed = observed |
| 2857 | .as_ref() |
| 2858 | .is_none_or(|last| last.is_some() != error.is_some()); |
| 2859 | *observed = Some(error); |
| 2860 | } |
| 2861 | let mut events = Vec::new(); |
| 2862 | match result { |
| 2863 | Ok(synced) => { |
| 2864 | if !synced.changed.is_empty() { |
| 2865 | events.push(Event::Changed(synced.changed.clone())); |
| 2866 | } |
| 2867 | if let Some((id, status)) = &synced.edit { |
| 2868 | events.push(Event::Attempt { |
| 2869 | id: *id, |
| 2870 | status: status.clone(), |
| 2871 | }); |
| 2872 | } |
| 2873 | } |
| 2874 | Err(Error::RemoteIo(error)) => { |
| 2875 | events.push(Event::Unreachable(match error.raw_os_error() { |
| 2876 | Some(code) => io::Error::from_raw_os_error(code), |
| 2877 | None => io::Error::new(error.kind(), error.to_string()), |
| 2878 | })) |
| 2879 | } |
| 2880 | Err(Error::Remote(error)) => events.push(Event::Unreachable(io::Error::new( |
| 2881 | error.error.kind(), |
| 2882 | error.to_string(), |
| 2883 | ))), |
| 2884 | Err(error) => events.push(Event::Failed(error.to_string())), |
| 2885 | } |
| 2886 | if (changed || !events.is_empty()) |
| 2887 | && events.into_iter().all(|event| sender.send(event).is_ok()) |
| 2888 | { |
| 2889 | notify(); |
| 2890 | } |
| 2891 | }, |
| 2892 | replacing, |
| 2893 | )?) |
| 2894 | } |
| 2895 | |
| 2896 | /// Follows a section file moved within its notebook, keeping its replica and queued edits. |
| 2897 | pub fn relocate(&mut self, file: impl AsRef<Path>) -> Result<()> { |
| 2898 | self.relocate_with(fs::absolute(file)?, |file, _| { |
| 2899 | Ok(FileRemote(file.to_owned())) |
| 2900 | }) |
| 2901 | } |
| 2902 | |
| 2903 | /// `relocate`, with a host's publication target. Cancellation leaves any in-flight step |
| 2904 | /// to finish off-thread; synchronization ownership serializes the replacement worker. |
| 2905 | pub fn relocate_with<R: Remote + 'static>( |
| 2906 | &mut self, |
| 2907 | file: impl AsRef<Path>, |
| 2908 | mut connect: impl FnMut(&Path, Option<&Path>) -> io::Result<R> + Send + 'static, |
| 2909 | ) -> Result<()> { |
| 2910 | let file = file.as_ref().to_owned(); |
| 2911 | let (target, replica) = (file.clone(), self.replica.path()); |
| 2912 | let previous = self.worker.take(); |
| 2913 | if let Some(worker) = &previous { |
| 2914 | worker.cancel(); |
| 2915 | } |
| 2916 | self.observed = Arc::new(Mutex::new(None)); |
| 2917 | self.worker = Some(self.start_worker( |
| 2918 | move || connect(&target, replica.as_deref()), |
| 2919 | CHECK, |
| 2920 | false, |
| 2921 | previous.as_ref(), |
| 2922 | )?); |
| 2923 | self.file = file; |
| 2924 | Ok(()) |
| 2925 | } |
| 2926 | |
| 2927 | /// The absolute local path, or share-relative path for an SMB session. |
| 2928 | pub fn file(&self) -> &Path { |
| 2929 | &self.file |
| 2930 | } |
| 2931 | |
| 2932 | /// The section file identity, which internal links name as `section-id` |
| 2933 | /// (`onestore::page::link::internal_link`). |
| 2934 | pub fn identity(&self) -> Result<[u8; 16]> { |
| 2935 | self.replica.identity() |
| 2936 | } |
| 2937 | |
| 2938 | /// Applies an edit without waiting: it becomes durable on the section thread, which |
| 2939 | /// reports a refusal as `Event::Rejected`. Edits apply in the order they arrive. |
| 2940 | pub fn apply(&self, author: &str, edit: Edit) -> Result<()> { |
| 2941 | self.apply_with(author, edit, |_| {}) |
| 2942 | } |
| 2943 | |
| 2944 | /// Submits without waiting; on completion, calls `reply` before waking the host. |
| 2945 | pub fn apply_with( |
| 2946 | &self, |
| 2947 | author: &str, |
| 2948 | edit: Edit, |
| 2949 | reply: impl FnOnce(Result<u64>) + Send + 'static, |
| 2950 | ) -> Result<()> { |
| 2951 | let (sender, notify) = (self.sender.clone(), Arc::clone(&self.notify)); |
| 2952 | let waiting: crate::working::Notice = { |
| 2953 | let (sender, notify) = (sender.clone(), Arc::clone(&notify)); |
| 2954 | Box::new(move |error| { |
| 2955 | if sender.send(Event::Failed(error.to_owned())).is_ok() { |
| 2956 | notify(); |
| 2957 | } |
| 2958 | }) |
| 2959 | }; |
| 2960 | let root = self.replica.root; |
| 2961 | let spaces = crate::queue::spaces(&edit, root); |
| 2962 | self.replica.submit( |
| 2963 | author, |
| 2964 | edit, |
| 2965 | Box::new(move |result| { |
| 2966 | let event = match &result { |
| 2967 | Ok(_) => None, |
| 2968 | Err(Error::Rejected(error)) => Some(Event::Rejected { |
| 2969 | spaces, |
| 2970 | error: error.to_string(), |
| 2971 | }), |
| 2972 | Err(error) => Some(Event::Failed(error.to_string())), |
| 2973 | }; |
| 2974 | reply(result); |
| 2975 | if let Some(event) = event { |
| 2976 | if sender.send(event).is_ok() { |
| 2977 | notify(); |
| 2978 | } |
| 2979 | } else { |
| 2980 | notify(); |
| 2981 | } |
| 2982 | }), |
| 2983 | waiting, |
| 2984 | ) |
| 2985 | } |
| 2986 | |
| 2987 | /// Page spaces, titles and outline levels (1 at the top) in section order, as the |
| 2988 | /// local edits leave them. |
| 2989 | pub fn pages(&self) -> Result<Vec<(ExGuid, String, u32)>> { |
| 2990 | self.replica.pages() |
| 2991 | } |
| 2992 | |
| 2993 | /// The page to show or edit; O(page), for opening and reloading. |
| 2994 | pub fn page(&self, space: ExGuid) -> Result<Page> { |
| 2995 | self.replica.page(space) |
| 2996 | } |
| 2997 | |
| 2998 | /// Each page's notebook-management identity, which internal links name. |
| 2999 | pub fn identities(&self) -> Result<Vec<(ExGuid, Option<[u8; 16]>)>> { |
| 3000 | self.replica.identities() |
| 3001 | } |
| 3002 | |
| 3003 | /// Copies a page (usually from another section) to the end of this section under |
| 3004 | /// fresh identities, queued like the user's own edits. Returns the new page's space. |
| 3005 | /// Content outside the model refuses to copy. |
| 3006 | pub fn import_page(&self, page: &Page, author: &str) -> Result<ExGuid> { |
| 3007 | crate::task::blocking(self.import_page_async(page, author))? |
| 3008 | } |
| 3009 | |
| 3010 | pub fn import_page_async( |
| 3011 | &self, |
| 3012 | page: &Page, |
| 3013 | author: &str, |
| 3014 | ) -> impl Future<Output = Result<ExGuid>> + Send + 'static + use<> { |
| 3015 | let replica = Arc::clone(&self.replica); |
| 3016 | let author = author.to_owned(); |
| 3017 | let op = copied(page, &author); |
| 3018 | async move { |
| 3019 | let op = op?; |
| 3020 | let Op::Section(SectionOp::Import { creation, .. }) = &op else { |
| 3021 | unreachable!("a copy is an import") |
| 3022 | }; |
| 3023 | let space = creation.space(); |
| 3024 | let edit = Edit { |
| 3025 | at: crate::now(), |
| 3026 | ops: vec![op], |
| 3027 | }; |
| 3028 | replica.apply_async(&author, edit).await?; |
| 3029 | Ok(space) |
| 3030 | } |
| 3031 | } |
| 3032 | |
| 3033 | /// Removes pages or conflict pages permanently, queued like the user's own edits (a |
| 3034 | /// move across sections imports a page there, then retires it here with `Replica::retire`). |
| 3035 | pub fn delete_pages(&self, pages: &[ExGuid]) -> Result<u64> { |
| 3036 | crate::task::blocking(self.delete_pages_async(pages))? |
| 3037 | } |
| 3038 | |
| 3039 | pub fn delete_pages_async( |
| 3040 | &self, |
| 3041 | pages: &[ExGuid], |
| 3042 | ) -> impl Future<Output = Result<u64>> + Send + 'static + use<> { |
| 3043 | let replica = Arc::clone(&self.replica); |
| 3044 | let pages = pages.to_vec(); |
| 3045 | async move { |
| 3046 | replica |
| 3047 | .apply_async( |
| 3048 | "", |
| 3049 | Edit { |
| 3050 | at: crate::now(), |
| 3051 | ops: vec![Op::Section(SectionOp::Delete(pages))], |
| 3052 | }, |
| 3053 | ) |
| 3054 | .await |
| 3055 | } |
| 3056 | } |
| 3057 | |
| 3058 | pub fn status(&self, id: u64) -> Result<Option<EditStatus>> { |
| 3059 | self.replica.status(id) |
| 3060 | } |
| 3061 | |
| 3062 | pub fn pending(&self) -> Result<Vec<PendingEdit>> { |
| 3063 | self.replica.pending() |
| 3064 | } |
| 3065 | |
| 3066 | /// See [`Replica::written`]. |
| 3067 | pub fn written(&self) -> Result<()> { |
| 3068 | self.replica.written() |
| 3069 | } |
| 3070 | |
| 3071 | /// The conflict pages of each page that has them, as the local edits leave them |
| 3072 | /// (`onestore::Section::conflicts`); `page` reads one, `delete_pages` removes it. |
| 3073 | pub fn conflicts(&self) -> Result<Vec<(ExGuid, Vec<onestore::ConflictPage>)>> { |
| 3074 | self.replica.conflicts() |
| 3075 | } |
| 3076 | |
| 3077 | /// The versions of each page that has them, newest first, as the local edits leave them |
| 3078 | /// (`onestore::Section::versions`); `version` reads one. |
| 3079 | pub fn versions(&self) -> Result<Vec<(ExGuid, Vec<onestore::PageVersion>)>> { |
| 3080 | self.replica.versions() |
| 3081 | } |
| 3082 | |
| 3083 | /// Page `space` as its version `version` holds it; O(section). |
| 3084 | pub fn version(&self, space: ExGuid, version: ExGuid) -> Result<Page> { |
| 3085 | self.replica.version(space, version) |
| 3086 | } |
| 3087 | |
| 3088 | /// Makes a page's version its current state, the page as it stood becoming the newest |
| 3089 | /// version, queued like the user's own edits. |
| 3090 | pub fn restore_version(&self, space: ExGuid, version: ExGuid, author: &str) -> Result<u64> { |
| 3091 | crate::task::blocking(self.restore_version_async(space, version, author))? |
| 3092 | } |
| 3093 | |
| 3094 | pub fn restore_version_async( |
| 3095 | &self, |
| 3096 | space: ExGuid, |
| 3097 | version: ExGuid, |
| 3098 | author: &str, |
| 3099 | ) -> impl Future<Output = Result<u64>> + Send + 'static + use<> { |
| 3100 | let replica = Arc::clone(&self.replica); |
| 3101 | let author = author.to_owned(); |
| 3102 | let op = SectionOp::restore(space, version); |
| 3103 | async move { |
| 3104 | replica |
| 3105 | .apply_async( |
| 3106 | &author, |
| 3107 | Edit { |
| 3108 | at: crate::now(), |
| 3109 | ops: vec![Op::Section(op?)], |
| 3110 | }, |
| 3111 | ) |
| 3112 | .await |
| 3113 | } |
| 3114 | } |
| 3115 | |
| 3116 | /// Deletes versions of pages, queued like the user's own edits. |
| 3117 | pub fn delete_versions(&self, versions: &[(ExGuid, Vec<ExGuid>)]) -> Result<u64> { |
| 3118 | crate::task::blocking(self.delete_versions_async(versions))? |
| 3119 | } |
| 3120 | |
| 3121 | pub fn delete_versions_async( |
| 3122 | &self, |
| 3123 | versions: &[(ExGuid, Vec<ExGuid>)], |
| 3124 | ) -> impl Future<Output = Result<u64>> + Send + 'static + use<> { |
| 3125 | let replica = Arc::clone(&self.replica); |
| 3126 | let ops = versions |
| 3127 | .iter() |
| 3128 | .map(|(page, versions)| { |
| 3129 | Op::Section(SectionOp::DeleteVersions { |
| 3130 | page: *page, |
| 3131 | versions: versions.clone(), |
| 3132 | }) |
| 3133 | }) |
| 3134 | .collect(); |
| 3135 | async move { |
| 3136 | replica |
| 3137 | .apply_async( |
| 3138 | "", |
| 3139 | Edit { |
| 3140 | at: crate::now(), |
| 3141 | ops, |
| 3142 | }, |
| 3143 | ) |
| 3144 | .await |
| 3145 | } |
| 3146 | } |
| 3147 | |
| 3148 | /// Retires an uncertain attempt after review, exporting the queue to `archive` first: |
| 3149 | /// `Mine` publishes the local edits again, `Theirs` abandons them. Neither claims the |
| 3150 | /// attempt was acknowledged. |
| 3151 | pub fn release( |
| 3152 | &self, |
| 3153 | id: u64, |
| 3154 | archive: impl AsRef<Path>, |
| 3155 | resolution: Resolution, |
| 3156 | ) -> Result<()> { |
| 3157 | self.replica.release(id, archive.as_ref(), resolution) |
| 3158 | } |
| 3159 | |
| 3160 | /// Captures the queue, its images and its states in a read-only archive. |
| 3161 | pub fn export_recovery(&self, path: impl AsRef<Path>) -> Result<()> { |
| 3162 | self.replica.export_recovery(path) |
| 3163 | } |
| 3164 | |
| 3165 | /// Events since the last poll, oldest first. |
| 3166 | pub fn events(&self) -> Vec<Event> { |
| 3167 | self.events |
| 3168 | .lock() |
| 3169 | .map(|events| events.try_iter().collect()) |
| 3170 | .unwrap_or_default() |
| 3171 | } |
| 3172 | |
| 3173 | /// Requests a synchronization attempt now, working offline included (Sync Now). |
| 3174 | pub fn wake(&self) { |
| 3175 | if let Some(worker) = &self.worker { |
| 3176 | worker.wake(); |
| 3177 | } |
| 3178 | } |
| 3179 | |
| 3180 | /// Publishes local edits once `pause` passes without another (`SyncWorker::set_pause`), |
| 3181 | /// as a notebook on a cloud drive does; `wake` publishes them at once. |
| 3182 | pub fn set_pause(&self, pause: Duration) { |
| 3183 | if let Some(worker) = &self.worker { |
| 3184 | worker.set_pause(pause); |
| 3185 | } |
| 3186 | } |
| 3187 | |
| 3188 | /// Stops or resumes synchronizing: working offline, edits queue until `wake` or until |
| 3189 | /// working online again (OneNote's Work Offline). |
| 3190 | pub fn set_offline(&self, offline: bool) { |
| 3191 | if let Some(worker) = &self.worker { |
| 3192 | worker.set_offline(offline); |
| 3193 | } |
| 3194 | } |
| 3195 | |
| 3196 | /// When the section file was last reached, why it could not be since, and what waits |
| 3197 | /// for it. `notify` runs when it is first reached and when an error comes or goes. |
| 3198 | pub fn sync_status(&self) -> Result<SyncStatus> { |
| 3199 | sync_status( |
| 3200 | &self.replica, |
| 3201 | || self.worker.as_ref().and_then(SyncWorker::synced), |
| 3202 | &self.observed, |
| 3203 | ) |
| 3204 | } |
| 3205 | |
| 3206 | /// The replica, which other threads may read pages from while the section is open. |
| 3207 | pub fn replica(&self) -> &Arc<Replica> { |
| 3208 | &self.replica |
| 3209 | } |
| 3210 | |
| 3211 | /// Stops future sync steps; native threads finish the current operation before returning. |
| 3212 | /// The worker retains cache ownership until its in-flight operation finishes. |
| 3213 | pub fn close(mut self) -> Result<()> { |
| 3214 | match self.worker.take() { |
| 3215 | Some(worker) => worker.stop(), |
| 3216 | None => Ok(()), |
| 3217 | } |
| 3218 | } |
| 3219 | |
| 3220 | /// Stops synchronization without consuming the section's recoverable model. |
| 3221 | pub fn stop_async(&mut self) -> impl Future<Output = Result<()>> + Send + 'static + use<> { |
| 3222 | let worker = self.worker.take(); |
| 3223 | async move { |
| 3224 | match worker { |
| 3225 | Some(worker) => worker.stop_async().await, |
| 3226 | None => Ok(()), |
| 3227 | } |
| 3228 | } |
| 3229 | } |
| 3230 | |
| 3231 | /// Makes the submitted edits locally durable and awaits synchronization before closing. |
| 3232 | pub async fn close_async(mut self) -> Result<()> { |
| 3233 | self.replica.written_async().await?; |
| 3234 | self.stop_async().await |
| 3235 | } |
| 3236 | } |
| 3237 | |
| 3238 | /// The section file itself as the publication target, under OneNote-compatible exclusion. |
| 3239 | struct FileRemote(PathBuf); |
| 3240 | |
| 3241 | impl Remote for FileRemote { |
| 3242 | fn read(&mut self) -> io::Result<Vec<u8>> { |
| 3243 | fs::read_file(&self.0) |
| 3244 | } |
| 3245 | |
| 3246 | /// Read without the whole-file lock, which would block OneNote's readers: a change |
| 3247 | /// detector, never a snapshot to edit. |
| 3248 | fn stamp(&mut self) -> io::Result<Stamp> { |
| 3249 | use std::io::Read; |
| 3250 | let mut file = fs::File::open(&self.0)?; |
| 3251 | let mut header = [0; 1024]; |
| 3252 | file.read_exact(&mut header)?; |
| 3253 | let length = file.metadata()?.len(); |
| 3254 | Ok(Stamp { header, length }) |
| 3255 | } |
| 3256 | |
| 3257 | fn publish(&mut self, transaction: &Transaction) -> std::result::Result<(), CommitError> { |
| 3258 | fs::commit_file(transaction, &self.0) |
| 3259 | } |
| 3260 | |
| 3261 | fn confirm(&mut self, base: &Stamp) -> std::result::Result<(), CommitError> { |
| 3262 | fs::confirm_file(&self.0, base) |
| 3263 | } |
| 3264 | } |
| 3265 | |
| 3266 | impl Drop for Section { |
| 3267 | fn drop(&mut self) { |
| 3268 | drop(self.worker.take()); |
| 3269 | } |
| 3270 | } |
| 3271 | |
| 3272 | #[cfg(test)] |
| 3273 | mod tests; |