1#[cfg(not(target_arch = "wasm32"))]
5pub mod import;
6pub mod pending;
7pub mod ram;
8pub mod range;
9pub mod store;
10
11use std::io::{Read, Seek, SeekFrom};
12use std::sync::Arc;
13
14pub trait MediaSource: Send + Sync {
16 fn len(&self) -> u64;
17 fn is_empty(&self) -> bool {
18 self.len() == 0
19 }
20 fn mime(&self) -> &str;
21 fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize>;
23}
24
25pub fn keep_media() -> bool {
27 crate::db::get_sql_setting("keep_media".to_string()).ok().flatten().as_deref() == Some("true")
28}
29
30pub fn keep_unencrypted() -> bool {
32 keep_media() && crate::db::get_sql_setting("keep_unencrypted".to_string()).ok().flatten().as_deref() == Some("true")
33}
34
35pub fn url_key(kind: &str, url: &str) -> [u8; 32] {
39 let mut key = crate::crypto::sha256::digest(format!("vector-url-media\n{kind}\n{url}").as_bytes());
40 key[0] ^= 0x80;
41 key
42}
43
44pub fn previewable(extension: &str) -> bool {
46 const IMAGES: [&str; 10] = ["png", "jpeg", "jpg", "gif", "webp", "svg", "bmp", "tiff", "tif", "ico"];
47 const AUDIO: [&str; 6] = ["wav", "mp3", "flac", "aac", "m4a", "ogg"];
48 const VIDEO: [&str; 3] = ["mp4", "webm", "mov"];
49 const MODELS: [&str; 5] = ["glb", "gltf", "stl", "obj", "fbx"];
50 let video = !cfg!(all(target_os = "linux", not(target_arch = "wasm32"))) && VIDEO.contains(&extension);
52 IMAGES.contains(&extension) || AUDIO.contains(&extension) || MODELS.contains(&extension) || video
53}
54
55pub fn open(hash: &[u8; 32]) -> Option<Arc<dyn MediaSource>> {
57 match ram::cache().get(hash) {
58 Some(entry) => Some(entry as Arc<dyn MediaSource>),
59 None => store::open(hash).or_else(|| pending::open(hash)).or_else(|| kept_plain(hash)),
60 }
61}
62
63#[cfg(not(target_arch = "wasm32"))]
65fn kept_plain(hash: &[u8; 32]) -> Option<Arc<dyn MediaSource>> {
66 let roots: Vec<std::path::PathBuf> = crate::db::download_roots().iter().filter_map(|r| std::fs::canonicalize(r).ok()).collect();
67 let paths = crate::db::attachments::downloaded_paths_by_hash(&crate::simd::hex::bytes_to_hex_32(hash)).ok()?;
68 paths.iter().find_map(|path| {
69 let real = std::fs::canonicalize(path).ok().filter(|real| roots.iter().any(|root| real.starts_with(root)))?;
70 let ext = real.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase();
71 crate::vcache::open(&real, crate::crypto::mime_from_extension(&ext))
72 })
73}
74
75#[cfg(target_arch = "wasm32")]
76fn kept_plain(_: &[u8; 32]) -> Option<Arc<dyn MediaSource>> {
77 None
78}
79
80pub async fn held_bytes(hash: &[u8; 32]) -> Option<(Vec<u8>, String)> {
83 if let Some(src) = open(hash) {
84 return read_all(&*src).ok().map(|bytes| (bytes, src.mime().to_string()));
85 }
86 #[cfg(target_arch = "wasm32")]
87 if let Some((plain, mime)) = store::read_plain(hash).await {
88 if !store::holds(hash) {
90 return None;
91 }
92 let _ = ram::cache().insert(*hash, plain.clone(), &mime);
93 return Some((plain, mime));
94 }
95 None
96}
97
98pub async fn read(path_or_ref: &str) -> Result<Vec<u8>, String> {
100 match MediaRef::parse(path_or_ref).ok_or("Unknown file")? {
101 MediaRef::File(path) => crate::files::read(std::path::Path::new(&path)).await,
102 MediaRef::Held(hash) => held_bytes(&hash).await.map(|(bytes, _)| bytes).ok_or_else(|| "This file isn't on this device any more".to_string()),
103 }
104}
105
106pub fn read_all(src: &dyn MediaSource) -> std::io::Result<Vec<u8>> {
108 let mut bytes = vec![0u8; usize::try_from(src.len()).map_err(|_| std::io::ErrorKind::OutOfMemory)?];
109 let mut filled = 0;
110 while filled < bytes.len() {
111 match src.read_at(filled as u64, &mut bytes[filled..])? {
112 0 => break,
113 n => filled += n,
114 }
115 }
116 bytes.truncate(filled);
117 Ok(bytes)
118}
119
120pub fn resident(hash: &[u8; 32]) -> bool {
122 ram::cache().contains(hash) || store::holds(hash) || pending::holds(hash)
123}
124
125pub fn openable(hash: &[u8; 32]) -> bool {
127 resident(hash) || open(hash).is_some()
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum MediaRef {
133 Held([u8; 32]),
134 File(String),
135}
136
137impl MediaRef {
138 pub const SCHEME: &'static str = "vmedia:";
139
140 pub fn parse(s: &str) -> Option<Self> {
142 match s.strip_prefix(Self::SCHEME) {
143 Some(hex) => crate::simd::hex::hex_to_bytes_32_checked(hex).map(MediaRef::Held),
144 None => Some(MediaRef::File(s.to_string())),
145 }
146 }
147
148 pub fn held(hash: &[u8; 32]) -> String {
149 format!("{}{}", Self::SCHEME, crate::simd::hex::bytes_to_hex_32(hash))
150 }
151}
152
153pub struct Reader {
155 src: Arc<dyn MediaSource>,
156 pos: u64,
157}
158
159pub fn reader(src: Arc<dyn MediaSource>) -> Reader {
160 Reader { src, pos: 0 }
161}
162
163impl Reader {
164 pub fn len(&self) -> u64 {
165 self.src.len()
166 }
167
168 pub fn is_empty(&self) -> bool {
169 self.src.is_empty()
170 }
171}
172
173impl Read for Reader {
174 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
175 let n = self.src.read_at(self.pos, buf)?;
176 self.pos += n as u64;
177 Ok(n)
178 }
179}
180
181impl Seek for Reader {
182 fn seek(&mut self, to: SeekFrom) -> std::io::Result<u64> {
183 let next = match to {
184 SeekFrom::Start(n) => i128::from(n),
185 SeekFrom::End(d) => i128::from(self.src.len()) + i128::from(d),
186 SeekFrom::Current(d) => i128::from(self.pos) + i128::from(d),
187 };
188 if next < 0 {
189 return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek before the start"));
190 }
191 self.pos = u64::try_from(next).unwrap_or(u64::MAX);
192 Ok(self.pos)
193 }
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 #[test]
201 fn no_file_can_claim_a_links_memory_slot() {
202 let url = "https://example.com/a.png";
203 let derivation = format!("vector-url-media\ninline-image\n{url}");
204 assert_ne!(url_key("inline-image", url), crate::crypto::sha256::digest(derivation.as_bytes()), "a file of the derivation's bytes hashes elsewhere");
205 assert_ne!(url_key("inline-image", url), url_key("embed-poster", url));
206 }
207
208 #[test]
209 fn a_ref_is_a_held_hash_or_a_file() {
210 let hash = [0xabu8; 32];
211 let held = MediaRef::held(&hash);
212 assert_eq!(MediaRef::parse(&held), Some(MediaRef::Held(hash)));
213 assert_eq!(MediaRef::parse("/dl/photo.jpg"), Some(MediaRef::File("/dl/photo.jpg".into())));
214 assert_eq!(MediaRef::parse("vmedia:nothex"), None);
215 assert_eq!(MediaRef::parse("vmedia:"), None);
216 }
217
218 #[test]
219 fn the_reader_reads_and_seeks_like_a_file() {
220 let ram = ram::MediaRam::default();
221 let data: Vec<u8> = (0..=255u8).collect();
222 let mut r = reader(ram.insert([9; 32], data.clone(), "audio/wav").unwrap());
223 let mut head = [0u8; 4];
224 r.read_exact(&mut head).unwrap();
225 assert_eq!(head, [0, 1, 2, 3]);
226 assert_eq!(r.seek(SeekFrom::End(-2)).unwrap(), 254);
227 let mut rest = Vec::new();
228 r.read_to_end(&mut rest).unwrap();
229 assert_eq!(rest, vec![254, 255]);
230 assert_eq!(r.seek(SeekFrom::Current(-100)).unwrap(), 156);
231 assert!(r.seek(SeekFrom::Current(-1000)).is_err());
232 assert_eq!(r.seek(SeekFrom::Start(9999)).unwrap(), 9999);
233 assert_eq!(r.read(&mut head).unwrap(), 0, "past the end reads nothing");
234 }
235}