deltachat/
download.rs

1//! # Download large messages manually.
2
3use 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
18/// If a message is downloaded only partially
19/// and `delete_server_after` is set to small timeouts (eg. "at once"),
20/// the user might have no chance to actually download that message.
21/// `MIN_DELETE_SERVER_AFTER` increases the timeout in this case.
22pub(crate) const MIN_DELETE_SERVER_AFTER: i64 = 48 * 60 * 60;
23
24/// From this point onward outgoing messages are considered large
25/// and get a Pre-Message, which announces the Post-Message.
26/// This is only about sending so we can modify it any time.
27/// Current value is a bit less than the minimum auto-download setting from the UIs (which is 160
28/// KiB).
29pub(crate) const PRE_MSG_ATTACHMENT_SIZE_THRESHOLD: u64 = 140_000;
30
31/// Max size for pre messages. A warning is emitted when this is exceeded.
32pub(crate) const PRE_MSG_SIZE_WARNING_THRESHOLD: usize = 150_000;
33
34/// Download state of the message.
35#[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    /// Message is fully downloaded.
53    #[default]
54    Done = 0,
55
56    /// Message is partially downloaded and can be fully downloaded at request.
57    Available = 10,
58
59    /// Failed to fully download the message.
60    Failure = 20,
61
62    /// Undecipherable message.
63    Undecipherable = 30,
64
65    /// Full download of the message is in progress.
66    InProgress = 1000,
67}
68
69impl MsgId {
70    /// Schedules Post-Message download for partially downloaded message.
71    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    /// Updates the message download state. Returns `Ok` if the message doesn't exist anymore or has
103    /// the download state up to date.
104    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    /// Returns the download state of the message.
134    pub fn download_state(&self) -> DownloadState {
135        self.download_state
136    }
137}
138
139/// Actually downloads a message partially downloaded before if the message is available on the
140/// session transport, in which case returns `Some`. If the message is available on another
141/// transport, returns `None`.
142///
143/// Most messages are downloaded automatically on fetch instead.
144pub(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        // No IMAP record found, we don't know the UID and folder.
168        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    /// Download a single message and pipe it to receive_imf().
183    ///
184    /// receive_imf() is not directly aware that this is a result of a call to download_msg(),
185    /// however, implicitly knows that as the existing message is flagged as being partly.
186    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        // we are connected, and the folder is selected
201        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        // Update download state to failure
218        // so it can be retried.
219        //
220        // On success update_download_state() is not needed
221        // as receive_imf() already
222        // set the state and emitted the event.
223        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                // This is probably a classical email that vanished before we could download it
291                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                // leave the message in DownloadState::InProgress;
307                // it will be downloaded once it arrives.
308            }
309        }
310    }
311
312    Ok(())
313}
314
315/// Downloads known post-messages without pre-messages
316/// in order to guard against lost pre-messages.
317pub(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            // Download the Post-Message unconditionally,
331            // because the Pre-Message got lost.
332            // The message may be in the wrong order,
333            // but at least we have it at all.
334            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        // values may be written to disk and must not change
361        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        // Nothing to do is ok.
399        msg_id
400            .update_download_state(&t, DownloadState::Done)
401            .await?;
402
403        Ok(())
404    }
405}