lockbook_server_lib/
document_service.rs1use crate::ServerError;
2use crate::config::Config;
3use lb_rs::io::docs::DocumentStore;
4use lb_rs::model::crypto::EncryptedDocument;
5use lb_rs::model::errors::{LbErr, LbErrKind, LbResult};
6use lb_rs::model::file_metadata::DocumentHmac;
7use std::fmt::Debug;
8use std::path::PathBuf;
9use tokio::fs::{File, remove_file};
10use tokio::io::{AsyncReadExt, AsyncWriteExt};
11use uuid::Uuid;
12
13pub trait DocumentService: DocumentStore {
15 fn get_path(&self, id: Uuid, hmac: DocumentHmac) -> PathBuf;
16}
17
18pub fn stored<T: Debug>(err: LbErr) -> ServerError<T> {
20 internal!("document store: {:?}", err)
21}
22
23#[derive(Clone)]
24pub struct OnDiskDocuments {
25 config: Config,
26}
27
28impl From<&Config> for OnDiskDocuments {
29 fn from(value: &Config) -> Self {
30 Self { config: value.clone() }
31 }
32}
33
34fn unexpected(err: impl Debug) -> LbErr {
35 LbErrKind::Unexpected(format!("{err:?}")).into()
36}
37
38impl DocumentStore for OnDiskDocuments {
39 async fn insert(
40 &self, id: Uuid, hmac: DocumentHmac, content: &EncryptedDocument,
41 ) -> LbResult<()> {
42 let content = bincode::serialize(content).map_err(unexpected)?;
43 let path = self.get_path(id, hmac);
44 let mut file = File::create(path).await.map_err(unexpected)?;
45 file.write_all(&content).await.map_err(unexpected)?;
46 file.flush().await.map_err(unexpected)?;
47 Ok(())
48 }
49
50 async fn maybe_get(&self, id: Uuid, hmac: DocumentHmac) -> LbResult<Option<EncryptedDocument>> {
51 let path = self.get_path(id, hmac);
52 if !path.exists() {
53 return Ok(None);
54 }
55 let mut file = File::open(path).await.map_err(unexpected)?;
56 let mut content = vec![];
57 file.read_to_end(&mut content).await.map_err(unexpected)?;
58 Ok(Some(bincode::deserialize(&content).map_err(unexpected)?))
59 }
60
61 async fn delete(&self, id: Uuid, hmac: DocumentHmac) -> LbResult<()> {
62 let path = self.get_path(id, hmac);
63 if path.exists() {
69 remove_file(path).await.map_err(unexpected)?;
70 }
71 Ok(())
72 }
73
74 fn exists(&self, id: Uuid, hmac: DocumentHmac) -> bool {
75 self.get_path(id, hmac).exists()
76 }
77}
78
79impl DocumentService for OnDiskDocuments {
80 fn get_path(&self, id: Uuid, hmac: DocumentHmac) -> PathBuf {
81 let mut path = self.config.files.path.clone();
82 let hmac = base64::encode_config(hmac, base64::URL_SAFE);
84 path.push(format!("{id}-{hmac}"));
85 path
86 }
87}