1use std::collections::HashMap;
13
14use crate::types::Attachment;
15
16const SELECT_COLS: &str = "event_id, att_index, hash, key, nonce, extension, name, url, \
17 path, size, img_meta, downloaded, webxdc_topic, group_id, original_hash, fallback_urls, verified";
18
19fn row_to_attachment(row: &rusqlite::Row, at_rest: &mut crate::crypto::AtRestOpener) -> rusqlite::Result<(String, Attachment)> {
22 let event_id: String = row.get(0)?;
23 let id: String = row.get(2)?;
24 let resident = crate::simd::hex::hex_to_bytes_32_checked(&id).is_some_and(|h| crate::media::resident(&h));
26 let img_meta_json: Option<String> = row.get(10)?;
27 let mut open = |i: usize| -> rusqlite::Result<String> { Ok(at_rest.open_or_keep(row.get(i)?)) };
28 let att = Attachment {
29 id,
30 key: open(3)?,
31 nonce: open(4)?,
32 extension: row.get(5)?,
33 name: open(6)?,
34 url: open(7)?,
35 path: row.get(8)?,
36 size: row.get::<_, i64>(9)? as u64,
37 img_meta: img_meta_json.and_then(|j| serde_json::from_str(&at_rest.open_or_keep(j)).ok()),
38 downloading: false,
39 downloaded: row.get::<_, i64>(11)? != 0,
40 webxdc_topic: row.get(12)?,
41 group_id: row.get(13)?,
42 original_hash: row.get(14)?,
43 fallback_urls: at_rest
44 .open_or_keep(row.get::<_, String>(15)?)
45 .split_whitespace()
46 .map(|s| s.to_string())
47 .collect(),
48 verified: row.get::<_, i64>(16)? != 0,
49 resident,
50 };
51 Ok((event_id, att))
52}
53
54pub fn insert_attachment_rows(
65 conn: &rusqlite::Connection,
66 event_id: &str,
67 attachments: &[Attachment],
68 seal: &mut crate::crypto::AtRestSealer,
69) -> Result<(), String> {
70 if attachments.is_empty() {
71 return Ok(());
72 }
73 let mut stmt = conn.prepare_cached(
76 "INSERT INTO attachments (event_id, att_index, hash, key, nonce, extension, name, url, \
77 path, size, img_meta, downloaded, webxdc_topic, group_id, original_hash, fallback_urls, verified) \
78 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17) \
79 ON CONFLICT(event_id, att_index) DO UPDATE SET \
80 key=excluded.key, nonce=excluded.nonce, extension=excluded.extension, \
81 name=excluded.name, url=excluded.url, size=excluded.size, img_meta=excluded.img_meta, \
82 webxdc_topic=excluded.webxdc_topic, group_id=excluded.group_id, \
83 original_hash=excluded.original_hash, \
84 fallback_urls=CASE WHEN excluded.fallback_urls='' THEN fallback_urls ELSE excluded.fallback_urls END, \
85 downloaded=MAX(downloaded, excluded.downloaded), \
86 verified=MAX(verified, excluded.verified), \
87 hash=CASE WHEN excluded.downloaded=1 OR excluded.verified=1 THEN excluded.hash ELSE hash END, \
88 path=CASE WHEN excluded.downloaded=1 THEN excluded.path ELSE path END",
89 ).map_err(|e| format!("prepare insert attachment: {e}"))?;
90 for (i, a) in attachments.iter().enumerate() {
91 let img_meta_json = a.img_meta.as_ref().and_then(|m| serde_json::to_string(m).ok());
92 stmt.execute(
93 rusqlite::params![
94 event_id, i as i64, a.id, seal.seal_set(&a.key)?, seal.seal_set(&a.nonce)?, a.extension,
95 seal.seal_set(&a.name)?, seal.seal_set(&a.url)?, a.path, a.size as i64,
96 img_meta_json.as_deref().map(|j| seal.seal(j)).transpose()?, a.downloaded as i64,
97 a.webxdc_topic, a.group_id, a.original_hash,
98 seal.seal_set(&a.fallback_urls.join(" "))?, a.verified as i64,
99 ],
100 ).map_err(|e| format!("insert attachment: {e}"))?;
101 }
102 Ok(())
103}
104
105pub fn get_attachments_for_events(event_ids: &[String]) -> Result<HashMap<String, Vec<Attachment>>, String> {
108 let mut out: HashMap<String, Vec<Attachment>> = HashMap::new();
109 if event_ids.is_empty() {
110 return Ok(out);
111 }
112 let conn = super::get_db_connection_guard_static()?;
113 let sql = format!(
114 "SELECT {SELECT_COLS} FROM attachments WHERE event_id IN (SELECT value FROM json_each(?1)) ORDER BY event_id, att_index"
115 );
116 let mut stmt = conn.prepare_cached(&sql).map_err(|e| format!("prepare get_attachments: {e}"))?;
117 crate::crypto::open_batch(|at_rest| {
118 let rows = stmt
119 .query_map([super::events::id_list_param(event_ids)], |row| row_to_attachment(row, at_rest))
120 .map_err(|e| format!("query get_attachments: {e}"))?;
121 for r in rows.flatten() {
122 out.entry(r.0).or_default().push(r.1);
123 }
124 Ok(out)
125 })
126}
127
128pub fn get_attachments_for_event(event_id: &str) -> Result<Vec<Attachment>, String> {
130 let map = get_attachments_for_events(std::slice::from_ref(&event_id.to_string()))?;
131 Ok(map.into_values().next().unwrap_or_default())
132}
133
134pub fn find_by_webxdc_topic_in(chat_identifier: &str, topic: &str) -> Result<Option<(String, Attachment)>, String> {
138 let Ok(chat) = super::id_cache::get_chat_id_by_identifier(chat_identifier) else { return Ok(None) };
139 let conn = super::get_db_connection_guard_static()?;
140 let cols = SELECT_COLS.split(", ").map(|c| format!("a.{}", c.trim())).collect::<Vec<_>>().join(", ");
141 let mut stmt = conn
142 .prepare(&format!(
143 "SELECT {cols} FROM attachments a JOIN events e ON e.id = a.event_id \
144 WHERE a.webxdc_topic = ?1 AND e.chat_id = ?2 ORDER BY e.created_at ASC LIMIT 1"
145 ))
146 .map_err(|e| format!("prepare topic lookup: {e}"))?;
147 let mut rows = stmt.query(rusqlite::params![topic, chat]).map_err(|e| format!("topic lookup: {e}"))?;
148 match rows.next().map_err(|e| format!("topic lookup: {e}"))? {
149 Some(row) => crate::crypto::open_batch(|at_rest| row_to_attachment(row, at_rest))
150 .map(Some)
151 .map_err(|e| format!("topic row: {e}")),
152 None => Ok(None),
153 }
154}
155
156pub fn events_with_attachment_hash(hash: &str) -> Result<Vec<String>, String> {
163 let conn = super::get_db_connection_guard_static()?;
164 let mut stmt = conn
165 .prepare(
166 "SELECT a.event_id FROM attachments a JOIN events e ON e.id = a.event_id \
170 WHERE a.hash = ?1 ORDER BY e.created_at DESC, e.received_at DESC, e.rowid DESC",
171 )
172 .map_err(|e| format!("prepare events_with_attachment_hash: {e}"))?;
173 let rows = stmt
174 .query_map(rusqlite::params![hash], |r| r.get::<_, String>(0))
175 .map_err(|e| format!("query events_with_attachment_hash: {e}"))?;
176 Ok(rows.flatten().collect())
177}
178
179pub fn set_attachment_downloaded(event_id: &str, hash: &str, downloaded: bool, path: &str) -> Result<(), String> {
182 let conn = super::get_write_connection_guard_static()?;
183 conn.execute(
184 "UPDATE attachments SET downloaded=?1, path=?2 WHERE event_id=?3 AND hash=?4",
185 rusqlite::params![downloaded as i64, path, event_id, hash],
186 ).map_err(|e| format!("set_attachment_downloaded: {e}"))?;
187 Ok(())
188}
189
190pub fn set_attachment_size(event_id: &str, hash: &str, size: u64) -> Result<(), String> {
192 let conn = super::get_write_connection_guard_static()?;
193 conn.execute(
194 "UPDATE attachments SET size=?1 WHERE event_id=?2 AND hash=?3 AND size=0",
195 rusqlite::params![size as i64, event_id, hash],
196 ).map_err(|e| format!("set_attachment_size: {e}"))?;
197 Ok(())
198}
199
200pub fn backfill_downloaded_by_hash(hash: &str, path: &str, exclude_event_id: &str) -> Result<Vec<String>, String> {
204 let conn = super::get_write_connection_guard_static()?;
205 let affected: Vec<String> = {
206 let mut stmt = conn.prepare(
207 "SELECT DISTINCT event_id FROM attachments WHERE hash=?1 AND event_id!=?2 AND downloaded=0"
208 ).map_err(|e| format!("prepare backfill_by_hash: {e}"))?;
209 let rows = stmt.query_map(rusqlite::params![hash, exclude_event_id], |r| r.get::<_, String>(0))
210 .map_err(|e| format!("query backfill_by_hash: {e}"))?;
211 rows.flatten().collect()
212 };
213 conn.execute(
214 "UPDATE attachments SET downloaded=1, path=?1 WHERE hash=?2 AND event_id!=?3 AND downloaded=0",
215 rusqlite::params![path, hash, exclude_event_id],
216 ).map_err(|e| format!("backfill_by_hash update: {e}"))?;
217 Ok(affected)
218}
219
220pub fn downloaded_attachment_paths() -> Result<Vec<(String, String, String)>, String> {
224 let conn = super::get_db_connection_guard_static()?;
225 let mut stmt = conn.prepare(
226 "SELECT event_id, hash, path FROM attachments WHERE downloaded=1"
227 ).map_err(|e| format!("prepare downloaded_paths: {e}"))?;
228 let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))
229 .map_err(|e| format!("query downloaded_paths: {e}"))?;
230 Ok(rows.flatten().collect())
231}
232
233pub fn clear_kept(hash: &str) -> Result<usize, String> {
235 let conn = super::get_write_connection_guard_static()?;
236 conn.execute("UPDATE attachments SET downloaded=0 WHERE hash=?1 AND downloaded=1 AND path=''", [hash])
237 .map_err(|e| format!("clear kept: {e}"))
238}
239
240pub fn unmarked_downloads() -> Result<Vec<(i64, String, String, u64)>, String> {
242 let conn = super::get_db_connection_guard_static()?;
243 let mut stmt = conn
244 .prepare("SELECT id, hash, path, size FROM attachments WHERE downloaded=0 AND path!=''")
245 .map_err(|e| format!("prepare unmarked_downloads: {e}"))?;
246 let rows = stmt
247 .query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, i64>(3)? as u64)))
248 .map_err(|e| format!("query unmarked_downloads: {e}"))?;
249 Ok(rows.flatten().collect())
250}
251
252pub fn mark_downloaded(id: i64, path: &str) -> Result<bool, String> {
254 let conn = super::get_write_connection_guard_static()?;
255 conn.execute("UPDATE attachments SET downloaded=1 WHERE id=?1 AND downloaded=0 AND path=?2", rusqlite::params![id, path])
256 .map(|n| n == 1)
257 .map_err(|e| format!("mark_downloaded: {e}"))
258}
259
260pub fn downloads_on_disk() -> Result<Vec<(String, String, String)>, String> {
262 let conn = super::get_db_connection_guard_static()?;
263 let mut stmt = conn
264 .prepare("SELECT hash, path, MAX(extension) FROM attachments WHERE downloaded=1 AND path!='' GROUP BY hash, path")
265 .map_err(|e| format!("prepare downloads_on_disk: {e}"))?;
266 let rows = stmt
267 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))
268 .map_err(|e| format!("query downloads_on_disk: {e}"))?;
269 Ok(rows.flatten().collect())
270}
271
272pub fn move_to_store(hash: &str, paths: &[&str]) -> Result<Vec<String>, String> {
275 let conn = super::get_write_connection_guard_static()?;
276 let tx = rusqlite::Transaction::new_unchecked(&conn, rusqlite::TransactionBehavior::Immediate)
278 .map_err(|e| format!("move_to_store: {e}"))?;
279 let held = crate::media::MediaRef::held(&crate::simd::hex::hex_to_bytes_32(hash));
281 let mut events = Vec::new();
282 for path in paths {
283 events.extend(events_at_path(&tx, path)?);
284 tx.execute("UPDATE attachments SET path='' WHERE path=?1 AND hash=?2", [path, hash])
285 .map_err(|e| format!("move_to_store: {e}"))?;
286 tx.execute("UPDATE attachments SET downloaded=0, path='' WHERE path=?1", [path])
287 .map_err(|e| format!("move_to_store: {e}"))?;
288 tx.execute("UPDATE miniapps_history SET attachment_ref=?2 WHERE attachment_ref=?1", [path, held.as_str()])
289 .map_err(|e| format!("move_to_store: {e}"))?;
290 tx.execute("UPDATE miniapps_history SET src_url=?2 WHERE src_url=?1", [path, held.as_str()])
291 .map_err(|e| format!("move_to_store: {e}"))?;
292 }
293 tx.commit().map_err(|e| format!("move_to_store: {e}"))?;
294 events.sort();
295 events.dedup();
296 Ok(events)
297}
298
299pub fn out_of_store(hash: &str, path: &str) -> Result<Vec<String>, String> {
302 let conn = super::get_write_connection_guard_static()?;
303 let tx = rusqlite::Transaction::new_unchecked(&conn, rusqlite::TransactionBehavior::Immediate)
304 .map_err(|e| format!("out_of_store: {e}"))?;
305 let events: Vec<String> = {
306 let mut stmt = tx
307 .prepare("SELECT DISTINCT event_id FROM attachments WHERE hash=?1 AND path='' AND downloaded=1")
308 .map_err(|e| format!("out_of_store: {e}"))?;
309 let rows = stmt.query_map([hash], |r| r.get::<_, String>(0)).map_err(|e| format!("out_of_store: {e}"))?;
310 rows.flatten().collect()
311 };
312 tx.execute("UPDATE attachments SET path=?2 WHERE hash=?1 AND path='' AND downloaded=1", [hash, path])
313 .map_err(|e| format!("out_of_store: {e}"))?;
314 let held = crate::media::MediaRef::held(&crate::simd::hex::hex_to_bytes_32(hash));
315 tx.execute("UPDATE miniapps_history SET attachment_ref=?2 WHERE attachment_ref=?1", [held.as_str(), path])
316 .map_err(|e| format!("out_of_store: {e}"))?;
317 tx.execute("UPDATE miniapps_history SET src_url=?2 WHERE src_url=?1", [held.as_str(), path])
318 .map_err(|e| format!("out_of_store: {e}"))?;
319 tx.commit().map_err(|e| format!("out_of_store: {e}"))?;
320 Ok(events)
321}
322
323pub fn kept_names() -> Result<Vec<([u8; 32], String, String)>, String> {
325 let conn = super::get_db_connection_guard_static()?;
326 let mut stmt = conn
327 .prepare(
328 "SELECT a.hash, a.name, a.extension FROM attachments a JOIN media_store m ON m.hash = a.hash \
329 WHERE a.path='' AND a.downloaded=1 ORDER BY a.hash",
330 )
331 .map_err(|e| format!("kept_names: {e}"))?;
332 crate::crypto::open_batch(|at_rest| {
333 let rows = stmt
334 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))
335 .map_err(|e| format!("kept_names: {e}"))?;
336 let mut out: Vec<([u8; 32], String, String)> = Vec::new();
337 for (hash, name, extension) in rows.flatten() {
338 let Some(hash) = crate::simd::hex::hex_to_bytes_32_checked(&hash) else { continue };
339 let name = at_rest.open_or_keep(name);
340 match out.last_mut() {
341 Some(last) if last.0 == hash => {
342 if last.1.is_empty() {
343 last.1 = name;
344 }
345 }
346 _ => out.push((hash, name, extension)),
347 }
348 }
349 Ok(out)
350 })
351}
352
353pub fn let_go(paths: &[&str]) -> Result<Vec<String>, String> {
355 let conn = super::get_write_connection_guard_static()?;
356 let tx = rusqlite::Transaction::new_unchecked(&conn, rusqlite::TransactionBehavior::Immediate)
357 .map_err(|e| format!("let_go: {e}"))?;
358 let mut events = Vec::new();
359 for path in paths {
360 events.extend(events_at_path(&tx, path)?);
361 tx.execute("UPDATE attachments SET downloaded=0, path='' WHERE path=?1", [path])
362 .map_err(|e| format!("let_go: {e}"))?;
363 }
364 tx.commit().map_err(|e| format!("let_go: {e}"))?;
365 events.sort();
366 events.dedup();
367 Ok(events)
368}
369
370pub fn names_path(path: &str) -> Result<bool, String> {
372 let conn = super::get_db_connection_guard_static()?;
373 conn.query_row(
374 "SELECT EXISTS(SELECT 1 FROM attachments WHERE path=?1)
375 OR EXISTS(SELECT 1 FROM miniapps_history WHERE attachment_ref=?1 OR src_url=?1)",
376 [path],
377 |r| r.get(0),
378 )
379 .map_err(|e| format!("names_path: {e}"))
380}
381
382pub fn keep_at_store(hash: &str, path: &str) -> Result<Vec<String>, String> {
385 let conn = super::get_write_connection_guard_static()?;
386 let events = events_at_path(&conn, path)?;
387 conn.execute("UPDATE attachments SET path='' WHERE path=?1 AND hash=?2", [path, hash])
388 .map_err(|e| format!("keep_at_store: {e}"))?;
389 Ok(events)
390}
391
392pub fn forget_path(hash: &str, path: &str) -> Result<Vec<String>, String> {
394 let conn = super::get_write_connection_guard_static()?;
395 let events = events_at_path(&conn, path)?;
396 conn.execute("UPDATE attachments SET downloaded=0, path='' WHERE path=?1 AND hash=?2", [path, hash])
397 .map_err(|e| format!("forget_path: {e}"))?;
398 Ok(events)
399}
400
401fn events_at_path(conn: &rusqlite::Connection, path: &str) -> Result<Vec<String>, String> {
402 let mut stmt = conn
403 .prepare("SELECT DISTINCT event_id FROM attachments WHERE path=?1")
404 .map_err(|e| format!("prepare events_at_path: {e}"))?;
405 let rows = stmt.query_map([path], |r| r.get::<_, String>(0)).map_err(|e| format!("query events_at_path: {e}"))?;
406 Ok(rows.flatten().collect())
407}
408
409pub fn clear_attachment_download(event_id: &str, hash: &str) -> Result<(), String> {
411 let conn = super::get_write_connection_guard_static()?;
412 conn.execute(
413 "UPDATE attachments SET downloaded=0, path='' WHERE event_id=?1 AND hash=?2",
414 rusqlite::params![event_id, hash],
415 ).map_err(|e| format!("clear_attachment_download: {e}"))?;
416 Ok(())
417}
418
419pub fn rewrite_downloaded_paths(old_prefixes: &[String], new_dir: &std::path::Path) -> Result<Vec<String>, String> {
423 let conn = super::get_write_connection_guard_static()?;
424 let rows: Vec<(i64, String, String)> = {
425 let mut stmt = conn.prepare("SELECT id, event_id, path FROM attachments WHERE downloaded=1 AND path!=''")
426 .map_err(|e| format!("prepare rewrite_paths: {e}"))?;
427 let mapped = stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))
428 .map_err(|e| format!("query rewrite_paths: {e}"))?;
429 mapped.flatten().collect()
430 };
431 let mut affected = Vec::new();
432 for (rowid, event_id, path) in rows {
433 if !old_prefixes.iter().any(|p| path.starts_with(p.as_str())) {
434 continue;
435 }
436 let Some(name) = std::path::Path::new(&path).file_name() else { continue };
437 let new_path = new_dir.join(name);
438 let res = if new_path.exists() {
439 conn.execute("UPDATE attachments SET path=?1 WHERE id=?2",
440 rusqlite::params![new_path.to_string_lossy().to_string(), rowid])
441 } else {
442 conn.execute("UPDATE attachments SET downloaded=0, path='' WHERE id=?1", rusqlite::params![rowid])
443 };
444 if res.is_ok() {
445 affected.push(event_id);
446 }
447 }
448 Ok(affected)
449}
450
451#[derive(Debug, Clone)]
454pub struct ReusableUpload {
455 pub url: String,
456 pub key: String,
457 pub nonce: String,
458 pub size: u64,
459 pub mine: bool,
462}
463
464pub async fn verify_local_copy(att: &crate::types::Attachment) -> Option<String> {
470 let expected = att.id.clone();
471 if crate::simd::hex::hex_to_bytes_32_checked(&expected).is_some_and(|h| crate::media::store::holds(&h)) {
473 return Some(String::new());
474 }
475 let mut candidates: Vec<std::path::PathBuf> = downloaded_paths_by_hash(&expected)
476 .unwrap_or_default()
477 .into_iter()
478 .map(Into::into)
479 .collect();
480 if !att.name.is_empty() {
481 candidates.push(crate::db::get_download_dir().join(&att.name));
482 }
483 let size = att.size;
484 #[cfg(target_arch = "wasm32")]
485 {
486 for p in candidates {
487 let Some(len) = crate::webfiles::size(&p).await else { continue };
488 if size != 0 && len != size && len + 16 != size {
489 continue;
490 }
491 if let Ok(bytes) = crate::webfiles::read(&p).await {
492 if crate::crypto::sha256_hex(&bytes) == expected {
493 return Some(p.to_string_lossy().to_string());
494 }
495 }
496 }
497 None
498 }
499 #[cfg(not(target_arch = "wasm32"))]
500 {
501 candidates.retain(|p| match std::fs::metadata(p) {
502 Ok(m) => size == 0 || m.len() == size || m.len() + 16 == size,
503 Err(_) => false,
504 });
505 if candidates.is_empty() {
506 return None;
507 }
508 crate::rt::spawn_blocking(move || {
509 candidates.into_iter().find_map(|p| {
510 let bytes = std::fs::read(&p).ok()?;
511 (crate::crypto::sha256_hex(&bytes) == expected)
512 .then(|| p.to_string_lossy().to_string())
513 })
514 })
515 .await
516 .ok()
517 .flatten()
518 }
519}
520
521pub async fn verify_message_attachments(msg: &mut crate::types::Message, chat_hint: Option<&str>) {
529 let mut converted: Vec<(String, String)> = Vec::new();
530 for att in &mut msg.attachments {
531 if !att.downloaded {
532 if let Some(path) = verify_local_copy(att).await {
533 att.downloaded = true;
534 att.path = path.clone();
535 converted.push((att.id.clone(), path));
536 }
537 }
538 }
539 if let Some(chat) = chat_hint {
540 if !converted.is_empty() {
541 let mut state = crate::state::STATE.lock().await;
542 for (att_id, path) in converted {
543 state.update_attachment(chat, &msg.id, &att_id, |a| {
544 a.set_downloaded(true);
545 a.set_path(path);
546 });
547 }
548 }
549 }
550}
551
552pub fn downloaded_paths_by_hash(hash: &str) -> Result<Vec<String>, String> {
557 let conn = crate::db::get_db_connection_guard_static()?;
558 let mut stmt = conn
559 .prepare("SELECT DISTINCT path FROM attachments WHERE hash = ?1 AND downloaded = 1 AND path != ''")
560 .map_err(|e| e.to_string())?;
561 let rows = stmt
562 .query_map([hash], |r| r.get::<_, String>(0))
563 .map_err(|e| e.to_string())?
564 .filter_map(|r| r.ok())
565 .collect();
566 Ok(rows)
567}
568
569pub fn find_reusable_by_hash(hash: &str) -> Result<Option<ReusableUpload>, String> {
578 if hash.is_empty() {
579 return Ok(None);
580 }
581 let conn = super::get_db_connection_guard_static()?;
582 let mut stmt = conn
583 .prepare(
584 "SELECT a.url, a.key, a.nonce, a.size, COALESCE(e.mine, 0)
585 FROM attachments a JOIN events e ON e.id = a.event_id
586 WHERE a.hash = ?1 AND a.url <> '' AND a.key <> '' AND a.nonce <> '' AND a.verified = 1
587 ORDER BY COALESCE(e.mine, 0) DESC, a.id DESC LIMIT 1",
588 )
589 .map_err(|e| format!("find_reusable_by_hash prepare: {e}"))?;
590 let row = crate::crypto::open_batch(|at_rest| {
592 let (url, key, nonce, size, mine) = stmt
593 .query_row(rusqlite::params![hash], |r| {
594 Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, i64>(3)?, r.get::<_, i64>(4)?))
595 })
596 .ok()?;
597 Some(ReusableUpload {
598 url: at_rest.open(url).ok()?,
599 key: at_rest.open(key).ok()?,
600 nonce: at_rest.open(nonce).ok()?,
601 size: size as u64,
602 mine: mine != 0,
603 })
604 });
605 Ok(row)
606}
607
608pub fn urls_unreferenced_elsewhere(urls: &[String], excluding_event_id: &str) -> Result<Vec<String>, String> {
615 if urls.is_empty() {
616 return Ok(Vec::new());
617 }
618 let conn = super::get_db_connection_guard_static()?;
619 let mut stmt = conn
620 .prepare("SELECT url, fallback_urls FROM attachments WHERE (url <> '' OR fallback_urls <> '') AND event_id <> ?1")
621 .map_err(|e| format!("urls_unreferenced prepare: {e}"))?;
622 let referenced: std::collections::HashSet<String> = crate::crypto::open_batch(|at_rest| {
624 let mut rows = stmt.query([excluding_event_id]).map_err(|e| format!("urls_unreferenced query: {e}"))?;
625 let mut set = std::collections::HashSet::new();
626 while let Some(row) = rows.next().map_err(|e| format!("urls_unreferenced row: {e}"))? {
627 for i in 0..2 {
628 let field: String = row.get(i).map_err(|e| format!("urls_unreferenced row: {e}"))?;
629 if field.is_empty() {
630 continue;
631 }
632 let opened = at_rest
633 .open(field)
634 .map_err(|_| "An attachment URL could not be opened, so nothing was scrubbed".to_string())?;
635 set.extend(opened.split_whitespace().map(str::to_string));
636 }
637 }
638 Ok::<_, String>(set)
639 })?;
640 Ok(urls.iter().filter(|u| !referenced.contains(*u)).cloned().collect())
641}
642
643pub fn hash_referenced_elsewhere(hash: &str, excluding_event_id: &str) -> Result<bool, String> {
647 if hash.is_empty() {
648 return Ok(false);
649 }
650 let conn = super::get_db_connection_guard_static()?;
651 let mut stmt = conn
652 .prepare("SELECT 1 FROM attachments WHERE hash = ?1 AND event_id <> ?2 LIMIT 1")
653 .map_err(|e| format!("hash_referenced prepare: {e}"))?;
654 stmt.exists(rusqlite::params![hash, excluding_event_id])
655 .map_err(|e| format!("hash_referenced query: {e}"))
656}
657
658#[cfg(test)]
659mod tests {
660 use super::*;
661 use crate::types::{Attachment, Message};
662
663 static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(74000);
664
665 fn make_test_npub(n: u32) -> String {
666 const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
667 let mut payload = vec![b'q'; 58];
668 let mut x = n as u64;
669 let mut i = 58;
670 while x > 0 && i > 0 {
671 i -= 1;
672 payload[i] = BECH32[(x as usize) % 32];
673 x /= 32;
674 }
675 format!("npub1{}", std::str::from_utf8(&payload).unwrap())
676 }
677
678 fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
679 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
680 crate::db::close_database();
681 crate::db::clear_id_caches();
682 let tmp = tempfile::tempdir().unwrap();
683 let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
684 let account = make_test_npub(n);
685 std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
686 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
687 crate::db::set_current_account(account.clone()).unwrap();
688 crate::db::init_database(&account).unwrap();
689 (tmp, guard)
690 }
691
692 fn att(hash: &str, url: &str, keyed: bool, downloaded: bool) -> Attachment {
694 Attachment {
695 id: hash.to_string(),
696 key: if keyed { "k".into() } else { String::new() },
697 nonce: if keyed { "n".into() } else { String::new() },
698 url: url.to_string(),
699 size: 42,
700 downloaded,
701 verified: downloaded,
702 ..Default::default()
703 }
704 }
705
706 async fn save(chat: &str, event_id: &str, mine: bool, a: Attachment) {
707 let msg = Message {
708 id: event_id.to_string(),
709 content: String::new(),
710 mine,
711 at: 1_000_000,
712 attachments: vec![a],
713 ..Default::default()
714 };
715 crate::db::events::save_message(chat, &msg).await.unwrap();
716 }
717
718 #[tokio::test]
721 async fn a_topic_resolves_to_its_app_message_only_within_its_chat() {
722 let (_tmp, _guard) = init_test_db();
723 let mut game = att("HG", "https://b.example/g", true, true);
724 game.extension = "xdc".into();
725 game.webxdc_topic = Some("TOPICA".into());
726 save("npub1chatq", "evt_game", false, game).await;
727 save("npub1chatq", "evt_photo", false, att("HP", "https://b.example/p", true, true)).await;
728
729 let (event_id, found) = find_by_webxdc_topic_in("npub1chatq", "TOPICA").unwrap().expect("the topic's message");
730 assert_eq!(event_id, "evt_game");
731 assert_eq!(found.id, "HG");
732 assert!(find_by_webxdc_topic_in("npub1chatq", "TOPICB").unwrap().is_none());
733 let mut copy = att("HG", "https://b.example/g2", true, true);
735 copy.extension = "xdc".into();
736 copy.webxdc_topic = Some("TOPICA".into());
737 save("npub1stranger", "evt_copy", false, copy).await;
738 assert_eq!(find_by_webxdc_topic_in("npub1chatq", "TOPICA").unwrap().unwrap().0, "evt_game");
739 assert_eq!(find_by_webxdc_topic_in("npub1stranger", "TOPICA").unwrap().unwrap().0, "evt_copy");
740 assert!(find_by_webxdc_topic_in("npub1nobody", "TOPICA").unwrap().is_none());
741 }
742
743 #[tokio::test]
747 async fn the_ledger_finds_a_prior_upload_and_prefers_our_own() {
748 let (_tmp, _guard) = init_test_db();
749 save("chat_a", "evt_foreign", false, att("H1", "https://b.example/foreign", true, true)).await;
750 save("chat_b", "evt_mine", true, att("H1", "https://b.example/mine", true, true)).await;
751 save("chat_c", "evt_unverified", false, att("H2", "https://b.example/x", true, false)).await;
752 save("chat_d", "evt_keyless", true, att("H3", "https://b.example/y", false, true)).await;
753
754 let hit = find_reusable_by_hash("H1").unwrap().expect("H1 is reusable");
755 assert_eq!(hit.url, "https://b.example/mine", "own upload preferred");
756 assert!(hit.mine);
757 assert_eq!(hit.key, "k");
758 assert_eq!(hit.size, 42);
759
760 assert!(find_reusable_by_hash("H2").unwrap().is_none(), "unverified rows never qualify");
761 assert!(find_reusable_by_hash("H3").unwrap().is_none(), "keyless rows never qualify");
762 assert!(find_reusable_by_hash("H9").unwrap().is_none());
763 }
764
765 #[tokio::test]
769 async fn a_claim_matched_by_a_local_file_never_lends_its_blob_to_a_forward() {
770 let (_tmp, _guard) = init_test_db();
771 let dir = tempfile::tempdir().unwrap();
772 let file = dir.path().join("photo.jpg");
773 std::fs::write(&file, b"a photo we really hold").unwrap();
774 let hash = crate::crypto::sha256_hex(b"a photo we really hold");
775
776 let mut honest = att(&hash, "https://b.example/honest", true, true);
777 honest.path = file.to_string_lossy().to_string();
778 save("chat_a", "evt_honest", false, honest.clone()).await;
779
780 let mut claim = att(&hash, "https://evil.example/other", true, false);
781 claim.key = "attacker".into();
782 claim.size = b"a photo we really hold".len() as u64 + 16;
783 let mut msg = Message {
784 id: "evt_claim".into(), content: String::new(), at: 2_000_000,
785 attachments: vec![claim], ..Default::default()
786 };
787 verify_message_attachments(&mut msg, None).await;
788 assert!(msg.attachments[0].downloaded, "the local file still renders for the claim");
789 crate::db::events::save_message("chat_b", &msg).await.unwrap();
790
791 let stored = get_attachments_for_event("evt_claim").unwrap();
792 assert!(stored[0].downloaded && !stored[0].verified, "matched, never proven");
793 let hit = find_reusable_by_hash(&hash).unwrap().expect("the honest blob is reusable");
794 assert_eq!(hit.url, "https://b.example/honest", "the newer, unproven claim never wins");
795
796 honest.verified = false;
797 honest.downloaded = false;
798 save("chat_a", "evt_honest", false, honest).await;
799 assert!(get_attachments_for_event("evt_honest").unwrap()[0].verified, "proof survives a re-delivery");
800 }
801
802 #[tokio::test]
806 async fn the_ledger_knows_where_the_bytes_already_landed() {
807 let (_tmp, _guard) = init_test_db();
808 let mut on_disk = att("HP", "https://b.example/p", true, true);
809 on_disk.path = "/dl/counter-strike-1.xdc".to_string();
810 save("chat_a", "evt_disk", true, on_disk).await;
811 let mut ghost = att("HP", "https://b.example/p2", true, false);
812 ghost.path = "/dl/never-finished.xdc".to_string();
813 save("chat_b", "evt_ghost", false, ghost).await;
814 save("chat_c", "evt_pathless", true, att("HP", "https://b.example/p3", true, true)).await;
815
816 assert_eq!(
817 downloaded_paths_by_hash("HP").unwrap(),
818 vec!["/dl/counter-strike-1.xdc".to_string()],
819 "only the downloaded row with a real path answers"
820 );
821 assert!(downloaded_paths_by_hash("H9").unwrap().is_empty());
822 }
823
824 #[tokio::test]
828 async fn a_claim_verifies_against_real_bytes_or_not_at_all() {
829 let (_tmp, _guard) = init_test_db();
830 let dir = tempfile::tempdir().unwrap();
831 let good = dir.path().join("counter-strike.xdc");
832 std::fs::write(&good, b"the actual game bytes").unwrap();
833 let real_hash = crate::crypto::sha256_hex(b"the actual game bytes");
834
835 let mut row = att(&real_hash, "https://b.example/cs", true, true);
836 row.path = good.to_string_lossy().to_string();
837 save("chat_a", "evt_cs", true, row).await;
838
839 let claim = |hash: &str, size: u64| crate::types::Attachment {
840 id: hash.to_string(),
841 size,
842 ..Default::default()
843 };
844 let plain_len = b"the actual game bytes".len() as u64;
846 assert!(verify_local_copy(&claim(&real_hash, plain_len)).await.is_some());
847 assert!(verify_local_copy(&claim(&real_hash, plain_len + 16)).await.is_some());
848 assert!(verify_local_copy(&claim(&real_hash, 0)).await.is_some(), "sizeless claims still verify by content");
849 assert!(verify_local_copy(&claim(&real_hash, plain_len + 1)).await.is_none());
851
852 std::fs::write(&good, b"not the game").unwrap();
854 assert!(verify_local_copy(&claim(&real_hash, plain_len)).await.is_none());
855
856 crate::media::store::keep_sealed(b"the actual game bytes", crate::simd::hex::hex_to_bytes_32(&real_hash), "application/zip", crate::db::media_store::Origin::Imported).unwrap();
858 assert_eq!(verify_local_copy(&claim(&real_hash, plain_len)).await.as_deref(), Some(""));
859 }
860
861 #[tokio::test]
864 async fn a_sealed_or_unreadable_reference_never_frees_a_blob() {
865 struct Vault;
866 impl Drop for Vault {
867 fn drop(&mut self) {
868 crate::state::ENCRYPTION_KEY.clear(&[]);
869 crate::state::set_encryption_enabled(false);
870 }
871 }
872 let (_tmp, _guard) = init_test_db();
873 let _vault = Vault;
874 crate::state::ENCRYPTION_KEY.set([0x71; 32], &[]);
875 crate::state::set_encryption_enabled(true);
876 let url = "https://b.example/shared".to_string();
877 save("chat_a", "evt_first", true, att("HH", &url, true, true)).await;
878 let mirror = Attachment { fallback_urls: vec![url.clone()], ..att("JJ", "https://c.example/own", true, true) };
879 save("chat_b", "evt_mirror", true, mirror).await;
880 assert!(urls_unreferenced_elsewhere(&[url.clone()], "evt_first").unwrap().is_empty(), "a sealed mirror URL still holds the blob");
881
882 crate::state::ENCRYPTION_KEY.set([0x72; 32], &[]);
883 assert!(urls_unreferenced_elsewhere(&[url.clone()], "evt_first").is_err(), "unreadable references scrub nothing");
884 assert!(find_reusable_by_hash("HH").unwrap().is_none(), "nor hand out ciphertext for a forward");
885 }
886
887 #[tokio::test]
891 async fn a_shared_blob_survives_every_delete_but_the_last() {
892 let (_tmp, _guard) = init_test_db();
893 let url = "https://b.example/shared".to_string();
894 save("chat_a", "evt_first", true, att("HH", &url, true, true)).await;
895 save("chat_b", "evt_second", true, att("HH", &url, true, true)).await;
896
897 assert!(urls_unreferenced_elsewhere(&[url.clone()], "evt_first").unwrap().is_empty());
899 assert!(urls_unreferenced_elsewhere(&[url.clone()], "evt_second").unwrap().is_empty());
900 assert!(hash_referenced_elsewhere("HH", "evt_first").unwrap());
901
902 crate::db::events::delete_event("evt_second").await.unwrap();
904 assert_eq!(urls_unreferenced_elsewhere(&[url.clone()], "evt_first").unwrap(), vec![url]);
905 assert!(!hash_referenced_elsewhere("HH", "evt_first").unwrap());
906 }
907}