deltachat/
ephemeral.rs

1//! # Ephemeral messages.
2//!
3//! Ephemeral messages are messages that have an Ephemeral-Timer
4//! header attached to them, which specifies time in seconds after
5//! which the message should be deleted both from the device and from
6//! the server. The timer is started when the message is marked as
7//! seen, which usually happens when its contents is displayed on
8//! device screen.
9//!
10//! Each chat, including 1:1, group chats and "saved messages" chat,
11//! has its own ephemeral timer setting, which is applied to all
12//! messages sent to the chat. The setting is synchronized to all the
13//! devices participating in the chat by applying the timer value from
14//! all received messages, including BCC-self ones, to the chat. This
15//! way the setting is eventually synchronized among all participants.
16//!
17//! When user changes ephemeral timer setting for the chat, a system
18//! message is automatically sent to update the setting for all
19//! participants. This allows changing the setting for a chat like any
20//! group chat setting, e.g. name and avatar, without the need to
21//! write an actual message.
22//!
23//! ## Device settings
24//!
25//! In addition to per-chat ephemeral message setting, each device has
26//! two global user-configured settings that complement per-chat
27//! settings: `delete_device_after` and `delete_server_after`. These
28//! settings are not synchronized among devices and apply to all
29//! messages known to the device, including messages sent or received
30//! before configuring the setting.
31//!
32//! `delete_device_after` configures the maximum time device is
33//! storing the messages locally. `delete_server_after` configures the
34//! time after which device will delete the messages it knows about
35//! from the server.
36//!
37//! ## How messages are deleted
38//!
39//! When Delta Chat deletes the message locally, it moves the message
40//! to the trash chat and removes actual message contents. Messages in
41//! the trash chat are called "tombstones" and track the Message-ID to
42//! prevent accidental redownloading of the message from the server,
43//! e.g. in case of UID validity change.
44//!
45//! Vice versa, when Delta Chat deletes the message from the server,
46//! it removes IMAP folder and UID row from the `imap` table, but
47//! keeps the message in the `msgs` table.
48//!
49//! Delta Chat eventually removes tombstones from the `msgs` table,
50//! leaving no trace of the message, when it thinks there are no more
51//! copies of the message stored on the server, i.e. when there is no
52//! corresponding `imap` table entry. This is done in the
53//! `prune_tombstones()` procedure during housekeeping.
54//!
55//! ## When messages are deleted
56//!
57//! The `ephemeral_loop` task schedules the next due running of
58//! `delete_expired_messages` which in turn emits `MsgsChanged` events
59//! when deleting local messages to make UIs reload displayed messages.
60//!
61//! Server deletion happens by updating the `imap` table based on
62//! the database entries which are expired either according to their
63//! ephemeral message timers or global `delete_server_after` setting.
64
65use std::cmp::max;
66use std::collections::BTreeSet;
67use std::fmt;
68use std::num::ParseIntError;
69use std::str::FromStr;
70use std::time::{Duration, UNIX_EPOCH};
71
72use anyhow::{Context as _, Result, ensure};
73use async_channel::Receiver;
74use serde::{Deserialize, Serialize};
75use tokio::time::timeout;
76
77use crate::chat::{ChatId, ChatIdBlocked, send_msg};
78use crate::constants::{DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH};
79use crate::contact::ContactId;
80use crate::context::Context;
81use crate::download::MIN_DELETE_SERVER_AFTER;
82use crate::events::EventType;
83use crate::location;
84use crate::log::{LogExt, error, info, warn};
85use crate::message::{Message, MessageState, MsgId, Viewtype};
86use crate::mimeparser::SystemMessage;
87use crate::stock_str;
88use crate::tools::{SystemTime, duration_to_str, time};
89
90/// Ephemeral timer value.
91#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
92pub enum Timer {
93    /// Timer is disabled.
94    Disabled,
95
96    /// Timer is enabled.
97    Enabled {
98        /// Timer duration in seconds.
99        ///
100        /// The value cannot be 0.
101        duration: u32,
102    },
103}
104
105impl Timer {
106    /// Converts epehmeral timer value to integer.
107    ///
108    /// If the timer is disabled, return 0.
109    pub fn to_u32(self) -> u32 {
110        match self {
111            Self::Disabled => 0,
112            Self::Enabled { duration } => duration,
113        }
114    }
115
116    /// Converts integer to ephemeral timer value.
117    ///
118    /// 0 value is treated as disabled timer.
119    pub fn from_u32(duration: u32) -> Self {
120        if duration == 0 {
121            Self::Disabled
122        } else {
123            Self::Enabled { duration }
124        }
125    }
126}
127
128impl Default for Timer {
129    fn default() -> Self {
130        Self::Disabled
131    }
132}
133
134impl fmt::Display for Timer {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        write!(f, "{}", self.to_u32())
137    }
138}
139
140impl FromStr for Timer {
141    type Err = ParseIntError;
142
143    fn from_str(input: &str) -> Result<Timer, ParseIntError> {
144        input.parse::<u32>().map(Self::from_u32)
145    }
146}
147
148impl rusqlite::types::ToSql for Timer {
149    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
150        let val = rusqlite::types::Value::Integer(match self {
151            Self::Disabled => 0,
152            Self::Enabled { duration } => i64::from(*duration),
153        });
154        let out = rusqlite::types::ToSqlOutput::Owned(val);
155        Ok(out)
156    }
157}
158
159impl rusqlite::types::FromSql for Timer {
160    fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
161        i64::column_result(value).and_then(|value| {
162            if value == 0 {
163                Ok(Self::Disabled)
164            } else if let Ok(duration) = u32::try_from(value) {
165                Ok(Self::Enabled { duration })
166            } else {
167                Err(rusqlite::types::FromSqlError::OutOfRange(value))
168            }
169        })
170    }
171}
172
173impl ChatId {
174    /// Get ephemeral message timer value in seconds.
175    pub async fn get_ephemeral_timer(self, context: &Context) -> Result<Timer> {
176        let timer = context
177            .sql
178            .query_get_value(
179                "SELECT IFNULL(ephemeral_timer, 0) FROM chats WHERE id=?",
180                (self,),
181            )
182            .await?
183            .with_context(|| format!("Chat {self} not found"))?;
184        Ok(timer)
185    }
186
187    /// Set ephemeral timer value without sending a message.
188    ///
189    /// Used when a message arrives indicating that someone else has
190    /// changed the timer value for a chat.
191    pub(crate) async fn inner_set_ephemeral_timer(
192        self,
193        context: &Context,
194        timer: Timer,
195    ) -> Result<()> {
196        ensure!(!self.is_special(), "Invalid chat ID");
197
198        context
199            .sql
200            .execute(
201                "UPDATE chats
202             SET ephemeral_timer=?
203             WHERE id=?;",
204                (timer, self),
205            )
206            .await?;
207
208        context.emit_event(EventType::ChatEphemeralTimerModified {
209            chat_id: self,
210            timer,
211        });
212        Ok(())
213    }
214
215    /// Set ephemeral message timer value in seconds.
216    ///
217    /// If timer value is 0, disable ephemeral message timer.
218    pub async fn set_ephemeral_timer(self, context: &Context, timer: Timer) -> Result<()> {
219        if timer == self.get_ephemeral_timer(context).await? {
220            return Ok(());
221        }
222        self.inner_set_ephemeral_timer(context, timer).await?;
223
224        if self.is_promoted(context).await? {
225            let mut msg = Message::new_text(
226                stock_ephemeral_timer_changed(context, timer, ContactId::SELF).await,
227            );
228            msg.param.set_cmd(SystemMessage::EphemeralTimerChanged);
229            if let Err(err) = send_msg(context, self, &mut msg).await {
230                error!(
231                    context,
232                    "Failed to send a message about ephemeral message timer change: {:?}", err
233                );
234            }
235        }
236        Ok(())
237    }
238}
239
240/// Returns a stock message saying that ephemeral timer is changed to `timer` by `from_id`.
241pub(crate) async fn stock_ephemeral_timer_changed(
242    context: &Context,
243    timer: Timer,
244    from_id: ContactId,
245) -> String {
246    match timer {
247        Timer::Disabled => stock_str::msg_ephemeral_timer_disabled(context, from_id).await,
248        Timer::Enabled { duration } => match duration {
249            0..=59 => {
250                stock_str::msg_ephemeral_timer_enabled(context, &timer.to_string(), from_id).await
251            }
252            60 => stock_str::msg_ephemeral_timer_minute(context, from_id).await,
253            61..=3599 => {
254                stock_str::msg_ephemeral_timer_minutes(
255                    context,
256                    &format!("{}", (f64::from(duration) / 6.0).round() / 10.0),
257                    from_id,
258                )
259                .await
260            }
261            3600 => stock_str::msg_ephemeral_timer_hour(context, from_id).await,
262            3601..=86399 => {
263                stock_str::msg_ephemeral_timer_hours(
264                    context,
265                    &format!("{}", (f64::from(duration) / 360.0).round() / 10.0),
266                    from_id,
267                )
268                .await
269            }
270            86400 => stock_str::msg_ephemeral_timer_day(context, from_id).await,
271            86401..=604_799 => {
272                stock_str::msg_ephemeral_timer_days(
273                    context,
274                    &format!("{}", (f64::from(duration) / 8640.0).round() / 10.0),
275                    from_id,
276                )
277                .await
278            }
279            604_800 => stock_str::msg_ephemeral_timer_week(context, from_id).await,
280            31_536_000..=31_708_800 => stock_str::msg_ephemeral_timer_year(context, from_id).await,
281            _ => {
282                stock_str::msg_ephemeral_timer_weeks(
283                    context,
284                    &format!("{}", (f64::from(duration) / 60480.0).round() / 10.0),
285                    from_id,
286                )
287                .await
288            }
289        },
290    }
291}
292
293impl MsgId {
294    /// Returns ephemeral message timer value for the message.
295    pub(crate) async fn ephemeral_timer(self, context: &Context) -> Result<Timer> {
296        let res = match context
297            .sql
298            .query_get_value("SELECT ephemeral_timer FROM msgs WHERE id=?", (self,))
299            .await?
300        {
301            None | Some(0) => Timer::Disabled,
302            Some(duration) => Timer::Enabled { duration },
303        };
304        Ok(res)
305    }
306
307    /// Starts ephemeral message timer for the message if it is not started yet.
308    pub(crate) async fn start_ephemeral_timer(self, context: &Context) -> Result<()> {
309        if let Timer::Enabled { duration } = self.ephemeral_timer(context).await? {
310            let ephemeral_timestamp = time().saturating_add(duration.into());
311
312            context
313                .sql
314                .execute(
315                    "UPDATE msgs SET ephemeral_timestamp = ? \
316                WHERE (ephemeral_timestamp == 0 OR ephemeral_timestamp > ?) \
317                AND id = ?",
318                    (ephemeral_timestamp, ephemeral_timestamp, self),
319                )
320                .await?;
321            context.scheduler.interrupt_ephemeral_task().await;
322        }
323        Ok(())
324    }
325}
326
327pub(crate) async fn start_ephemeral_timers_msgids(
328    context: &Context,
329    msg_ids: &[MsgId],
330) -> Result<()> {
331    let now = time();
332    let should_interrupt =
333    context
334        .sql
335        .transaction(move |transaction| {
336            let mut should_interrupt = false;
337            let mut stmt =
338                transaction.prepare(
339                    "UPDATE msgs SET ephemeral_timestamp = ?1 + ephemeral_timer
340                     WHERE (ephemeral_timestamp == 0 OR ephemeral_timestamp > ?1 + ephemeral_timer) AND ephemeral_timer > 0
341                     AND id=?2")?;
342            for msg_id in msg_ids {
343                should_interrupt |= stmt.execute((now, msg_id))? > 0;
344            }
345            Ok(should_interrupt)
346        }).await?;
347    if should_interrupt {
348        context.scheduler.interrupt_ephemeral_task().await;
349    }
350    Ok(())
351}
352
353/// Starts ephemeral timer for all messages in the chat.
354///
355/// This should be called when chat is marked as noticed.
356pub(crate) async fn start_chat_ephemeral_timers(context: &Context, chat_id: ChatId) -> Result<()> {
357    let now = time();
358    let should_interrupt = context
359        .sql
360        .execute(
361            "UPDATE msgs SET ephemeral_timestamp = ?1 + ephemeral_timer
362             WHERE chat_id = ?2
363             AND ephemeral_timer > 0
364             AND (ephemeral_timestamp == 0 OR ephemeral_timestamp > ?1 + ephemeral_timer)",
365            (now, chat_id),
366        )
367        .await?
368        > 0;
369    if should_interrupt {
370        context.scheduler.interrupt_ephemeral_task().await;
371    }
372    Ok(())
373}
374
375/// Selects messages which are expired according to
376/// `delete_device_after` setting or `ephemeral_timestamp` column.
377///
378/// For each message a row ID, chat id, viewtype and location ID is returned.
379async fn select_expired_messages(
380    context: &Context,
381    now: i64,
382) -> Result<Vec<(MsgId, ChatId, Viewtype, u32)>> {
383    let mut rows = context
384        .sql
385        .query_map(
386            r#"
387SELECT id, chat_id, type, location_id
388FROM msgs
389WHERE
390  ephemeral_timestamp != 0
391  AND ephemeral_timestamp <= ?
392  AND chat_id != ?
393"#,
394            (now, DC_CHAT_ID_TRASH),
395            |row| {
396                let id: MsgId = row.get("id")?;
397                let chat_id: ChatId = row.get("chat_id")?;
398                let viewtype: Viewtype = row.get("type")?;
399                let location_id: u32 = row.get("location_id")?;
400                Ok((id, chat_id, viewtype, location_id))
401            },
402            |rows| rows.collect::<Result<Vec<_>, _>>().map_err(Into::into),
403        )
404        .await?;
405
406    if let Some(delete_device_after) = context.get_config_delete_device_after().await? {
407        let self_chat_id = ChatIdBlocked::lookup_by_contact(context, ContactId::SELF)
408            .await?
409            .map(|c| c.id)
410            .unwrap_or_default();
411        let device_chat_id = ChatIdBlocked::lookup_by_contact(context, ContactId::DEVICE)
412            .await?
413            .map(|c| c.id)
414            .unwrap_or_default();
415
416        let threshold_timestamp = now.saturating_sub(delete_device_after);
417
418        let rows_expired = context
419            .sql
420            .query_map(
421                r#"
422SELECT id, chat_id, type, location_id
423FROM msgs
424WHERE
425  timestamp < ?1
426  AND timestamp_rcvd < ?1
427  AND chat_id > ?
428  AND chat_id != ?
429  AND chat_id != ?
430"#,
431                (
432                    threshold_timestamp,
433                    DC_CHAT_ID_LAST_SPECIAL,
434                    self_chat_id,
435                    device_chat_id,
436                ),
437                |row| {
438                    let id: MsgId = row.get("id")?;
439                    let chat_id: ChatId = row.get("chat_id")?;
440                    let viewtype: Viewtype = row.get("type")?;
441                    let location_id: u32 = row.get("location_id")?;
442                    Ok((id, chat_id, viewtype, location_id))
443                },
444                |rows| rows.collect::<Result<Vec<_>, _>>().map_err(Into::into),
445            )
446            .await?;
447
448        rows.extend(rows_expired);
449    }
450
451    Ok(rows)
452}
453
454/// Deletes messages which are expired according to
455/// `delete_device_after` setting or `ephemeral_timestamp` column.
456///
457/// Emits relevant `MsgsChanged` and `WebxdcInstanceDeleted` events
458/// if messages are deleted.
459pub(crate) async fn delete_expired_messages(context: &Context, now: i64) -> Result<()> {
460    let rows = select_expired_messages(context, now).await?;
461
462    if !rows.is_empty() {
463        info!(context, "Attempting to delete {} messages.", rows.len());
464
465        let (msgs_changed, webxdc_deleted) = context
466            .sql
467            .transaction(|transaction| {
468                let mut msgs_changed = Vec::with_capacity(rows.len());
469                let mut webxdc_deleted = Vec::new();
470                // If you change which information is preserved here, also change `MsgId::trash()`
471                // and other places it references.
472                let mut del_msg_stmt = transaction.prepare(
473                    "INSERT OR REPLACE INTO msgs (id, rfc724_mid, timestamp, chat_id)
474                     SELECT ?1, rfc724_mid, timestamp, ? FROM msgs WHERE id=?1",
475                )?;
476                let mut del_location_stmt =
477                    transaction.prepare("DELETE FROM locations WHERE independent=1 AND id=?")?;
478                for (msg_id, chat_id, viewtype, location_id) in rows {
479                    del_msg_stmt.execute((msg_id, DC_CHAT_ID_TRASH))?;
480                    if location_id > 0 {
481                        del_location_stmt.execute((location_id,))?;
482                    }
483
484                    msgs_changed.push((chat_id, msg_id));
485                    if viewtype == Viewtype::Webxdc {
486                        webxdc_deleted.push(msg_id)
487                    }
488                }
489                Ok((msgs_changed, webxdc_deleted))
490            })
491            .await?;
492
493        let mut modified_chat_ids = BTreeSet::new();
494
495        for (chat_id, msg_id) in msgs_changed {
496            context.emit_event(EventType::MsgDeleted { chat_id, msg_id });
497            modified_chat_ids.insert(chat_id);
498        }
499
500        for modified_chat_id in modified_chat_ids {
501            context.emit_msgs_changed_without_msg_id(modified_chat_id);
502        }
503
504        for msg_id in webxdc_deleted {
505            context.emit_event(EventType::WebxdcInstanceDeleted { msg_id });
506        }
507    }
508
509    Ok(())
510}
511
512/// Calculates the next timestamp when a message will be deleted due to
513/// `delete_device_after` setting being set.
514async fn next_delete_device_after_timestamp(context: &Context) -> Result<Option<i64>> {
515    if let Some(delete_device_after) = context.get_config_delete_device_after().await? {
516        let self_chat_id = ChatIdBlocked::lookup_by_contact(context, ContactId::SELF)
517            .await?
518            .map(|c| c.id)
519            .unwrap_or_default();
520        let device_chat_id = ChatIdBlocked::lookup_by_contact(context, ContactId::DEVICE)
521            .await?
522            .map(|c| c.id)
523            .unwrap_or_default();
524
525        let oldest_message_timestamp: Option<i64> = context
526            .sql
527            .query_get_value(
528                r#"
529                SELECT min(max(timestamp, timestamp_rcvd))
530                FROM msgs
531                WHERE chat_id > ?
532                  AND chat_id != ?
533                  AND chat_id != ?
534                HAVING count(*) > 0
535                "#,
536                (DC_CHAT_ID_TRASH, self_chat_id, device_chat_id),
537            )
538            .await?;
539
540        Ok(oldest_message_timestamp.map(|x| x.saturating_add(delete_device_after)))
541    } else {
542        Ok(None)
543    }
544}
545
546/// Calculates next timestamp when expiration of some message will happen.
547///
548/// Expiration can happen either because user has set `delete_device_after` setting or because the
549/// message itself has an ephemeral timer.
550async fn next_expiration_timestamp(context: &Context) -> Option<i64> {
551    let ephemeral_timestamp: Option<i64> = match context
552        .sql
553        .query_get_value(
554            r#"
555            SELECT min(ephemeral_timestamp)
556            FROM msgs
557            WHERE ephemeral_timestamp != 0
558              AND chat_id != ?
559            HAVING count(*) > 0
560            "#,
561            (DC_CHAT_ID_TRASH,), // Trash contains already deleted messages, skip them
562        )
563        .await
564    {
565        Err(err) => {
566            warn!(context, "Can't calculate next ephemeral timeout: {}", err);
567            None
568        }
569        Ok(ephemeral_timestamp) => ephemeral_timestamp,
570    };
571
572    let delete_device_after_timestamp: Option<i64> =
573        match next_delete_device_after_timestamp(context).await {
574            Err(err) => {
575                warn!(
576                    context,
577                    "Can't calculate timestamp of the next message expiration: {}", err
578                );
579                None
580            }
581            Ok(timestamp) => timestamp,
582        };
583
584    ephemeral_timestamp
585        .into_iter()
586        .chain(delete_device_after_timestamp)
587        .min()
588}
589
590pub(crate) async fn ephemeral_loop(context: &Context, interrupt_receiver: Receiver<()>) {
591    loop {
592        let ephemeral_timestamp = next_expiration_timestamp(context).await;
593
594        let now = SystemTime::now();
595        let until = if let Some(ephemeral_timestamp) = ephemeral_timestamp {
596            UNIX_EPOCH
597                + Duration::from_secs(ephemeral_timestamp.try_into().unwrap_or(u64::MAX))
598                + Duration::from_secs(1)
599        } else {
600            // no messages to be deleted for now, wait long for one to occur
601            now + Duration::from_secs(86400)
602        };
603
604        if let Ok(duration) = until.duration_since(now) {
605            info!(
606                context,
607                "Ephemeral loop waiting for deletion in {} or interrupt",
608                duration_to_str(duration)
609            );
610            match timeout(duration, interrupt_receiver.recv()).await {
611                Ok(Ok(())) => {
612                    // received an interruption signal, recompute waiting time (if any)
613                    continue;
614                }
615                Ok(Err(err)) => {
616                    warn!(
617                        context,
618                        "Interrupt channel closed, ephemeral loop exits now: {err:#}."
619                    );
620                    return;
621                }
622                Err(_err) => {
623                    // Timeout.
624                }
625            }
626        }
627
628        delete_expired_messages(context, time())
629            .await
630            .log_err(context)
631            .ok();
632
633        location::delete_expired(context, time())
634            .await
635            .log_err(context)
636            .ok();
637    }
638}
639
640/// Schedules expired IMAP messages for deletion.
641pub(crate) async fn delete_expired_imap_messages(context: &Context) -> Result<()> {
642    let now = time();
643
644    let (threshold_timestamp, threshold_timestamp_extended) =
645        match context.get_config_delete_server_after().await? {
646            None => (0, 0),
647            Some(delete_server_after) => (
648                match delete_server_after {
649                    // Guarantee immediate deletion.
650                    0 => i64::MAX,
651                    _ => now - delete_server_after,
652                },
653                now - max(delete_server_after, MIN_DELETE_SERVER_AFTER),
654            ),
655        };
656    let target = context.get_delete_msgs_target().await?;
657
658    context
659        .sql
660        .execute(
661            "UPDATE imap
662             SET target=?
663             WHERE rfc724_mid IN (
664               SELECT rfc724_mid FROM msgs
665               WHERE ((download_state = 0 AND timestamp < ?) OR
666                      (download_state != 0 AND timestamp < ?) OR
667                      (ephemeral_timestamp != 0 AND ephemeral_timestamp <= ?))
668             )",
669            (
670                &target,
671                threshold_timestamp,
672                threshold_timestamp_extended,
673                now,
674            ),
675        )
676        .await?;
677
678    Ok(())
679}
680
681/// Start ephemeral timers for seen messages if they are not started
682/// yet.
683///
684/// It is possible that timers are not started due to a missing or
685/// failed `MsgId.start_ephemeral_timer()` call, either in the current
686/// or previous version of Delta Chat.
687///
688/// This function is supposed to be called in the background,
689/// e.g. from housekeeping task.
690pub(crate) async fn start_ephemeral_timers(context: &Context) -> Result<()> {
691    context
692        .sql
693        .execute(
694            "UPDATE msgs \
695    SET ephemeral_timestamp = ? + ephemeral_timer \
696    WHERE ephemeral_timer > 0 \
697    AND ephemeral_timestamp = 0 \
698    AND state NOT IN (?, ?, ?)",
699            (
700                time(),
701                MessageState::InFresh,
702                MessageState::InNoticed,
703                MessageState::OutDraft,
704            ),
705        )
706        .await?;
707
708    Ok(())
709}
710
711#[cfg(test)]
712mod ephemeral_tests;