lockbook_server_lib/
document_service.rs1use crate::ServerError;
2use crate::config::Config;
3use async_trait::async_trait;
4use lb_rs::model::crypto::EncryptedDocument;
5use lb_rs::model::file_metadata::DocumentHmac;
6use std::fmt::Debug;
7use std::path::PathBuf;
8use tokio::fs::{File, remove_file};
9use tokio::io::{AsyncReadExt, AsyncWriteExt};
10use uuid::Uuid;
11
12#[async_trait]
13pub trait DocumentService: Send + Sync + Clone + 'static {
14 async fn insert<T: Debug>(
15 &self, id: &Uuid, hmac: &DocumentHmac, content: &EncryptedDocument,
16 ) -> Result<(), ServerError<T>>;
17 async fn get<T: Debug>(
18 &self, id: &Uuid, hmac: &DocumentHmac,
19 ) -> Result<EncryptedDocument, ServerError<T>>;
20 async fn maybe_get<T: Debug>(
21 &self, id: &Uuid, hmac: &DocumentHmac,
22 ) -> Result<Option<EncryptedDocument>, ServerError<T>>;
23 async fn delete<T: Debug>(&self, id: &Uuid, hmac: &DocumentHmac) -> Result<(), ServerError<T>>;
24
25 fn exists(&self, id: &Uuid, hmac: &DocumentHmac) -> bool;
26 fn get_path(&self, id: &Uuid, hmac: &DocumentHmac) -> PathBuf;
27}
28
29#[derive(Clone)]
30pub struct OnDiskDocuments {
31 config: Config,
32}
33
34impl From<&Config> for OnDiskDocuments {
35 fn from(value: &Config) -> Self {
36 Self { config: value.clone() }
37 }
38}
39
40#[async_trait]
41impl DocumentService for OnDiskDocuments {
42 async fn insert<T: Debug>(
43 &self, id: &Uuid, hmac: &DocumentHmac, content: &EncryptedDocument,
44 ) -> Result<(), ServerError<T>> {
45 let content = bincode::serialize(content)?;
46 let path = self.get_path(id, hmac);
47 let mut file = File::create(path.clone()).await?;
48 file.write_all(&content)
49 .await
50 .map_err(|err| internal!("{:?}", err))?;
51 file.flush().await.map_err(|err| internal!("{:?}", err))?;
52 Ok(())
53 }
54
55 async fn get<T: Debug>(
56 &self, id: &Uuid, hmac: &DocumentHmac,
57 ) -> Result<EncryptedDocument, ServerError<T>> {
58 let path = self.get_path(id, hmac);
59 let mut file = File::open(path.clone()).await?;
60 let mut content = vec![];
61 file.read_to_end(&mut content).await?;
62 let content = bincode::deserialize(&content)?;
63 Ok(content)
64 }
65
66 async fn maybe_get<T: Debug>(
67 &self, id: &Uuid, hmac: &DocumentHmac,
68 ) -> Result<Option<EncryptedDocument>, ServerError<T>> {
69 let path = self.get_path(id, hmac);
70 if !path.exists() {
71 return Ok(None);
72 }
73
74 Ok(Some(self.get(id, hmac).await?))
75 }
76
77 async fn delete<T: Debug>(&self, id: &Uuid, hmac: &DocumentHmac) -> Result<(), ServerError<T>> {
78 let path = self.get_path(id, hmac);
79 if path.exists() {
85 remove_file(path).await?;
86 }
87 Ok(())
88 }
89
90 fn exists(&self, id: &Uuid, hmac: &DocumentHmac) -> bool {
91 self.get_path(id, hmac).exists()
92 }
93
94 fn get_path(&self, id: &Uuid, hmac: &DocumentHmac) -> PathBuf {
95 let mut path = self.config.files.path.clone();
96 let hmac = base64::encode_config(hmac, base64::URL_SAFE);
98 path.push(format!("{id}-{hmac}"));
99 path
100 }
101}