1use base64::Engine;
2use std::collections::hash_map::DefaultHasher;
3use std::collections::{HashMap, VecDeque};
4use std::hash::{Hash, Hasher};
5use std::sync::{Arc, LazyLock, Mutex};
6
7pub(crate) const MEMO_CAPACITY: usize = 128;
8
9pub(crate) struct FifoMemo<K, V> {
10 map: HashMap<K, V>,
11 order: VecDeque<K>,
12}
13
14impl<K: Eq + Hash + Clone, V> FifoMemo<K, V> {
15 pub(crate) fn new() -> Self {
16 Self {
17 map: HashMap::new(),
18 order: VecDeque::new(),
19 }
20 }
21
22 pub(crate) fn get(&self, key: &K) -> Option<&V> {
23 self.map.get(key)
24 }
25
26 pub(crate) fn insert(&mut self, key: K, value: V) -> Option<V> {
27 if !self.map.contains_key(&key) {
28 if self.order.len() >= MEMO_CAPACITY
29 && let Some(oldest) = self.order.pop_front()
30 {
31 _ = self.map.remove(&oldest);
32 }
33 self.order.push_back(key.clone());
34 }
35 self.map.insert(key, value)
36 }
37}
38
39static PREVIEW_MEMO: LazyLock<Mutex<FifoMemo<(String, u64), Preview>>> =
40 LazyLock::new(|| Mutex::new(FifoMemo::new()));
41
42#[derive(Debug, Clone, PartialEq, Default)]
43pub struct Attachment {
44 pub name: String,
45 pub data: Arc<[u8]>,
46}
47
48#[must_use]
49pub fn format_size(size: u64) -> String {
50 const KB: u64 = 1024;
51 const MB: u64 = KB * 1024;
52 if size < KB {
53 format!("{size} B")
54 } else {
55 let (unit, label) = if size >= MB { (MB, "MB") } else { (KB, "KB") };
56 let tenths = (u128::from(size) * 10 + u128::from(unit) / 2) / u128::from(unit);
57 format!("{}.{} {}", tenths / 10, tenths % 10, label)
58 }
59}
60
61#[must_use]
62pub fn mime_for(name: &str) -> Option<&'static str> {
63 let ext = name
64 .rsplit_once('.')
65 .map(|(_, e)| e.to_ascii_lowercase())
66 .unwrap_or_default();
67 match ext.as_str() {
68 "jpg" | "jpeg" => Some("image/jpeg"),
69 "png" => Some("image/png"),
70 "gif" => Some("image/gif"),
71 "webp" => Some("image/webp"),
72 "bmp" => Some("image/bmp"),
73 "svg" => Some("image/svg+xml"),
74 "avif" => Some("image/avif"),
75 "ico" => Some("image/x-icon"),
76 "mp4" => Some("video/mp4"),
77 "webm" => Some("video/webm"),
78 "mov" => Some("video/quicktime"),
79 "ogv" => Some("video/ogg"),
80 "m4v" => Some("video/x-m4v"),
81 "mp3" => Some("audio/mpeg"),
82 "wav" => Some("audio/wav"),
83 "ogg" | "oga" => Some("audio/ogg"),
84 "m4a" => Some("audio/mp4"),
85 "flac" => Some("audio/flac"),
86 "aac" => Some("audio/aac"),
87 "opus" => Some("audio/opus"),
88 "pdf" => Some("application/pdf"),
89 "txt" | "log" => Some("text/plain"),
90 "md" | "markdown" => Some("text/markdown"),
91 "html" | "htm" => Some("text/html"),
92 "css" => Some("text/css"),
93 "csv" => Some("text/csv"),
94 "json" => Some("application/json"),
95 "xml" => Some("application/xml"),
96 "toml" => Some("application/toml"),
97 "yaml" | "yml" => Some("application/yaml"),
98 _ => None,
99 }
100}
101
102#[must_use]
103pub fn is_text(mime: &str) -> bool {
104 mime.starts_with("text/")
105 || matches!(
106 mime,
107 "application/json" | "application/xml" | "application/toml" | "application/yaml"
108 )
109}
110
111#[derive(Debug, Clone, PartialEq)]
112pub enum Preview {
113 Image(String),
114 Video(String),
115 Audio(String),
116 Pdf(String),
117 Markdown(String),
118 Text(String),
119 Download,
120 Missing,
121}
122
123#[must_use]
124pub fn preview(name: &str, data: &[u8]) -> Preview {
125 const PREVIEW_LIMIT: usize = 5 * 1024 * 1024;
126 if data.len() > PREVIEW_LIMIT {
127 return Preview::Download;
128 }
129 let url = |mime: &str| {
130 format!(
131 "data:{mime};base64,{}",
132 base64::engine::general_purpose::STANDARD.encode(data)
133 )
134 };
135 match mime_for(name) {
136 Some(mime) if mime.starts_with("image/") => Preview::Image(url(mime)),
137 Some(mime) if mime.starts_with("video/") => Preview::Video(url(mime)),
138 Some(mime) if mime.starts_with("audio/") => Preview::Audio(url(mime)),
139 Some("application/pdf") => Preview::Pdf(url("application/pdf")),
140 Some(mime) if is_text(mime) => match String::from_utf8(data.to_vec()) {
141 Ok(text) if mime == "text/markdown" => Preview::Markdown(text),
142 Ok(text) => Preview::Text(text),
143 Err(e) => {
144 tracing::warn!("Preview text decode failed: {e}");
145 Preview::Download
146 }
147 },
148 _ => Preview::Download,
149 }
150}
151
152#[must_use]
153pub fn preview_cached(name: &str, data: &[u8]) -> Preview {
154 let key = (name.to_string(), preview_key(data));
155 PREVIEW_MEMO
156 .lock()
157 .ok()
158 .and_then(|guard| guard.get(&key).cloned())
159 .unwrap_or_else(|| {
160 let preview = preview(name, data);
161 if let Ok(mut guard) = PREVIEW_MEMO.lock() {
162 _ = guard.insert(key, preview.clone());
163 }
164 preview
165 })
166}
167
168#[must_use]
174pub fn preview_key(data: &[u8]) -> u64 {
175 let mut hasher = DefaultHasher::new();
176 data.as_ptr().hash(&mut hasher);
177 data.len().hash(&mut hasher);
178 hasher.finish()
179}
180
181#[must_use]
185pub fn preview_blob_url(preview: &Preview) -> Option<&str> {
186 match preview {
187 Preview::Image(url) | Preview::Video(url) | Preview::Audio(url) | Preview::Pdf(url) => {
188 url.strip_prefix("blob:").map(|_| url.as_str())
189 }
190 _ => None,
191 }
192}
193
194#[must_use]
200pub fn preview_initial(name: &str, data: &[u8]) -> Option<Preview> {
201 if mime_for(name).is_some_and(|m| {
202 m.starts_with("image/")
203 || m.starts_with("video/")
204 || m.starts_with("audio/")
205 || m == "application/pdf"
206 }) {
207 None
208 } else {
209 Some(preview(name, data))
210 }
211}