-
Notifications
You must be signed in to change notification settings - Fork 209
Expand file tree
/
Copy pathdata.rs
More file actions
296 lines (259 loc) · 7 KB
/
Copy pathdata.rs
File metadata and controls
296 lines (259 loc) · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use std::{sync::Arc, time::Duration};
use futures::StreamExt;
use ruma::{Mxc, OwnedMxcUri, OwnedUserId, UserId, http_headers::ContentDisposition};
use tuwunel_core::{
Err, Result, debug, debug_info, err,
utils::{ReadyExt, str_from_bytes, stream::TryIgnore, string_from_bytes},
};
use tuwunel_database::{Database, Interfix, Map, serialize_key};
use super::{preview::UrlPreviewData, thumbnail::Dim};
pub(crate) struct Data {
mediaid_file: Arc<Map>,
mediaid_user: Arc<Map>,
url_previews: Arc<Map>,
}
#[derive(Debug)]
pub(super) struct Metadata {
pub(super) content_disposition: Option<ContentDisposition>,
pub(super) content_type: Option<String>,
pub(super) key: Vec<u8>,
}
impl Data {
pub(super) fn new(db: &Arc<Database>) -> Self {
Self {
mediaid_file: db["mediaid_file"].clone(),
mediaid_user: db["mediaid_user"].clone(),
url_previews: db["url_previews"].clone(),
}
}
pub(super) fn create_file_metadata(
&self,
mxc: &Mxc<'_>,
user: Option<&UserId>,
dim: &Dim,
content_disposition: Option<&ContentDisposition>,
content_type: Option<&str>,
) -> Result<Vec<u8>> {
let dim: &[u32] = &[dim.width, dim.height];
let key = (mxc, dim, content_disposition, content_type);
let key = serialize_key(key)?;
self.mediaid_file.insert(&key, []);
if let Some(user) = user {
let key = (mxc, user);
self.mediaid_user.put_raw(key, user);
}
Ok(key.to_vec())
}
pub(super) async fn delete_file_mxc(&self, mxc: &Mxc<'_>) {
debug!("MXC URI: {mxc}");
let prefix = (mxc, Interfix);
self.mediaid_file
.keys_prefix_raw(&prefix)
.ignore_err()
.ready_for_each(|key| self.mediaid_file.remove(key))
.await;
self.mediaid_user
.stream_prefix_raw(&prefix)
.ignore_err()
.ready_for_each(|(key, val)| {
debug_assert!(
key.starts_with(mxc.to_string().as_bytes()),
"key should start with the mxc"
);
let user = str_from_bytes(val).unwrap_or_default();
debug_info!("Deleting key {key:?} which was uploaded by user {user}");
self.mediaid_user.remove(key);
})
.await;
}
/// Searches for all files with the given MXC
pub(super) async fn search_mxc_metadata_prefix(&self, mxc: &Mxc<'_>) -> Result<Vec<Vec<u8>>> {
debug!("MXC URI: {mxc}");
let prefix = (mxc, Interfix);
let keys: Vec<Vec<u8>> = self
.mediaid_file
.keys_prefix_raw(&prefix)
.ignore_err()
.map(<[u8]>::to_vec)
.collect()
.await;
if keys.is_empty() {
return Err!(Database("Failed to find any keys in database for `{mxc}`",));
}
debug!("Got the following keys: {keys:?}");
Ok(keys)
}
pub(super) async fn search_file_metadata(
&self,
mxc: &Mxc<'_>,
dim: &Dim,
) -> Result<Metadata> {
let dim: &[u32] = &[dim.width, dim.height];
let prefix = (mxc, dim, Interfix);
let key = self
.mediaid_file
.keys_prefix_raw(&prefix)
.ignore_err()
.map(ToOwned::to_owned)
.next()
.await
.ok_or_else(|| err!(Request(NotFound("Media not found"))))?;
let mut parts = key.rsplit(|&b| b == 0xFF);
let content_type = parts
.next()
.map(string_from_bytes)
.transpose()
.map_err(|e| err!(Database(error!(?mxc, "Content-type is invalid: {e}"))))?;
let content_disposition = parts
.next()
.map(Some)
.ok_or_else(|| err!(Database(error!(?mxc, "Media ID in db is invalid."))))?
.filter(|bytes| !bytes.is_empty())
.map(string_from_bytes)
.transpose()
.map_err(|e| err!(Database(error!(?mxc, "Content-type is invalid: {e}"))))?
.as_deref()
.map(str::parse)
.transpose()?;
Ok(Metadata { content_disposition, content_type, key })
}
/// Gets all the MXCs associated with a user
pub(super) async fn get_all_user_mxcs(&self, user_id: &UserId) -> Vec<OwnedMxcUri> {
self.mediaid_user
.stream()
.ignore_err()
.ready_filter_map(|(key, user): (&str, &UserId)| {
(user == user_id).then(|| key.into())
})
.collect()
.await
}
pub(super) async fn get_media_owner(&self, mxc: &str) -> Option<OwnedUserId> {
let prefix = (mxc, Interfix);
let mut stream = self
.mediaid_user
.stream_prefix_raw(&prefix)
.ignore_err();
while let Some((_, raw_user)) = stream.next().await {
if let Ok(user) = string_from_bytes(raw_user) {
if let Ok(user_id) = OwnedUserId::try_from(user) {
return Some(user_id);
}
}
}
None
}
/// Gets all the media keys in our database (this includes all the metadata
/// associated with it such as width, height, content-type, etc)
pub(crate) async fn get_all_media_keys(&self) -> Vec<Vec<u8>> {
self.mediaid_file
.raw_keys()
.ignore_err()
.map(<[u8]>::to_vec)
.collect()
.await
}
#[inline]
pub(super) fn remove_url_preview(&self, url: &str) -> Result {
self.url_previews.remove(url.as_bytes());
Ok(())
}
pub(super) fn set_url_preview(
&self,
url: &str,
data: &UrlPreviewData,
timestamp: Duration,
) -> Result {
let mut value = Vec::<u8>::new();
value.extend_from_slice(×tamp.as_secs().to_be_bytes());
value.push(0xFF);
value.extend_from_slice(
data.title
.as_ref()
.map(String::as_bytes)
.unwrap_or_default(),
);
value.push(0xFF);
value.extend_from_slice(
data.description
.as_ref()
.map(String::as_bytes)
.unwrap_or_default(),
);
value.push(0xFF);
value.extend_from_slice(
data.image
.as_ref()
.map(String::as_bytes)
.unwrap_or_default(),
);
value.push(0xFF);
value.extend_from_slice(&data.image_size.unwrap_or(0).to_be_bytes());
value.push(0xFF);
value.extend_from_slice(&data.image_width.unwrap_or(0).to_be_bytes());
value.push(0xFF);
value.extend_from_slice(&data.image_height.unwrap_or(0).to_be_bytes());
self.url_previews.insert(url.as_bytes(), &value);
Ok(())
}
pub(super) async fn get_url_preview(&self, url: &str) -> Result<UrlPreviewData> {
let values = self.url_previews.get(url).await?;
let mut values = values.split(|&b| b == 0xFF);
let _ts = values.next();
/* if we ever decide to use timestamp, this is here.
match values.next().map(|b| u64::from_be_bytes(b.try_into().expect("valid BE array"))) {
Some(0) => None,
x => x,
};*/
let title = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
| Some(s) if s.is_empty() => None,
| x => x,
};
let description = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
| Some(s) if s.is_empty() => None,
| x => x,
};
let image = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
| Some(s) if s.is_empty() => None,
| x => x,
};
let image_size = match values
.next()
.map(|b| usize::from_be_bytes(b.try_into().unwrap_or_default()))
{
| Some(0) => None,
| x => x,
};
let image_width = match values
.next()
.map(|b| u32::from_be_bytes(b.try_into().unwrap_or_default()))
{
| Some(0) => None,
| x => x,
};
let image_height = match values
.next()
.map(|b| u32::from_be_bytes(b.try_into().unwrap_or_default()))
{
| Some(0) => None,
| x => x,
};
Ok(UrlPreviewData {
title,
description,
image,
image_size,
image_width,
image_height,
})
}
}