1use std::collections::BTreeMap;
4
5use anyhow::{Result, anyhow, bail, ensure};
6use deltachat_derive::{FromSql, ToSql};
7use serde::{Deserialize, Serialize};
8
9use crate::context::Context;
10use crate::imap::session::Session;
11use crate::log::warn;
12use crate::message::{self, Message, MsgId, rfc724_mid_exists};
13use crate::{EventType, chatlist_events};
14
15pub(crate) mod post_msg_metadata;
16pub(crate) use post_msg_metadata::PostMsgMetadata;
17
18pub(crate) const MIN_DELETE_SERVER_AFTER: i64 = 48 * 60 * 60;
23
24pub(crate) const PRE_MSG_ATTACHMENT_SIZE_THRESHOLD: u64 = 140_000;
30
31pub(crate) const PRE_MSG_SIZE_WARNING_THRESHOLD: usize = 150_000;
33
34#[derive(
36 Debug,
37 Default,
38 Display,
39 Clone,
40 Copy,
41 PartialEq,
42 Eq,
43 FromPrimitive,
44 ToPrimitive,
45 FromSql,
46 ToSql,
47 Serialize,
48 Deserialize,
49)]
50#[repr(u32)]
51pub enum DownloadState {
52 #[default]
54 Done = 0,
55
56 Available = 10,
58
59 Failure = 20,
61
62 Undecipherable = 30,
64
65 InProgress = 1000,
67}
68
69impl MsgId {
70 pub async fn download_full(self, context: &Context) -> Result<()> {
72 let msg = Message::load_from_db(context, self).await?;
73 match msg.download_state() {
74 DownloadState::Done | DownloadState::Undecipherable => {
75 return Err(anyhow!("Nothing to download."));
76 }
77 DownloadState::InProgress => return Err(anyhow!("Download already in progress.")),
78 DownloadState::Available | DownloadState::Failure => {
79 if msg.rfc724_mid().is_empty() {
80 return Err(anyhow!("Download not possible, message has no rfc724_mid"));
81 }
82 self.update_download_state(context, DownloadState::InProgress)
83 .await?;
84 info!(
85 context,
86 "Requesting full download of {:?}.",
87 msg.rfc724_mid()
88 );
89 context
90 .sql
91 .execute(
92 "INSERT INTO download (rfc724_mid, msg_id) VALUES (?,?)",
93 (msg.rfc724_mid(), msg.id),
94 )
95 .await?;
96 context.scheduler.interrupt_inbox().await;
97 }
98 }
99 Ok(())
100 }
101
102 pub(crate) async fn update_download_state(
105 self,
106 context: &Context,
107 download_state: DownloadState,
108 ) -> Result<()> {
109 if context
110 .sql
111 .execute(
112 "UPDATE msgs SET download_state=? WHERE id=? AND download_state<>?1",
113 (download_state, self),
114 )
115 .await?
116 == 0
117 {
118 return Ok(());
119 }
120 let Some(msg) = Message::load_from_db_optional(context, self).await? else {
121 return Ok(());
122 };
123 context.emit_event(EventType::MsgsChanged {
124 chat_id: msg.chat_id,
125 msg_id: self,
126 });
127 chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);
128 Ok(())
129 }
130}
131
132impl Message {
133 pub fn download_state(&self) -> DownloadState {
135 self.download_state
136 }
137}
138
139pub(crate) async fn download_msg(
145 context: &Context,
146 rfc724_mid: String,
147 session: &mut Session,
148) -> Result<Option<()>> {
149 let transport_id = session.transport_id();
150 let row = context
151 .sql
152 .query_row_optional(
153 "SELECT uid, folder, transport_id FROM imap
154 WHERE rfc724_mid=? AND target!=''
155 ORDER BY transport_id=? DESC LIMIT 1",
156 (&rfc724_mid, transport_id),
157 |row| {
158 let server_uid: u32 = row.get(0)?;
159 let server_folder: String = row.get(1)?;
160 let msg_transport_id: u32 = row.get(2)?;
161 Ok((server_uid, server_folder, msg_transport_id))
162 },
163 )
164 .await?;
165
166 let Some((server_uid, server_folder, msg_transport_id)) = row else {
167 return Err(anyhow!(
169 "IMAP location for {rfc724_mid:?} post-message is unknown"
170 ));
171 };
172 if msg_transport_id != transport_id {
173 return Ok(None);
174 }
175 session
176 .fetch_single_msg(context, &server_folder, server_uid, rfc724_mid)
177 .await?;
178 Ok(Some(()))
179}
180
181impl Session {
182 async fn fetch_single_msg(
187 &mut self,
188 context: &Context,
189 folder: &str,
190 uid: u32,
191 rfc724_mid: String,
192 ) -> Result<()> {
193 if uid == 0 {
194 bail!("Attempt to fetch UID 0");
195 }
196
197 let folder_exists = self.select_with_uidvalidity(context, folder).await?;
198 ensure!(folder_exists, "No folder {folder}");
199
200 info!(context, "Downloading message {}/{} fully...", folder, uid);
202
203 let mut uid_message_ids: BTreeMap<u32, String> = BTreeMap::new();
204 uid_message_ids.insert(uid, rfc724_mid);
205 let (sender, receiver) = async_channel::unbounded();
206 self.fetch_many_msgs(context, folder, vec![uid], &uid_message_ids, sender)
207 .await?;
208 if receiver.recv().await.is_err() {
209 bail!("Failed to fetch UID {uid}");
210 }
211 Ok(())
212 }
213}
214
215async fn set_state_to_failure(context: &Context, rfc724_mid: &str) -> Result<()> {
216 if let Some(msg_id) = rfc724_mid_exists(context, rfc724_mid).await? {
217 msg_id
224 .update_download_state(context, DownloadState::Failure)
225 .await?;
226 }
227 Ok(())
228}
229
230async fn available_post_msgs_contains_rfc724_mid(
231 context: &Context,
232 rfc724_mid: &str,
233) -> Result<bool> {
234 Ok(context
235 .sql
236 .query_get_value::<String>(
237 "SELECT rfc724_mid FROM available_post_msgs WHERE rfc724_mid=?",
238 (&rfc724_mid,),
239 )
240 .await?
241 .is_some())
242}
243
244async fn delete_from_available_post_msgs(context: &Context, rfc724_mid: &str) -> Result<()> {
245 context
246 .sql
247 .execute(
248 "DELETE FROM available_post_msgs WHERE rfc724_mid=?",
249 (&rfc724_mid,),
250 )
251 .await?;
252 Ok(())
253}
254
255async fn delete_from_downloads(context: &Context, rfc724_mid: &str) -> Result<()> {
256 context
257 .sql
258 .execute("DELETE FROM download WHERE rfc724_mid=?", (&rfc724_mid,))
259 .await?;
260 Ok(())
261}
262
263pub(crate) async fn msg_is_downloaded_for(context: &Context, rfc724_mid: &str) -> Result<bool> {
264 Ok(message::rfc724_mid_exists(context, rfc724_mid)
265 .await?
266 .is_some())
267}
268
269pub(crate) async fn download_msgs(context: &Context, session: &mut Session) -> Result<()> {
270 let rfc724_mids = context
271 .sql
272 .query_map_vec("SELECT rfc724_mid FROM download", (), |row| {
273 let rfc724_mid: String = row.get(0)?;
274 Ok(rfc724_mid)
275 })
276 .await?;
277
278 for rfc724_mid in &rfc724_mids {
279 let res = download_msg(context, rfc724_mid.clone(), session).await;
280 if let Ok(Some(())) = res {
281 delete_from_downloads(context, rfc724_mid).await?;
282 delete_from_available_post_msgs(context, rfc724_mid).await?;
283 }
284 if let Err(err) = res {
285 warn!(
286 context,
287 "Failed to download message rfc724_mid={rfc724_mid}: {:#}.", err
288 );
289 if !msg_is_downloaded_for(context, rfc724_mid).await? {
290 warn!(
292 context,
293 "{rfc724_mid} download failed and there is no downloaded pre-message."
294 );
295 delete_from_downloads(context, rfc724_mid).await?;
296 } else if available_post_msgs_contains_rfc724_mid(context, rfc724_mid).await? {
297 warn!(
298 context,
299 "{rfc724_mid} is in available_post_msgs table but we failed to fetch it,
300 so set the message to DownloadState::Failure - probably it was deleted on the server in the meantime"
301 );
302 set_state_to_failure(context, rfc724_mid).await?;
303 delete_from_downloads(context, rfc724_mid).await?;
304 delete_from_available_post_msgs(context, rfc724_mid).await?;
305 } else {
306 }
309 }
310 }
311
312 Ok(())
313}
314
315pub(crate) async fn download_known_post_messages_without_pre_message(
318 context: &Context,
319 session: &mut Session,
320) -> Result<()> {
321 let rfc724_mids = context
322 .sql
323 .query_map_vec("SELECT rfc724_mid FROM available_post_msgs", (), |row| {
324 let rfc724_mid: String = row.get(0)?;
325 Ok(rfc724_mid)
326 })
327 .await?;
328 for rfc724_mid in &rfc724_mids {
329 if !msg_is_downloaded_for(context, rfc724_mid).await? {
330 let res = download_msg(context, rfc724_mid.clone(), session).await;
335 if let Ok(Some(())) = res {
336 delete_from_available_post_msgs(context, rfc724_mid).await?;
337 }
338 if let Err(err) = res {
339 warn!(
340 context,
341 "download_known_post_messages_without_pre_message: Failed to download message rfc724_mid={rfc724_mid}: {:#}.",
342 err
343 );
344 }
345 }
346 }
347 Ok(())
348}
349
350#[cfg(test)]
351mod tests {
352 use num_traits::FromPrimitive;
353
354 use super::*;
355 use crate::chat::send_msg;
356 use crate::test_utils::TestContext;
357
358 #[test]
359 fn test_downloadstate_values() {
360 assert_eq!(DownloadState::Done, DownloadState::default());
362 assert_eq!(DownloadState::Done, DownloadState::from_i32(0).unwrap());
363 assert_eq!(
364 DownloadState::Available,
365 DownloadState::from_i32(10).unwrap()
366 );
367 assert_eq!(DownloadState::Failure, DownloadState::from_i32(20).unwrap());
368 assert_eq!(
369 DownloadState::InProgress,
370 DownloadState::from_i32(1000).unwrap()
371 );
372 }
373
374 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
375 async fn test_update_download_state() -> Result<()> {
376 let t = TestContext::new_alice().await;
377 let chat = t.create_chat_with_contact("Bob", "bob@example.org").await;
378
379 let mut msg = Message::new_text("Hi Bob".to_owned());
380 let msg_id = send_msg(&t, chat.id, &mut msg).await?;
381 let msg = Message::load_from_db(&t, msg_id).await?;
382 assert_eq!(msg.download_state(), DownloadState::Done);
383
384 for s in &[
385 DownloadState::Available,
386 DownloadState::InProgress,
387 DownloadState::Failure,
388 DownloadState::Done,
389 DownloadState::Done,
390 ] {
391 msg_id.update_download_state(&t, *s).await?;
392 let msg = Message::load_from_db(&t, msg_id).await?;
393 assert_eq!(msg.download_state(), *s);
394 }
395 t.sql
396 .execute("DELETE FROM msgs WHERE id=?", (msg_id,))
397 .await?;
398 msg_id
400 .update_download_state(&t, DownloadState::Done)
401 .await?;
402
403 Ok(())
404 }
405}