1use crate::io::docs::LocalDocuments;
4
5use crate::Lb;
6use crate::io::server::Server;
7use crate::model::ValidationFailure;
8use crate::model::api::METADATA_FEE;
9use crate::model::crypto::AESKey;
10use crate::model::errors::{LbErr, LbErrKind, LbResult};
11use crate::model::file::File;
12use crate::model::file_like::FileLike;
13use crate::model::file_metadata::FileType;
14use crate::model::symkey;
15use crate::model::tree_like::TreeLike;
16use crate::service::documents::{compress_encrypt_document, document_hmac};
17use crate::service::events::Actor;
18use futures::StreamExt;
19use futures::stream::FuturesUnordered;
20use std::collections::hash_map::Entry as Slot;
21use std::collections::{HashMap, HashSet};
22use std::fs::{self, Metadata, OpenOptions};
23use std::io::Write;
24use std::path::{Path, PathBuf};
25use tokio::sync::Semaphore;
26use uuid::Uuid;
27
28static EXPORT_DOCUMENTS: Semaphore = Semaphore::const_new(16);
31
32pub enum ImportStatus {
33 CalculatedTotal(usize),
34 StartingItem(String),
35 FinishedItem(File),
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum Existing {
41 Copy,
43 Update,
46}
47
48#[derive(Clone, Debug)]
50pub struct ImportPlan {
51 pub dest: Uuid,
52 pub entries: Vec<Entry>,
54}
55
56#[derive(Clone, Debug)]
57pub struct Entry {
58 pub disk_path: PathBuf,
59 pub file_type: EntryType,
60 pub action: Action,
61 pub skip: bool,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum EntryType {
68 Folder,
69 Document {
73 disk_bytes: u64,
74 stored_bytes: u64,
75 added_bytes: u64,
76 },
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum Action {
81 Create,
82 Replace(Uuid),
83 Noop(Uuid),
85 Ignore(IgnoreReason),
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub enum IgnoreReason {
90 Hidden,
92 Unreadable,
93 NotAFile,
95}
96
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
99pub struct DocTotals {
100 pub files: usize,
101 pub added_bytes: u64,
102}
103
104impl DocTotals {
105 fn add(&mut self, added_bytes: u64) {
106 self.files += 1;
107 self.added_bytes += added_bytes;
108 }
109}
110
111#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub struct ImportSummary {
114 pub new: usize,
115 pub changed: usize,
116 pub same: usize,
118 pub disk_bytes: u64,
120 pub stored_bytes: u64,
122 pub added_bytes: u64,
124 pub skipped: DocTotals,
125 pub hidden: usize,
126 pub unreadable: usize,
127 pub not_a_file: usize,
128}
129
130impl Entry {
131 pub fn name(&self) -> String {
132 self.disk_path
133 .file_name()
134 .map(|n| n.to_string_lossy().into_owned())
135 .unwrap_or_default()
136 }
137
138 pub fn writes(&self) -> bool {
140 matches!(self.action, Action::Create | Action::Replace(_)) && !self.skip
141 }
142}
143
144impl<S: Server, D: LocalDocuments> Lb<S, D> {
145 async fn create_imported(
149 &self, name: &str, parent: Uuid, content: Option<&[u8]>,
150 ) -> LbResult<File> {
151 let id = self.entropy.id();
152 let key = self.entropy.key();
153 let document = match content {
154 Some(content) => {
155 let (hmac, encrypted) = compress_encrypt_document(&key, content)?;
156 let pending = self.docs.insert_pending(id, hmac, &encrypted).await?;
157 Some((pending, hmac, encrypted.value.len()))
158 }
159 None => None,
160 };
161 let file_type = if document.is_some() { FileType::Document } else { FileType::Folder };
162
163 let mut tx = self.begin_tx().await;
164 let db = tx.db();
165 let mut tree = (&db.base_metadata)
166 .to_staged(&mut db.local_metadata)
167 .to_lazy();
168 let content = match document {
169 Some((pending, hmac, size)) => {
170 pending.promote().await?;
171 Some((hmac, size))
172 }
173 None => None,
174 };
175 let mut free_name = name.to_string();
176 for tries in 1.. {
177 match tree.create(id, key, &parent, &free_name, file_type, &self.keychain) {
178 Err(err)
179 if matches!(
180 err.kind,
181 LbErrKind::Validation(ValidationFailure::PathConflict(_))
182 ) =>
183 {
184 free_name = format!("{name}-{tries}");
185 }
186 result => {
187 result?;
188 break;
189 }
190 }
191 }
192 if let Some((hmac, size)) = content {
193 tree.overwrite_document_hmac(&id, Some(hmac), Some(size), &self.keychain)?;
194 }
195 let file = tree.decrypt(&self.keychain, &id, &db.pub_key_lookup)?;
196 tx.end();
197
198 self.events.meta_changed(Actor::User(None));
199 if content.is_some() {
200 self.events.doc_written(id, Actor::User(None));
201 }
202 Ok(file)
203 }
204
205 async fn holds(&self, id: Uuid, content: &[u8]) -> LbResult<bool> {
207 let (hmac, key) = {
208 let tx = self.ro_tx().await;
209 let db = tx.db();
210 let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
211 let hmac = tree.find(&id)?.document_hmac().copied();
212 (hmac, tree.decrypt_key(&id, &self.keychain)?)
213 };
214 Ok(match hmac {
215 Some(hmac) => document_hmac(&key, content)? == hmac,
216 None => content.is_empty(),
217 })
218 }
219}
220
221fn stored_size(key: &AESKey, data: &[u8]) -> LbResult<u64> {
224 Ok(compress_encrypt_document(key, data)?.1.value.len() as u64)
225}
226
227fn hidden(name: &str, meta: &Metadata) -> bool {
229 if name.starts_with('.') {
230 return true;
231 }
232 #[cfg(target_os = "macos")]
233 {
234 use std::os::macos::fs::MetadataExt;
235 const UF_HIDDEN: u32 = 0x8000;
236 meta.st_flags() & UF_HIDDEN != 0
237 }
238 #[cfg(target_os = "ios")]
239 {
240 use std::os::ios::fs::MetadataExt;
241 const UF_HIDDEN: u32 = 0x8000;
242 meta.st_flags() & UF_HIDDEN != 0
243 }
244 #[cfg(windows)]
245 {
246 use std::os::windows::fs::MetadataExt;
247 const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;
248 meta.file_attributes() & FILE_ATTRIBUTE_HIDDEN != 0
249 }
250 #[cfg(not(any(target_os = "macos", target_os = "ios", windows)))]
251 {
252 let _ = meta;
253 false
254 }
255}
256
257impl<S: Server, D: LocalDocuments> Lb<S, D> {
258 async fn plan_entry(
260 &self, disk_path: &Path, parent: Option<Uuid>, top: bool, key: &AESKey,
261 children: &mut HashMap<Uuid, Vec<File>>,
262 ) -> LbResult<(EntryType, Action)> {
263 let unread = EntryType::Document { disk_bytes: 0, stored_bytes: 0, added_bytes: 0 };
264
265 let Ok(meta) = fs::symlink_metadata(disk_path) else {
268 return Ok((unread, Action::Ignore(IgnoreReason::Unreadable)));
269 };
270 let file_type = if meta.is_dir() { EntryType::Folder } else { unread };
271 let Some(name) = disk_path.file_name().and_then(|n| n.to_str()) else {
272 return Ok((file_type, Action::Ignore(IgnoreReason::Unreadable)));
273 };
274
275 if !top && hidden(name, &meta) {
277 return Ok((file_type, Action::Ignore(IgnoreReason::Hidden)));
278 }
279
280 let existing = match parent {
282 Some(parent) => {
283 let listed = match children.entry(parent) {
284 Slot::Occupied(listed) => listed.into_mut(),
285 Slot::Vacant(slot) => slot.insert(self.all_children(&parent).await?),
286 };
287 listed.iter().find(|f| f.name == name).cloned()
288 }
289 None => None,
290 };
291
292 if meta.is_dir() {
294 let action = match existing.filter(|f| f.is_folder()) {
295 Some(f) => Action::Noop(f.id),
296 None => Action::Create,
297 };
298 return Ok((file_type, action));
299 }
300
301 if !meta.is_file() {
303 return Ok((file_type, Action::Ignore(IgnoreReason::NotAFile)));
304 }
305 let Ok(data) = fs::read(disk_path) else {
306 return Ok((file_type, Action::Ignore(IgnoreReason::Unreadable)));
307 };
308 let disk_bytes = data.len() as u64;
309 let existing = existing.filter(|f| f.is_document());
310 let held = |f: &File| f.size_bytes.saturating_sub(METADATA_FEE);
312
313 if let Some(f) = &existing {
315 if self.holds(f.id, &data).await? {
316 let (stored_bytes, added_bytes) = (held(f), 0);
317 return Ok((
318 EntryType::Document { disk_bytes, stored_bytes, added_bytes },
319 Action::Noop(f.id),
320 ));
321 }
322 }
323
324 let stored_bytes = stored_size(key, &data)?;
327 Ok(match existing {
328 Some(f) => {
329 let added_bytes = stored_bytes.saturating_sub(held(&f));
330 (
331 EntryType::Document { disk_bytes, stored_bytes, added_bytes },
332 Action::Replace(f.id),
333 )
334 }
335 None => {
336 let added_bytes = stored_bytes + METADATA_FEE;
337 (EntryType::Document { disk_bytes, stored_bytes, added_bytes }, Action::Create)
338 }
339 })
340 }
341
342 #[instrument(level = "debug", skip(self), err(Debug))]
345 pub async fn plan_import(
346 &self, sources: &[PathBuf], dest: Uuid, existing: Existing,
347 ) -> LbResult<ImportPlan> {
348 let parent = self.get_file_by_id(dest).await?;
350 if !parent.is_folder() {
351 Err(LbErrKind::Validation(ValidationFailure::NonFolderWithChildren(dest)))?;
352 }
353
354 let key = symkey::generate_key();
356 let mut children = HashMap::new();
357 let mut entries = Vec::new();
358
359 let mut stack: Vec<(PathBuf, Option<Uuid>, bool)> = sources
363 .iter()
364 .rev()
365 .filter(|s| !sources.iter().any(|o| o != *s && s.starts_with(o)))
366 .map(|s| (s.clone(), (existing == Existing::Update).then_some(dest), true))
367 .collect();
368
369 while let Some((disk_path, parent, top)) = stack.pop() {
372 let (file_type, mut action) = self
373 .plan_entry(&disk_path, parent, top, &key, &mut children)
374 .await?;
375 if file_type == EntryType::Folder && !matches!(action, Action::Ignore(_)) {
376 let listed: std::io::Result<Vec<PathBuf>> = fs::read_dir(&disk_path)
377 .and_then(|dir| dir.map(|child| Ok(child?.path())).collect());
378 match listed {
379 Ok(mut inside) => {
380 let here = match action {
381 Action::Noop(id) => Some(id),
382 _ => None,
383 };
384 inside.sort();
385 stack.extend(inside.into_iter().rev().map(|c| (c, here, false)));
386 }
387 Err(_) => action = Action::Ignore(IgnoreReason::Unreadable),
389 }
390 }
391 entries.push(Entry { disk_path, file_type, action, skip: false });
392 }
393 Ok(ImportPlan { dest, entries })
394 }
395}
396
397impl ImportPlan {
398 pub fn summary(&self) -> ImportSummary {
400 let mut s = ImportSummary::default();
401 for e in &self.entries {
402 match (e.action, e.file_type) {
403 (Action::Ignore(IgnoreReason::Hidden), _) => s.hidden += 1,
404 (Action::Ignore(IgnoreReason::Unreadable), _) => s.unreadable += 1,
405 (Action::Ignore(IgnoreReason::NotAFile), _) => s.not_a_file += 1,
406 (Action::Noop(_), EntryType::Document { .. }) => s.same += 1,
407 (Action::Noop(_), EntryType::Folder) => {}
408 (_, EntryType::Folder) => {
409 s.stored_bytes += METADATA_FEE;
410 s.added_bytes += METADATA_FEE;
411 }
412 (_, EntryType::Document { added_bytes, .. }) if e.skip => {
413 s.skipped.add(added_bytes)
414 }
415 (action, EntryType::Document { disk_bytes, stored_bytes, added_bytes, .. }) => {
416 if action == Action::Create {
417 s.new += 1;
418 s.stored_bytes += stored_bytes + METADATA_FEE;
419 } else {
420 s.changed += 1;
421 s.stored_bytes += stored_bytes;
422 }
423 s.disk_bytes += disk_bytes;
424 s.added_bytes += added_bytes;
425 }
426 }
427 }
428 s
429 }
430}
431
432impl<S: Server, D: LocalDocuments> Lb<S, D> {
433 async fn import_entry(&self, e: &Entry, parent: Uuid) -> LbResult<File> {
435 let name = e
436 .disk_path
437 .file_name()
438 .and_then(|n| n.to_str())
439 .ok_or(LbErrKind::DiskPathInvalid)?;
440 if e.file_type == EntryType::Folder {
441 return self.create_imported(name, parent, None).await;
442 }
443 let content = fs::read(&e.disk_path).map_err(LbErr::from)?;
444 match e.action {
445 Action::Replace(id) => {
446 self.write_document(id, &content).await?;
447 self.get_file_by_id(id).await
448 }
449 _ => self.create_imported(name, parent, Some(&content)).await,
450 }
451 }
452
453 #[instrument(level = "debug", skip(self, plan, update_status), err(Debug))]
456 pub async fn import_planned<F: Fn(ImportStatus)>(
457 &self, plan: &ImportPlan, update_status: &F,
458 ) -> LbResult<()> {
459 let total = plan.entries.iter().filter(|e| e.writes()).count();
460 update_status(ImportStatus::CalculatedTotal(total));
461
462 let folders: HashSet<&Path> = plan
463 .entries
464 .iter()
465 .filter(|e| e.file_type == EntryType::Folder)
466 .map(|e| e.disk_path.as_path())
467 .collect();
468 let mut ids: HashMap<&Path, Uuid> = HashMap::new();
469 let mut failed = Vec::new();
470 for e in &plan.entries {
471 if let (Action::Noop(id), EntryType::Folder) = (e.action, e.file_type) {
472 ids.insert(&e.disk_path, id);
473 }
474 if !e.writes() {
475 continue;
476 }
477 let parent = match e.disk_path.parent().filter(|p| folders.contains(p)) {
478 Some(folder) => ids.get(folder).copied(),
479 None => Some(plan.dest),
480 };
481 update_status(ImportStatus::StartingItem(e.disk_path.display().to_string()));
482 let result = match parent {
483 Some(parent) => self.import_entry(e, parent).await,
484 None => Err(LbErrKind::FileParentNonexistent.into()),
485 };
486 match result {
487 Ok(file) => {
488 if e.file_type == EntryType::Folder {
489 ids.insert(&e.disk_path, file.id);
490 }
491 update_status(ImportStatus::FinishedItem(file));
492 }
493 Err(err) => {
494 error!(?err, path = %e.disk_path.display(), "import failed");
495 failed.push(e.disk_path.clone());
496 }
497 }
498 }
499 if failed.is_empty() {
500 Ok(())
501 } else {
502 Err(LbErrKind::ImportFailed { paths: failed, total }.into())
503 }
504 }
505
506 #[instrument(level = "debug", skip(self, update_status), err(Debug))]
510 pub async fn import_files<F: Fn(ImportStatus)>(
511 &self, sources: &[PathBuf], dest: Uuid, update_status: &F,
512 ) -> LbResult<()> {
513 let plan = self.plan_import(sources, dest, Existing::Copy).await?;
514 let mut failed: Vec<PathBuf> = plan
515 .entries
516 .iter()
517 .filter(|e| match e.action {
518 Action::Ignore(IgnoreReason::Unreadable) => true,
519 Action::Ignore(IgnoreReason::NotAFile) => sources.contains(&e.disk_path),
520 _ => false,
521 })
522 .map(|e| e.disk_path.clone())
523 .collect();
524 let total = failed.len() + plan.entries.iter().filter(|e| e.writes()).count();
525 if let Err(err) = self.import_planned(&plan, update_status).await {
526 let LbErrKind::ImportFailed { paths, .. } = &err.kind else {
527 return Err(err);
528 };
529 failed.extend(paths.iter().cloned());
530 }
531 if failed.is_empty() {
532 Ok(())
533 } else {
534 Err(LbErrKind::ImportFailed { paths: failed, total }.into())
535 }
536 }
537}
538
539impl<S: Server, D: LocalDocuments> Lb<S, D> {
540 #[instrument(level = "debug", skip(self, update_status), err(Debug))]
541 pub async fn export_file<F: Fn(ExportFileInfo)>(
542 &self, id: Uuid, dest: PathBuf, edit: bool, update_status: &Option<F>,
543 ) -> LbResult<()> {
544 if dest.is_file() {
545 return Err(LbErrKind::DiskPathInvalid.into());
546 }
547
548 self.export_file_recursively(id, &dest, edit, update_status)
549 .await
550 }
551
552 pub async fn export_file_recursively<F: Fn(ExportFileInfo)>(
553 &self, id: Uuid, disk_path: &Path, edit: bool, update_status: &Option<F>,
554 ) -> LbResult<()> {
555 let file = self.get_file_by_id(id).await?;
556
557 let new_dest = disk_path.join(&file.name);
558
559 if let Some(update_status) = update_status {
560 update_status(ExportFileInfo {
561 disk_path: disk_path.to_path_buf(),
562 lockbook_path: self.get_path_by_id(file.id).await?,
563 });
564 }
565
566 match file.file_type {
567 FileType::Document => {
568 let _permit = EXPORT_DOCUMENTS
569 .acquire()
570 .await
571 .expect("export semaphore is never closed");
572 let content = self.read_document(file.id, true).await?;
573
574 let mut disk_file = if edit {
576 OpenOptions::new()
577 .write(true)
578 .create(true)
579 .truncate(true)
580 .open(new_dest)
581 } else {
582 OpenOptions::new()
583 .write(true)
584 .create_new(true)
585 .open(new_dest)
586 }
587 .map_err(LbErr::from)?;
588
589 disk_file.write_all(&content).map_err(LbErr::from)?;
590
591 if let Some(folder) = self.get_attachments_folder(&file.id).await? {
594 if folder.parent != file.parent {
595 Box::pin(
596 self.export_file_recursively(folder.id, disk_path, edit, &None::<F>),
597 )
598 .await?;
599 }
600 }
601 }
602 FileType::Folder => {
603 fs::create_dir(new_dest.clone()).map_err(LbErr::from)?;
604 let export_file_futures = FuturesUnordered::new();
605
606 for child in self.all_children(&file.id).await? {
607 let lb = self.clone();
608 let new_dest = &new_dest;
609
610 export_file_futures.push(async move {
611 lb.export_file_recursively(child.id, new_dest, edit, update_status)
612 .await
613 });
614 }
615
616 export_file_futures
617 .collect::<Vec<LbResult<()>>>()
618 .await
619 .into_iter()
620 .collect::<LbResult<()>>()?;
621 }
622 FileType::Link { target } => {
623 let export_file_futures = FuturesUnordered::new();
624 let lb = self.clone();
625
626 export_file_futures.push(async move {
627 lb.export_file_recursively(target, disk_path, edit, update_status)
628 .await
629 });
630
631 export_file_futures
632 .collect::<Vec<LbResult<()>>>()
633 .await
634 .into_iter()
635 .collect::<LbResult<()>>()?;
636 }
637 }
638
639 Ok(())
640 }
641}
642
643#[derive(Debug, Clone)]
644pub struct ExportFileInfo {
645 pub disk_path: PathBuf,
646 pub lockbook_path: String,
647}