|
1 | 1 | use crate::error::AppError; |
| 2 | +use regex_lite::Regex; |
| 3 | +use rusqlite::{params, params_from_iter, types::Value, Connection}; |
2 | 4 | use serde::Serialize; |
3 | 5 | use sha2::{Digest, Sha256}; |
| 6 | +use std::collections::HashSet; |
4 | 7 | use std::fs; |
5 | 8 | use std::path::PathBuf; |
6 | 9 | use tauri::{AppHandle, Manager}; |
@@ -88,6 +91,124 @@ pub fn save_blob(app: &AppHandle, hash: &str, ext: &str, data: &[u8]) -> Result< |
88 | 91 | Ok(()) |
89 | 92 | } |
90 | 93 |
|
| 94 | +/// Delete a blob from the local attachments directory by its hash. |
| 95 | +/// Returns true if a file was deleted. |
| 96 | +pub fn delete_local_blob(app: &AppHandle, hash: &str) -> Result<bool, AppError> { |
| 97 | + let dir = attachments_dir(app)?; |
| 98 | + for ext in KNOWN_EXTENSIONS { |
| 99 | + let path = dir.join(format!("{hash}.{ext}")); |
| 100 | + if path.exists() { |
| 101 | + fs::remove_file(&path)?; |
| 102 | + return Ok(true); |
| 103 | + } |
| 104 | + } |
| 105 | + Ok(false) |
| 106 | +} |
| 107 | + |
| 108 | +/// Extract attachment:// hashes from markdown content. |
| 109 | +pub fn extract_attachment_hashes(markdown: &str) -> Vec<String> { |
| 110 | + static RE: std::sync::LazyLock<Regex> = |
| 111 | + std::sync::LazyLock::new(|| Regex::new(r"attachment://([a-f0-9]{64})\.\w+").unwrap()); |
| 112 | + RE.captures_iter(markdown) |
| 113 | + .map(|cap| cap[1].to_string()) |
| 114 | + .collect() |
| 115 | +} |
| 116 | + |
| 117 | +/// Find attachment hashes in the given notes that are not referenced by any other note. |
| 118 | +/// Must be called BEFORE the notes are deleted. |
| 119 | +pub fn find_orphaned_blob_hashes(conn: &Connection, note_ids: &[String]) -> Result<HashSet<String>, AppError> { |
| 120 | + if note_ids.is_empty() { |
| 121 | + return Ok(HashSet::new()); |
| 122 | + } |
| 123 | + |
| 124 | + // Collect all hashes referenced by notes being deleted |
| 125 | + let placeholders: String = note_ids.iter().map(|_| "?").collect::<Vec<_>>().join(","); |
| 126 | + let sql = format!("SELECT markdown FROM notes WHERE id IN ({})", placeholders); |
| 127 | + let mut stmt = conn.prepare(&sql)?; |
| 128 | + let id_params: Vec<Value> = note_ids.iter().map(|id| Value::from(id.clone())).collect(); |
| 129 | + let rows = stmt.query_map(params_from_iter(id_params.iter()), |row| { |
| 130 | + row.get::<_, String>(0) |
| 131 | + })?; |
| 132 | + |
| 133 | + let mut candidate_hashes = HashSet::new(); |
| 134 | + for row in rows { |
| 135 | + for hash in extract_attachment_hashes(&row?) { |
| 136 | + candidate_hashes.insert(hash); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + if candidate_hashes.is_empty() { |
| 141 | + return Ok(HashSet::new()); |
| 142 | + } |
| 143 | + |
| 144 | + // Check which hashes are still referenced by other notes using SQL |
| 145 | + // to avoid pulling all markdown into memory |
| 146 | + let excluded = format!("SELECT markdown FROM notes WHERE id NOT IN ({})", placeholders); |
| 147 | + let mut remaining_stmt = conn.prepare(&excluded)?; |
| 148 | + let excluded_params: Vec<Value> = note_ids.iter().map(|id| Value::from(id.clone())).collect(); |
| 149 | + let remaining_rows = remaining_stmt.query_map(params_from_iter(excluded_params.iter()), |row| { |
| 150 | + row.get::<_, String>(0) |
| 151 | + })?; |
| 152 | + |
| 153 | + for row in remaining_rows { |
| 154 | + for hash in extract_attachment_hashes(&row?) { |
| 155 | + candidate_hashes.remove(&hash); |
| 156 | + } |
| 157 | + if candidate_hashes.is_empty() { |
| 158 | + break; // Early exit — all candidates are still referenced |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + Ok(candidate_hashes) |
| 163 | +} |
| 164 | + |
| 165 | +/// Clean up orphaned blobs: delete local files, remove blob_meta/blob_uploads entries. |
| 166 | +/// Returns (server_url, ciphertext_hash) pairs for Blossom server deletion. |
| 167 | +pub fn cleanup_orphaned_blobs( |
| 168 | + app: &AppHandle, |
| 169 | + conn: &Connection, |
| 170 | + orphaned_hashes: &HashSet<String>, |
| 171 | +) -> Vec<(String, String)> { |
| 172 | + if orphaned_hashes.is_empty() { |
| 173 | + return Vec::new(); |
| 174 | + } |
| 175 | + |
| 176 | + let mut blossom_deletions = Vec::new(); |
| 177 | + |
| 178 | + // Prepare statements once outside the loop |
| 179 | + let mut meta_stmt = conn |
| 180 | + .prepare("SELECT server_url, ciphertext_hash FROM blob_meta WHERE plaintext_hash = ?1") |
| 181 | + .ok(); |
| 182 | + let mut del_meta_stmt = conn |
| 183 | + .prepare("DELETE FROM blob_meta WHERE plaintext_hash = ?1") |
| 184 | + .ok(); |
| 185 | + let mut del_uploads_stmt = conn |
| 186 | + .prepare("DELETE FROM blob_uploads WHERE hash = ?1") |
| 187 | + .ok(); |
| 188 | + |
| 189 | + for hash in orphaned_hashes { |
| 190 | + if let Some(ref mut stmt) = meta_stmt { |
| 191 | + if let Ok(rows) = stmt.query_map(params![hash], |row| { |
| 192 | + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) |
| 193 | + }) { |
| 194 | + for row in rows.flatten() { |
| 195 | + blossom_deletions.push(row); |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | + if let Some(ref mut stmt) = del_meta_stmt { |
| 200 | + let _ = stmt.execute(params![hash]); |
| 201 | + } |
| 202 | + if let Some(ref mut stmt) = del_uploads_stmt { |
| 203 | + let _ = stmt.execute(params![hash]); |
| 204 | + } |
| 205 | + let _ = delete_local_blob(app, hash); |
| 206 | + eprintln!("[blob-gc] cleaned up orphaned blob hash={}", &hash[..8.min(hash.len())]); |
| 207 | + } |
| 208 | + |
| 209 | + blossom_deletions |
| 210 | +} |
| 211 | + |
91 | 212 | /// Read a blob from the attachments directory by its hash. |
92 | 213 | /// Returns (bytes, extension). |
93 | 214 | pub fn read_blob(app: &AppHandle, hash: &str) -> Result<Option<(Vec<u8>, String)>, AppError> { |
|
0 commit comments