use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard};
#[derive(Clone)]
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
enum Source {
Plain(PathBuf),
Sealed { path: PathBuf, key: String, nonce: String },
}
#[derive(Default)]
struct Map(Mutex<HashMap<[u8; 32], (Source, String)>>);
struct PendingKey;
fn map() -> Arc<Map> {
crate::db::current_session().scoped::<PendingKey, Map>()
}
fn lock(map: &Map) -> MutexGuard<'_, HashMap<[u8; 32], (Source, String)>> {
map.0.lock().unwrap_or_else(|e| e.into_inner())
}
pub(crate) fn attach(session: &Arc<crate::db::Session>) {
let _ = session.scoped::<PendingKey, Map>();
}
pub fn plain(hash: [u8; 32], path: PathBuf, mime: &str) {
lock(&map()).insert(hash, (Source::Plain(path), mime.to_string()));
}
pub fn sealed(hash: [u8; 32], path: PathBuf, key: &str, nonce: &str, mime: &str) {
lock(&map()).insert(hash, (Source::Sealed { path, key: key.to_string(), nonce: nonce.to_string() }, mime.to_string()));
}
pub fn forget(hash: &[u8; 32]) {
lock(&map()).remove(hash);
}
#[cfg(not(target_arch = "wasm32"))]
pub fn release_path(path: &std::path::Path) {
let pending = map();
let released: Vec<([u8; 32], String)> = {
let mut map = lock(&pending);
let hit: Vec<_> = map.iter()
.filter(|(_, (source, _))| matches!(source, Source::Plain(p) if p == path))
.map(|(hash, (_, mime))| (*hash, mime.clone()))
.collect();
for (hash, _) in &hit {
map.remove(hash);
}
hit
};
let ram = super::ram::cache();
let unheld: Vec<_> = released.into_iter().filter(|(hash, _)| !ram.contains(hash) && !super::store::holds(hash)).collect();
let fits = std::fs::metadata(path).is_ok_and(|m| ram.admits(m.len()));
if unheld.is_empty() || !fits {
return;
}
let Ok(bytes) = std::fs::read(path) else { return };
for (hash, mime) in unheld {
let _ = ram.insert(hash, bytes.clone(), &mime);
}
}
pub fn holds(hash: &[u8; 32]) -> bool {
lock(&map()).contains_key(hash)
}
pub fn plain_path(hash: &[u8; 32]) -> Option<PathBuf> {
match lock(&map()).get(hash) {
Some((Source::Plain(path), _)) if path.is_file() => Some(path.clone()),
_ => None,
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn open(hash: &[u8; 32]) -> Option<Arc<dyn super::MediaSource>> {
let (source, mime) = lock(&map()).get(hash)?.clone();
match source {
Source::Plain(path) => {
let file = std::fs::File::open(&path).ok()?;
let len = file.metadata().ok()?.len();
Some(Arc::new(PlainFile { file, len, mime }))
}
Source::Sealed { path, key, nonce } => {
super::store::StoredGcm::sealed(&path, &key, &nonce, &mime).map(|s| Arc::new(s) as Arc<dyn super::MediaSource>)
}
}
}
#[cfg(target_arch = "wasm32")]
pub fn open(_hash: &[u8; 32]) -> Option<Arc<dyn super::MediaSource>> {
None
}
#[cfg(not(target_arch = "wasm32"))]
struct PlainFile {
file: std::fs::File,
len: u64,
mime: String,
}
#[cfg(not(target_arch = "wasm32"))]
impl super::MediaSource for PlainFile {
fn len(&self) -> u64 {
self.len
}
fn mime(&self) -> &str {
&self.mime
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize> {
if offset >= self.len {
return Ok(0);
}
let n = buf.len().min(usize::try_from(self.len - offset).unwrap_or(usize::MAX));
super::store::read_exact_at(&self.file, &mut buf[..n], offset)?;
Ok(n)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_send_shows_its_own_file_then_its_sealed_copy() {
let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("photo.png");
std::fs::write(&file, b"the sender's own bytes").unwrap();
let hash = [0x71u8; 32];
plain(hash, file.clone(), "image/png");
assert!(holds(&hash) && crate::media::resident(&hash));
assert_eq!(plain_path(&hash), Some(file.clone()));
let src = open(&hash).unwrap();
assert_eq!(crate::media::read_all(&*src).unwrap(), b"the sender's own bytes");
let params = crate::crypto::generate_encryption_params();
let enc = dir.path().join("photo.enc");
std::fs::write(&enc, crate::crypto::encrypt_data(b"the sender's own bytes", ¶ms).unwrap()).unwrap();
sealed(hash, enc, ¶ms.key, ¶ms.nonce, "image/png");
assert_eq!(plain_path(&hash), None);
assert_eq!(crate::media::read_all(&*open(&hash).unwrap()).unwrap(), b"the sender's own bytes");
forget(&hash);
assert!(!holds(&hash) && open(&hash).is_none());
}
#[test]
fn a_file_going_away_hands_its_bubbles_to_memory() {
let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let dir = tempfile::tempdir().unwrap();
let (copy, other, enc) = (dir.path().join("copy.mp3"), dir.path().join("other.mp3"), dir.path().join("x.enc"));
std::fs::write(©, b"the sender's picked bytes").unwrap();
let (a, b, c, d) = ([0x81u8; 32], [0x82u8; 32], [0x83u8; 32], [0x84u8; 32]);
plain(a, copy.clone(), "audio/mpeg");
plain(b, copy.clone(), "audio/mpeg");
plain(c, other.clone(), "audio/mpeg");
sealed(d, enc, "k", "n", "audio/mpeg");
release_path(©);
std::fs::remove_file(©).unwrap();
assert!(!holds(&a) && !holds(&b), "both bubbles on the copy let go of it");
for hash in [a, b] {
assert!(crate::media::resident(&hash), "and still play, from memory");
assert_eq!(crate::media::read_all(&*crate::media::open(&hash).unwrap()).unwrap(), b"the sender's picked bytes");
crate::media::ram::cache().remove(&hash);
}
assert!(holds(&c) && holds(&d), "another file and a sealed copy stay");
forget(&c);
forget(&d);
}
}