Skip to main content

lb_rs/service/
file.rs

1use crate::Lb;
2use crate::io::docs::LocalDocuments;
3use crate::io::server::Server;
4use crate::model::access_info::UserAccessMode;
5use crate::model::errors::{LbErrKind, LbResult};
6use crate::model::file::File;
7use crate::model::file_like::FileLike;
8use crate::model::file_metadata::{FileType, Owner};
9use crate::model::filename::{MAX_FILENAME_LENGTH, NameComponents};
10use crate::model::lazy::LazyTree;
11use crate::model::signed_meta::SignedMeta;
12use crate::model::tree_like::TreeLike;
13use crate::service::events::Actor;
14use std::collections::HashMap;
15use std::iter;
16use uuid::Uuid;
17
18/// The attachments folders [Lb::list_attachments] finds, with what's in them.
19#[derive(Debug, Clone, Default)]
20pub struct Attachments {
21    /// Every attachments folder and everything inside
22    pub files: Vec<File>,
23    /// Note id -> its attachments folder id
24    pub folders: HashMap<Uuid, Uuid>,
25}
26
27impl<S: Server, D: LocalDocuments> Lb<S, D> {
28    #[instrument(level = "debug", skip(self), err(Debug))]
29    pub async fn create_file(
30        &self, name: &str, parent: &Uuid, file_type: FileType,
31    ) -> LbResult<File> {
32        let mut tx = self.begin_tx().await;
33        let db = tx.db();
34
35        // todo this is checked later and probably can be removed
36        if name.len() > MAX_FILENAME_LENGTH {
37            return Err(LbErrKind::FileNameTooLong.into());
38        }
39        let mut tree = (&db.base_metadata)
40            .to_staged(&mut db.local_metadata)
41            .to_lazy();
42
43        let id = tree.create(
44            self.entropy.id(),
45            self.entropy.key(),
46            parent,
47            name,
48            file_type,
49            &self.keychain,
50        )?;
51
52        let ui_file = tree.decrypt(&self.keychain, &id, &db.pub_key_lookup)?;
53
54        tx.end();
55
56        self.events.meta_changed(Actor::User(None));
57        Ok(ui_file)
58    }
59
60    /// Creates `document`'s attachments folder, beside it and named for it: `plan.md`'s is
61    /// `plan-attachments`. The folder keeps that name when the document is renamed. Refused as
62    /// [LbErrKind::InsufficientPermission] while this device doesn't create them
63    /// ([Lb::attachments_folders]), and refused when the document already has one.
64    #[instrument(level = "debug", skip(self), err(Debug))]
65    pub async fn create_attachments_folder(&self, document: &Uuid) -> LbResult<File> {
66        if !self.attachments_folders {
67            return Err(LbErrKind::InsufficientPermission.into());
68        }
69        let mut tx = self.begin_tx().await;
70        let db = tx.db();
71
72        let mut tree = (&db.base_metadata)
73            .to_staged(&mut db.local_metadata)
74            .to_lazy();
75
76        let id = tree.create_attachments(
77            self.entropy.id(),
78            self.entropy.key(),
79            document,
80            &self.keychain,
81        )?;
82        let ui_file = tree.decrypt(&self.keychain, &id, &db.pub_key_lookup)?;
83
84        tx.end();
85
86        self.events.meta_changed(Actor::User(None));
87        Ok(ui_file)
88    }
89
90    /// Every attachments folder and everything in it that isn't deleted, including those
91    /// [Self::list_metadatas] leaves out, for an app that hides them itself but still finds images
92    /// and plans links through them.
93    #[instrument(level = "debug", skip(self), err(Debug))]
94    pub async fn list_attachments(&self) -> LbResult<Attachments> {
95        let tx = self.ro_tx().await;
96        let db = tx.db();
97
98        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
99        let mut ids = Vec::new();
100        let mut folders = HashMap::new();
101        for id in tree.ids() {
102            if tree.in_attachments(&id)?
103                && !tree.find(&id)?.is_link()
104                && !tree.calculate_deleted(&id)?
105            {
106                ids.push(id);
107                if let Some(of) = tree.find(&id)?.attachment_of() {
108                    folders.entry(of.id).or_insert(id);
109                }
110            }
111        }
112
113        let files = tree.decrypt_all(&self.keychain, ids.into_iter(), &db.pub_key_lookup, false)?;
114        Ok(Attachments { files, folders })
115    }
116
117    /// `document`'s attachments folder, if it has one that isn't deleted.
118    #[instrument(level = "debug", skip(self), err(Debug))]
119    pub async fn get_attachments_folder(&self, document: &Uuid) -> LbResult<Option<File>> {
120        let tx = self.ro_tx().await;
121        let db = tx.db();
122
123        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
124        tree.find(document)?;
125        let Some(id) = tree.attachments_folder(document)? else {
126            return Ok(None);
127        };
128        Ok(Some(tree.decrypt(&self.keychain, &id, &db.pub_key_lookup)?))
129    }
130
131    /// The document `folder` is the attachments folder of, if it is one. Such a folder moves only
132    /// with its document and is never renamed, so a host that offers rename and move per file can leave
133    /// them off it.
134    #[instrument(level = "debug", skip(self), err(Debug))]
135    pub async fn attachments_of(&self, folder: &Uuid) -> LbResult<Option<Uuid>> {
136        let tx = self.ro_tx().await;
137        let db = tx.db();
138
139        let tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
140        Ok(tree.find(folder)?.attachment_of().map(|of| of.id))
141    }
142
143    #[instrument(level = "debug", skip(self), err(Debug))]
144    pub async fn rename_file(&self, id: &Uuid, new_name: &str) -> LbResult<()> {
145        let mut tx = self.begin_tx().await;
146        let db = tx.db();
147
148        if new_name.len() > MAX_FILENAME_LENGTH {
149            return Err(LbErrKind::FileNameTooLong.into());
150        }
151        let mut tree = (&db.base_metadata)
152            .to_staged(&mut db.local_metadata)
153            .to_lazy();
154
155        let id = &tree.linked_by(id)?.unwrap_or(*id);
156
157        tree.rename(id, new_name, &self.keychain)?;
158
159        tx.end();
160
161        self.events.meta_changed(Actor::User(None));
162
163        Ok(())
164    }
165
166    #[instrument(level = "debug", skip(self), err(Debug))]
167    pub async fn move_file(&self, id: &Uuid, new_parent: &Uuid) -> LbResult<()> {
168        let mut tx = self.begin_tx().await;
169        let db = tx.db();
170
171        let mut tree = (&db.base_metadata)
172            .to_staged(&mut db.local_metadata)
173            .to_lazy();
174
175        let id = &tree.linked_by(id)?.unwrap_or(*id);
176
177        tree.move_file(id, new_parent, &self.keychain)?;
178        tx.end();
179
180        self.events.meta_changed(Actor::User(None));
181
182        Ok(())
183    }
184
185    #[instrument(level = "debug", skip(self), err(Debug))]
186    pub async fn duplicate_file(&self, id: &Uuid) -> LbResult<File> {
187        let mut source = self.get_file_by_id(*id).await?;
188        if let FileType::Link { target } = source.file_type {
189            source = self.get_file_by_id(target).await?;
190        }
191        if !source.is_document() {
192            return Err(LbErrKind::FileNotDocument.into());
193        }
194
195        let content = self.read_document(source.id, false).await?;
196
197        let name = NameComponents::from(&source.name)
198            .free_copy_in(&self.all_children(&source.parent).await?);
199
200        let new_file = self
201            .create_file(&name, &source.parent, FileType::Document)
202            .await?;
203        self.write_document(new_file.id, &content).await?;
204
205        Ok(new_file)
206    }
207
208    #[instrument(level = "debug", skip(self), err(Debug))]
209    pub async fn delete(&self, id: &Uuid) -> LbResult<()> {
210        let mut tx = self.begin_tx().await;
211        let db = tx.db();
212
213        let mut tree = (&db.base_metadata)
214            .to_staged(&mut db.local_metadata)
215            .to_lazy();
216
217        let id = &tree.linked_by(id)?.unwrap_or(*id);
218
219        tree.delete(id, &self.keychain)?;
220
221        tx.end();
222
223        self.events.meta_changed(Actor::User(None));
224
225        Ok(())
226    }
227
228    // todo: keychain?
229    #[instrument(level = "debug", skip(self), err(Debug))]
230    pub async fn root(&self) -> LbResult<File> {
231        let tx = self.ro_tx().await;
232        let db = tx.db();
233
234        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
235
236        let root_id = db.root.as_ref().ok_or(LbErrKind::RootNonexistent)?;
237
238        let root = tree.decrypt(&self.keychain, root_id, &db.pub_key_lookup)?;
239
240        Ok(root)
241    }
242
243    /// All files as this client lists them: attachments hidden for desktop and mobile, shown for cli
244    /// and files integrations
245    #[instrument(level = "debug", skip(self), err(Debug))]
246    pub async fn list_metadatas(&self) -> LbResult<Vec<File>> {
247        let tx = self.ro_tx().await;
248        let db = tx.db();
249
250        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
251
252        let mut ids = tree.ids();
253        if !self.config.list_attachments {
254            ids = Self::omit_attachments(&mut tree, ids)?;
255        }
256
257        tree.decrypt_all(&self.keychain, ids.into_iter(), &db.pub_key_lookup, true)
258    }
259
260    /// Every file, attachments folders and their contents included, for lb's own walks.
261    pub(crate) async fn all_metadatas(&self) -> LbResult<Vec<File>> {
262        let tx = self.ro_tx().await;
263        let db = tx.db();
264
265        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
266
267        let ids = tree.ids();
268
269        tree.decrypt_all(&self.keychain, ids.into_iter(), &db.pub_key_lookup, true)
270    }
271
272    /// A folder's children as this client lists them: attachments hidden for desktop and mobile,
273    /// shown for cli and files integrations
274    #[instrument(level = "debug", skip(self), err(Debug))]
275    pub async fn get_children(&self, id: &Uuid) -> LbResult<Vec<File>> {
276        let tx = self.ro_tx().await;
277        let db = tx.db();
278
279        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
280
281        let mut ids = tree.children_using_links(id)?;
282        if !self.config.list_attachments {
283            ids = Self::omit_attachments(&mut tree, ids)?;
284        }
285
286        tree.decrypt_all(&self.keychain, ids.into_iter(), &db.pub_key_lookup, true)
287    }
288
289    /// All of `id`'s children that aren't deleted, including the ones listings leave out, for lb's
290    /// own walks and name checks.
291    pub(crate) async fn all_children(&self, id: &Uuid) -> LbResult<Vec<File>> {
292        let tx = self.ro_tx().await;
293        let db = tx.db();
294
295        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
296
297        let mut ids = Vec::new();
298        for child in tree.children_using_links(id)? {
299            if !tree.calculate_deleted(&child)? {
300                ids.push(child);
301            }
302        }
303
304        tree.decrypt_all(&self.keychain, ids.into_iter(), &db.pub_key_lookup, false)
305    }
306
307    #[instrument(level = "debug", skip(self), err(Debug))]
308    pub async fn get_and_get_children_recursively(&self, id: &Uuid) -> LbResult<Vec<File>> {
309        let tx = self.ro_tx().await;
310        let db = tx.db();
311
312        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
313
314        let mut descendants = tree.descendants_using_links(id)?;
315        if !self.config.list_attachments {
316            descendants = Self::omit_attachments(&mut tree, descendants)?;
317        }
318
319        tree.decrypt_all(
320            &self.keychain,
321            descendants.into_iter().chain(iter::once(*id)),
322            &db.pub_key_lookup,
323            true,
324        )
325    }
326
327    #[instrument(level = "debug", skip(self), err(Debug))]
328    pub async fn get_file_by_id(&self, id: Uuid) -> LbResult<File> {
329        let tx = self.ro_tx().await;
330        let db = tx.db();
331
332        let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
333
334        if tree.calculate_deleted(&id)? {
335            return Err(LbErrKind::FileNonexistent.into());
336        }
337        if tree.access_mode(Owner(self.keychain.get_pk()?), &id)? < Some(UserAccessMode::Read) {
338            return Err(LbErrKind::FileNonexistent.into());
339        }
340
341        let file = tree.decrypt(&self.keychain, &id, &db.pub_key_lookup)?;
342
343        Ok(file)
344    }
345
346    #[instrument(level = "debug", skip(self), err(Debug))]
347    pub async fn get_file_link_url(&self, id: Uuid) -> LbResult<String> {
348        let tx = self.ro_tx().await;
349        let db = tx.db();
350
351        let tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
352
353        // Ensure file exists
354        let id = tree.find(&id)?.id();
355
356        let account = self.get_account()?;
357        let link_url = match account.api_url.as_str() {
358            // Use a more user-friendly link for prod API - both route to the same place
359            "https://api.prod.lockbook.net" => "https://app.lockbook.net",
360            other => other,
361        };
362
363        Ok(format!("{}/open/{}", link_url.trim_end_matches('/'), id))
364    }
365
366    /// `ids` without attachments folders and their contents, for a listing on a client whose
367    /// config doesn't list them.
368    pub(crate) fn omit_attachments<T, Ids>(tree: &mut LazyTree<T>, ids: Ids) -> LbResult<Ids>
369    where
370        T: TreeLike<F = SignedMeta>,
371        Ids: IntoIterator<Item = Uuid> + FromIterator<Uuid>,
372    {
373        let mut kept = Vec::new();
374        for id in ids {
375            if !tree.in_attachments(&id)? {
376                kept.push(id);
377            }
378        }
379        Ok(kept.into_iter().collect())
380    }
381
382    pub async fn local_changes(&self) -> Vec<Uuid> {
383        let tx = self.ro_tx().await;
384        let db = tx.db();
385        db.local_metadata
386            .iter()
387            .map(|(key, _)| key)
388            .copied()
389            .collect()
390    }
391}