Skip to main content

vector_core/media/
mod.rs

1//! Media Vector shows without writing it down: decrypted bytes held in memory per account
2//! (`ram`), read through one interface whatever holds them.
3
4#[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
14/// Bytes a media view reads, wherever they live.
15pub 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    /// Fill `buf` from `offset`. Fewer bytes only at the end, none past it.
22    fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize>;
23}
24
25/// "Keep Files on This Device": every file received is kept in the store too, not only held.
26pub fn keep_media() -> bool {
27    crate::db::get_sql_setting("keep_media".to_string()).ok().flatten().as_deref() == Some("true")
28}
29
30/// "Keep Unencrypted": what is kept is a plain file in the public folder, not sealed in the store.
31pub fn keep_unencrypted() -> bool {
32    keep_media() && crate::db::get_sql_setting("keep_unencrypted".to_string()).ok().flatten().as_deref() == Some("true")
33}
34
35/// The memory key of media fetched by URL rather than by content hash: `kind` keeps one kind's
36/// keys apart from another's. The digest is masked so that no file's content hash can be it: a
37/// file of exactly the derivation's bytes would otherwise claim the link's slot.
38pub 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
44/// Kinds a chat bubble draws itself: these load for viewing without being kept.
45pub 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    // Linux's webview plays no inline video.
51    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
55/// What holds `hash` for this account right now, memory first, if anything.
56pub 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/// A file kept unencrypted in one of Vector's folders, for a hash memory has let go of.
64#[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
80/// The plaintext and type of media this account holds, from memory or the store. A kept file
81/// read on the web is held in memory after, since its store can't be read a range at a time.
82pub 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        // Deleted while it was read: it doesn't come back into memory.
89        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
98/// The bytes behind a path or a `vmedia:` ref, for readers that want the whole file.
99pub 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
106/// Every byte of `src`, for a reader that wants the whole file.
107pub 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
120/// Whether this account can show `hash` without fetching it.
121pub fn resident(hash: &[u8; 32]) -> bool {
122    ram::cache().contains(hash) || store::holds(hash) || pending::holds(hash)
123}
124
125/// Whether `hash` is held, or [`open`] would find it as a plain copy in a download folder.
126pub fn openable(hash: &[u8; 32]) -> bool {
127    resident(hash) || open(hash).is_some()
128}
129
130/// How a command names an attachment's bytes: a hash this account holds, or a file.
131#[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    /// None for a `vmedia:` ref that names no hash.
141    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
153/// A cursor over a source, for readers that want `Read + Seek`.
154pub 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}