1use crate::Lb;
2use crate::io::docs::LocalDocuments;
3use crate::io::server::Server;
4use crate::model::api::GetPublicKeyRequest;
5use crate::model::errors::{LbErr, LbErrKind, LbResult};
6use crate::model::file::{File, ShareMode};
7use crate::model::file_like::FileLike;
8use crate::model::file_metadata::Owner;
9use crate::model::tree_like::TreeLike;
10use crate::service::events::Actor;
11use libsecp256k1::PublicKey;
12use serde::{Deserialize, Serialize};
13use std::collections::{HashMap, HashSet};
14use uuid::Uuid;
15
16#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
19pub struct SharingContact {
20 pub username: String,
21 pub outgoing_file_count: u64,
22 pub incoming_file_count: u64,
23 pub total_file_count: u64,
25}
26
27impl<S: Server, D: LocalDocuments> Lb<S, D> {
28 #[instrument(level = "debug", skip(self))]
32 pub async fn get_sharing_contacts(&self) -> LbResult<Vec<SharingContact>> {
33 let me = self.keychain.get_pk()?;
34 let tx = self.ro_tx().await;
35 let db = tx.db();
36 let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
37 let mut counts: HashMap<Owner, (u64, u64, u64)> = HashMap::new();
38 let root = db.root.as_ref().ok_or(LbErrKind::RootNonexistent)?;
39 let mut document_ids = tree.descendants_using_links(root)?;
42 document_ids.extend(tree.non_deleted_pending_files(&self.keychain)?);
43 for id in document_ids {
44 if !tree.find(&id)?.is_document() {
45 continue;
46 }
47 let mut outgoing = HashSet::new();
48 let mut incoming = HashSet::new();
49 let mut visited = HashSet::new();
50 let mut current = id;
51 let mut deleted = false;
52 while visited.insert(current) {
53 let Some(file) = tree.maybe_find(¤t) else { break };
54 if file.explicitly_deleted() {
55 deleted = true;
56 break;
57 }
58 for access in file.user_access_keys() {
59 if access.deleted || access.encrypted_by == access.encrypted_for {
60 continue;
61 }
62 if access.encrypted_by == me {
63 outgoing.insert(Owner(access.encrypted_for));
64 } else if access.encrypted_for == me {
65 incoming.insert(Owner(access.encrypted_by));
66 }
67 }
68 if file.is_root() {
69 break;
70 }
71 current = *file.parent();
72 }
73 if deleted {
74 continue;
75 }
76 for user in outgoing.union(&incoming) {
77 let count = counts.entry(*user).or_default();
78 count.0 += u64::from(outgoing.contains(user));
79 count.1 += u64::from(incoming.contains(user));
80 count.2 += 1;
81 }
82 }
83 let mut contacts: Vec<_> = counts
84 .into_iter()
85 .filter_map(|(owner, (outgoing, incoming, total))| {
86 let username = db.pub_key_lookup.get(&owner)?.clone();
87 let trimmed = username.trim();
88 if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("<unknown>") {
89 return None;
90 }
91 Some(SharingContact {
92 username,
93 outgoing_file_count: outgoing,
94 incoming_file_count: incoming,
95 total_file_count: total,
96 })
97 })
98 .collect();
99 contacts.sort_by(|a, b| {
100 b.total_file_count
101 .cmp(&a.total_file_count)
102 .then_with(|| a.username.cmp(&b.username))
103 });
104 Ok(contacts)
105 }
106
107 #[instrument(level = "debug", skip(self))]
109 pub async fn share_file(&self, id: Uuid, username: &str, mode: ShareMode) -> LbResult<()> {
110 let account = self.get_account()?;
111 let username = username.to_lowercase();
112
113 let sharee = Owner(
114 self.client
115 .get_public_key(account, GetPublicKeyRequest { username: username.clone() })
116 .await
117 .map_err(LbErr::from)?
118 .key,
119 );
120
121 let mut tx = self.begin_tx().await;
122 let db = tx.db();
123
124 let mut tree = (&db.base_metadata)
125 .to_staged(&mut db.local_metadata)
126 .to_lazy();
127 db.pub_key_lookup.insert(sharee, username)?;
128
129 tree.add_share(id, sharee, mode, &self.keychain)?;
130 let me = Owner(self.keychain.get_pk()?);
131 if self.attachments_folders && tree.wants_attachments(&id, me)? {
132 tree.create_attachments(self.entropy.id(), self.entropy.key(), &id, &self.keychain)?;
133 }
134
135 tx.end();
136
137 self.events.meta_changed(Actor::User(None));
138
139 Ok(())
140 }
141
142 #[instrument(level = "debug", skip(self))]
143 pub async fn unshare_file(&self, id: Uuid, username: &str) -> LbResult<()> {
144 let sharee = {
145 let tx = self.ro_tx().await;
146 tx.db()
147 .pub_key_lookup
148 .iter()
149 .find_map(|(owner, name)| {
150 (name != "<unknown>" && name.eq_ignore_ascii_case(username)).then_some(owner.0)
151 })
152 .ok_or(LbErrKind::ShareNonexistent)?
153 };
154
155 self.delete_share(&id, Some(sharee)).await
156 }
157
158 #[instrument(level = "debug", skip(self))]
162 pub async fn get_pending_shares(&self) -> LbResult<Vec<File>> {
163 let tx = self.ro_tx().await;
164 let db = tx.db();
165
166 let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
167 let mut pending_roots = tree.pending_roots(&self.keychain)?;
168 if !self.config.list_attachments {
169 pending_roots = Self::omit_attachments(&mut tree, pending_roots)?;
170 }
171
172 tree.decrypt_all(&self.keychain, pending_roots.into_iter(), &db.pub_key_lookup, false)
173 }
174
175 #[instrument(level = "debug", skip(self))]
178 pub async fn get_pending_share_files(&self) -> LbResult<Vec<File>> {
179 let tx = self.ro_tx().await;
180 let db = tx.db();
181
182 let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
183 let mut pending_files = tree.non_deleted_pending_files(&self.keychain)?;
184 if !self.config.list_attachments {
185 pending_files = Self::omit_attachments(&mut tree, pending_files)?;
186 }
187
188 tree.decrypt_all(&self.keychain, pending_files.into_iter(), &db.pub_key_lookup, false)
189 }
190
191 #[instrument(level = "debug", skip(self))]
192 async fn delete_share(
193 &self, id: &Uuid, maybe_encrypted_for: Option<PublicKey>,
194 ) -> LbResult<()> {
195 let mut tx = self.begin_tx().await;
196 let db = tx.db();
197
198 let mut tree = (&db.base_metadata)
199 .to_staged(&mut db.local_metadata)
200 .to_lazy();
201
202 tree.delete_share(id, maybe_encrypted_for, &self.keychain)?;
203
204 tx.end();
205 self.events.meta_changed(Actor::User(None));
206
207 Ok(())
208 }
209
210 #[instrument(level = "debug", skip(self))]
211 pub async fn known_usernames(&self) -> LbResult<Vec<String>> {
212 let db = self.ro_tx().await;
213 let db = db.db();
214
215 Ok(db
216 .pub_key_lookup
217 .iter()
218 .map(|(_, value)| value)
219 .cloned()
220 .collect())
221 }
222
223 #[instrument(level = "debug", skip(self))]
229 pub async fn username_exists(&self, username: &str) -> LbResult<bool> {
230 use crate::DEFAULT_API_LOCATION;
231 use crate::model::account::Account;
232 use crate::model::errors::LbErrKind;
233
234 let username = username.trim().to_lowercase();
235 if username.is_empty() {
236 return Ok(false);
237 }
238 if let Ok(known) = self.known_usernames().await {
240 if known.iter().any(|u| u.eq_ignore_ascii_case(&username)) {
241 return Ok(true);
242 }
243 }
244
245 let owned;
247 let account = match self.get_account() {
248 Ok(a) => a,
249 Err(_) => {
250 let api =
251 std::env::var("API_URL").unwrap_or_else(|_| DEFAULT_API_LOCATION.to_string());
252 owned = Account::new(String::new(), api);
253 &owned
254 }
255 };
256
257 match self
258 .client
259 .get_public_key(account, GetPublicKeyRequest { username })
260 .await
261 {
262 Ok(_) => Ok(true),
263 Err(e) => {
264 let err = LbErr::from(e);
265 match err.kind {
266 LbErrKind::AccountNonexistent | LbErrKind::UsernameNotFound => Ok(false),
268 _ => Err(err),
269 }
270 }
271 }
272 }
273
274 #[instrument(level = "debug", skip(self))]
275 pub async fn reject_share(&self, id: &Uuid) -> Result<(), LbErr> {
276 let pk = self.keychain.get_pk()?;
277 self.delete_share(id, Some(pk)).await
278 }
279}