deltachat/
context.rs

1//! Context module.
2
3use std::collections::{BTreeMap, HashMap};
4use std::ffi::OsString;
5use std::ops::Deref;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::AtomicBool;
8use std::sync::{Arc, OnceLock, Weak};
9use std::time::Duration;
10
11use anyhow::{Result, bail, ensure};
12use async_channel::{self as channel, Receiver, Sender};
13use pgp::composed::SignedPublicKey;
14use ratelimit::Ratelimit;
15use tokio::sync::{Mutex, Notify, RwLock};
16
17use crate::chat::{ChatId, get_chat_cnt};
18use crate::config::Config;
19use crate::constants::{self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_VERSION_STR};
20use crate::contact::{Contact, ContactId};
21use crate::debug_logging::DebugLogging;
22use crate::events::{Event, EventEmitter, EventType, Events};
23use crate::imap::{FolderMeaning, Imap, ServerMetadata};
24use crate::key::self_fingerprint;
25use crate::log::warn;
26use crate::logged_debug_assert;
27use crate::message::{self, MessageState, MsgId};
28use crate::net::tls::TlsSessionStore;
29use crate::peer_channels::Iroh;
30use crate::push::PushSubscriber;
31use crate::quota::QuotaInfo;
32use crate::scheduler::{ConnectivityStore, SchedulerState, convert_folder_meaning};
33use crate::sql::Sql;
34use crate::stock_str::StockStrings;
35use crate::timesmearing::SmearedTimestamp;
36use crate::tools::{self, duration_to_str, time, time_elapsed};
37use crate::transport::ConfiguredLoginParam;
38use crate::{chatlist_events, stats};
39
40pub use crate::scheduler::connectivity::Connectivity;
41
42/// Builder for the [`Context`].
43///
44/// Many arguments to the [`Context`] are kind of optional and only needed to handle
45/// multiple contexts, for which the [account manager](crate::accounts::Accounts) should be
46/// used.  This builder makes creating a new context simpler, especially for the
47/// standalone-context case.
48///
49/// # Examples
50///
51/// Creating a new database:
52///
53/// ```
54/// # let rt = tokio::runtime::Runtime::new().unwrap();
55/// # rt.block_on(async move {
56/// use deltachat::context::ContextBuilder;
57///
58/// let dir = tempfile::tempdir().unwrap();
59/// let context = ContextBuilder::new(dir.path().join("db"))
60///      .open()
61///      .await
62///      .unwrap();
63/// drop(context);
64/// # });
65/// ```
66#[derive(Clone, Debug)]
67pub struct ContextBuilder {
68    dbfile: PathBuf,
69    id: u32,
70    events: Events,
71    stock_strings: StockStrings,
72    password: Option<String>,
73
74    push_subscriber: Option<PushSubscriber>,
75}
76
77impl ContextBuilder {
78    /// Create the builder using the given database file.
79    ///
80    /// The *dbfile* should be in a dedicated directory and this directory must exist.  The
81    /// [`Context`] will create other files and folders in the same directory as the
82    /// database file used.
83    pub fn new(dbfile: PathBuf) -> Self {
84        ContextBuilder {
85            dbfile,
86            id: rand::random(),
87            events: Events::new(),
88            stock_strings: StockStrings::new(),
89            password: None,
90            push_subscriber: None,
91        }
92    }
93
94    /// Sets the context ID.
95    ///
96    /// This identifier is used e.g. in [`Event`]s to identify which [`Context`] an event
97    /// belongs to.  The only real limit on it is that it should not conflict with any other
98    /// [`Context`]s you currently have open.  So if you handle multiple [`Context`]s you
99    /// may want to use this.
100    ///
101    /// Note that the [account manager](crate::accounts::Accounts) is designed to handle the
102    /// common case for using multiple [`Context`] instances.
103    pub fn with_id(mut self, id: u32) -> Self {
104        self.id = id;
105        self
106    }
107
108    /// Sets the event channel for this [`Context`].
109    ///
110    /// Mostly useful when using multiple [`Context`]s, this allows creating one [`Events`]
111    /// channel and passing it to all [`Context`]s so all events are received on the same
112    /// channel.
113    ///
114    /// Note that the [account manager](crate::accounts::Accounts) is designed to handle the
115    /// common case for using multiple [`Context`] instances.
116    pub fn with_events(mut self, events: Events) -> Self {
117        self.events = events;
118        self
119    }
120
121    /// Sets the [`StockStrings`] map to use for this [`Context`].
122    ///
123    /// This is useful in order to share the same translation strings in all [`Context`]s.
124    /// The mapping may be empty when set, it will be populated by
125    /// [`Context::set_stock_translation`] or [`Accounts::set_stock_translation`] calls.
126    ///
127    /// Note that the [account manager](crate::accounts::Accounts) is designed to handle the
128    /// common case for using multiple [`Context`] instances.
129    ///
130    /// [`Accounts::set_stock_translation`]: crate::accounts::Accounts::set_stock_translation
131    pub fn with_stock_strings(mut self, stock_strings: StockStrings) -> Self {
132        self.stock_strings = stock_strings;
133        self
134    }
135
136    /// Sets the password to unlock the database.
137    /// Deprecated 2025-11:
138    /// - Db encryption does nothing with blobs, so fs/disk encryption is recommended.
139    /// - Isolation from other apps is needed anyway.
140    ///
141    /// If an encrypted database is used it must be opened with a password.  Setting a
142    /// password on a new database will enable encryption.
143    #[deprecated(since = "TBD")]
144    pub fn with_password(mut self, password: String) -> Self {
145        self.password = Some(password);
146        self
147    }
148
149    /// Sets push subscriber.
150    pub(crate) fn with_push_subscriber(mut self, push_subscriber: PushSubscriber) -> Self {
151        self.push_subscriber = Some(push_subscriber);
152        self
153    }
154
155    /// Builds the [`Context`] without opening it.
156    pub async fn build(self) -> Result<Context> {
157        let push_subscriber = self.push_subscriber.unwrap_or_default();
158        let context = Context::new_closed(
159            &self.dbfile,
160            self.id,
161            self.events,
162            self.stock_strings,
163            push_subscriber,
164        )
165        .await?;
166        Ok(context)
167    }
168
169    /// Builds the [`Context`] and opens it.
170    ///
171    /// Returns error if context cannot be opened.
172    pub async fn open(self) -> Result<Context> {
173        let password = self.password.clone().unwrap_or_default();
174        let context = self.build().await?;
175        match context.open(password).await? {
176            true => Ok(context),
177            false => bail!("database could not be decrypted, incorrect or missing password"),
178        }
179    }
180}
181
182/// The context for a single DeltaChat account.
183///
184/// This contains all the state for a single DeltaChat account, including background tasks
185/// running in Tokio to operate the account.  The [`Context`] can be cheaply cloned.
186///
187/// Each context, and thus each account, must be associated with an directory where all the
188/// state is kept.  This state is also preserved between restarts.
189///
190/// To use multiple accounts it is best to look at the [accounts
191/// manager][crate::accounts::Accounts] which handles storing multiple accounts in a single
192/// directory structure and handles loading them all concurrently.
193#[derive(Clone, Debug)]
194pub struct Context {
195    pub(crate) inner: Arc<InnerContext>,
196}
197
198impl Deref for Context {
199    type Target = InnerContext;
200
201    fn deref(&self) -> &Self::Target {
202        &self.inner
203    }
204}
205
206/// A weak reference to a [`Context`]
207///
208/// Can be used to obtain a [`Context`]. An existing weak reference does not prevent the corresponding [`Context`] from being dropped.
209#[derive(Clone, Debug)]
210pub(crate) struct WeakContext {
211    inner: Weak<InnerContext>,
212}
213
214impl WeakContext {
215    /// Returns the [`Context`] if it is still available.
216    pub(crate) fn upgrade(&self) -> Result<Context> {
217        let inner = self
218            .inner
219            .upgrade()
220            .ok_or_else(|| anyhow::anyhow!("Inner struct has been dropped"))?;
221        Ok(Context { inner })
222    }
223}
224
225/// Actual context, expensive to clone.
226#[derive(Debug)]
227pub struct InnerContext {
228    /// Blob directory path
229    pub(crate) blobdir: PathBuf,
230    pub(crate) sql: Sql,
231    pub(crate) smeared_timestamp: SmearedTimestamp,
232    /// The global "ongoing" process state.
233    ///
234    /// This is a global mutex-like state for operations which should be modal in the
235    /// clients.
236    running_state: RwLock<RunningState>,
237    /// Mutex to enforce only a single running oauth2 is running.
238    pub(crate) oauth2_mutex: Mutex<()>,
239    /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent.
240    pub(crate) wrong_pw_warning_mutex: Mutex<()>,
241    /// Mutex to prevent running housekeeping from multiple threads at once.
242    pub(crate) housekeeping_mutex: Mutex<()>,
243
244    /// Mutex to prevent multiple IMAP loops from fetching the messages at once.
245    ///
246    /// Without this mutex IMAP loops may waste traffic downloading the same message
247    /// from multiple IMAP servers and create multiple copies of the same message
248    /// in the database if the check for duplicates and creating a message
249    /// happens in separate database transactions.
250    pub(crate) fetch_msgs_mutex: Mutex<()>,
251
252    pub(crate) translated_stockstrings: StockStrings,
253    pub(crate) events: Events,
254
255    pub(crate) scheduler: SchedulerState,
256    pub(crate) ratelimit: RwLock<Ratelimit>,
257
258    /// Recently loaded quota information for each trasnport, if any.
259    /// If quota was never tried to load, then the transport doesn't have an entry in the BTreeMap.
260    pub(crate) quota: RwLock<BTreeMap<u32, QuotaInfo>>,
261
262    /// Notify about new messages.
263    ///
264    /// This causes [`Context::wait_next_msgs`] to wake up.
265    pub(crate) new_msgs_notify: Notify,
266
267    /// Server ID response if ID capability is supported
268    /// and the server returned non-NIL on the inbox connection.
269    /// <https://datatracker.ietf.org/doc/html/rfc2971>
270    pub(crate) server_id: RwLock<Option<HashMap<String, String>>>,
271
272    /// IMAP METADATA.
273    pub(crate) metadata: RwLock<Option<ServerMetadata>>,
274
275    /// ID for this `Context` in the current process.
276    ///
277    /// This allows for multiple `Context`s open in a single process where each context can
278    /// be identified by this ID.
279    pub(crate) id: u32,
280
281    creation_time: tools::Time,
282
283    /// The text of the last error logged and emitted as an event.
284    /// If the ui wants to display an error after a failure,
285    /// `last_error` should be used to avoid races with the event thread.
286    pub(crate) last_error: parking_lot::RwLock<String>,
287
288    /// It's not possible to emit migration errors as an event,
289    /// because at the time of the migration, there is no event emitter yet.
290    /// So, this holds the error that happened during migration, if any.
291    /// This is necessary for the possibly-failible PGP migration,
292    /// which happened 2025-05, and can be removed a few releases later.
293    pub(crate) migration_error: parking_lot::RwLock<Option<String>>,
294
295    /// If debug logging is enabled, this contains all necessary information
296    ///
297    /// Standard RwLock instead of [`tokio::sync::RwLock`] is used
298    /// because the lock is used from synchronous [`Context::emit_event`].
299    pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>,
300
301    /// Push subscriber to store device token
302    /// and register for heartbeat notifications.
303    pub(crate) push_subscriber: PushSubscriber,
304
305    /// True if account has subscribed to push notifications via IMAP.
306    pub(crate) push_subscribed: AtomicBool,
307
308    /// TLS session resumption cache.
309    pub(crate) tls_session_store: TlsSessionStore,
310
311    /// Iroh for realtime peer channels.
312    pub(crate) iroh: Arc<RwLock<Option<Iroh>>>,
313
314    /// The own fingerprint, if it was computed already.
315    /// tokio::sync::OnceCell would be possible to use, but overkill for our usecase;
316    /// the standard library's OnceLock is enough, and it's a lot smaller in memory.
317    pub(crate) self_fingerprint: OnceLock<String>,
318
319    /// OpenPGP certificate aka Transferrable Public Key.
320    ///
321    /// It is generated on first use from the secret key stored in the database.
322    ///
323    /// Mutex is also held while generating the key to avoid generating the key twice.
324    pub(crate) self_public_key: Mutex<Option<SignedPublicKey>>,
325
326    /// `Connectivity` values for mailboxes, unordered. Used to compute the aggregate connectivity,
327    /// see [`Context::get_connectivity()`].
328    pub(crate) connectivities: parking_lot::Mutex<Vec<ConnectivityStore>>,
329
330    #[expect(clippy::type_complexity)]
331    /// Transforms the root of the cryptographic payload before encryption.
332    pub(crate) pre_encrypt_mime_hook: parking_lot::Mutex<
333        Option<
334            for<'a> fn(
335                &Context,
336                mail_builder::mime::MimePart<'a>,
337            ) -> mail_builder::mime::MimePart<'a>,
338        >,
339    >,
340}
341
342/// The state of ongoing process.
343#[derive(Debug, Default)]
344enum RunningState {
345    /// Ongoing process is allocated.
346    Running { cancel_sender: Sender<()> },
347
348    /// Cancel signal has been sent, waiting for ongoing process to be freed.
349    ShallStop { request: tools::Time },
350
351    /// There is no ongoing process, a new one can be allocated.
352    #[default]
353    Stopped,
354}
355
356/// Return some info about deltachat-core
357///
358/// This contains information mostly about the library itself, the
359/// actual keys and their values which will be present are not
360/// guaranteed.  Calling [Context::get_info] also includes information
361/// about the context on top of the information here.
362#[expect(clippy::arithmetic_side_effects)]
363pub fn get_info() -> BTreeMap<&'static str, String> {
364    let mut res = BTreeMap::new();
365
366    #[cfg(debug_assertions)]
367    res.insert(
368        "debug_assertions",
369        "On - DO NOT RELEASE THIS BUILD".to_string(),
370    );
371    #[cfg(not(debug_assertions))]
372    res.insert("debug_assertions", "Off".to_string());
373
374    res.insert("deltachat_core_version", format!("v{DC_VERSION_STR}"));
375    res.insert("sqlite_version", rusqlite::version().to_string());
376    res.insert("arch", (std::mem::size_of::<usize>() * 8).to_string());
377    res.insert("num_cpus", num_cpus::get().to_string());
378    res.insert("level", "awesome".into());
379    res
380}
381
382impl Context {
383    /// Creates new context and opens the database.
384    pub async fn new(
385        dbfile: &Path,
386        id: u32,
387        events: Events,
388        stock_strings: StockStrings,
389    ) -> Result<Context> {
390        let context =
391            Self::new_closed(dbfile, id, events, stock_strings, Default::default()).await?;
392
393        // Open the database if is not encrypted.
394        if context.check_passphrase("".to_string()).await? {
395            context.sql.open(&context, "".to_string()).await?;
396        }
397        Ok(context)
398    }
399
400    /// Creates new context without opening the database.
401    pub async fn new_closed(
402        dbfile: &Path,
403        id: u32,
404        events: Events,
405        stockstrings: StockStrings,
406        push_subscriber: PushSubscriber,
407    ) -> Result<Context> {
408        let mut blob_fname = OsString::new();
409        blob_fname.push(dbfile.file_name().unwrap_or_default());
410        blob_fname.push("-blobs");
411        let blobdir = dbfile.with_file_name(blob_fname);
412        if !blobdir.exists() {
413            tokio::fs::create_dir_all(&blobdir).await?;
414        }
415        let context = Context::with_blobdir(
416            dbfile.into(),
417            blobdir,
418            id,
419            events,
420            stockstrings,
421            push_subscriber,
422        )?;
423        Ok(context)
424    }
425
426    /// Returns a weak reference to this [`Context`].
427    pub(crate) fn get_weak_context(&self) -> WeakContext {
428        WeakContext {
429            inner: Arc::downgrade(&self.inner),
430        }
431    }
432
433    /// Opens the database with the given passphrase.
434    /// NB: Db encryption is deprecated, so `passphrase` should be empty normally. See
435    /// [`ContextBuilder::with_password()`] for reasoning.
436    ///
437    /// Returns true if passphrase is correct, false is passphrase is not correct. Fails on other
438    /// errors.
439    #[deprecated(since = "TBD")]
440    pub async fn open(&self, passphrase: String) -> Result<bool> {
441        if self.sql.check_passphrase(passphrase.clone()).await? {
442            self.sql.open(self, passphrase).await?;
443            Ok(true)
444        } else {
445            Ok(false)
446        }
447    }
448
449    /// Changes encrypted database passphrase.
450    /// Deprecated 2025-11, see [`ContextBuilder::with_password()`] for reasoning.
451    pub async fn change_passphrase(&self, passphrase: String) -> Result<()> {
452        self.sql.change_passphrase(passphrase).await?;
453        Ok(())
454    }
455
456    /// Returns true if database is open.
457    pub async fn is_open(&self) -> bool {
458        self.sql.is_open().await
459    }
460
461    /// Tests the database passphrase.
462    ///
463    /// Returns true if passphrase is correct.
464    ///
465    /// Fails if database is already open.
466    pub(crate) async fn check_passphrase(&self, passphrase: String) -> Result<bool> {
467        self.sql.check_passphrase(passphrase).await
468    }
469
470    pub(crate) fn with_blobdir(
471        dbfile: PathBuf,
472        blobdir: PathBuf,
473        id: u32,
474        events: Events,
475        stockstrings: StockStrings,
476        push_subscriber: PushSubscriber,
477    ) -> Result<Context> {
478        ensure!(
479            blobdir.is_dir(),
480            "Blobdir does not exist: {}",
481            blobdir.display()
482        );
483
484        let new_msgs_notify = Notify::new();
485        // Notify once immediately to allow processing old messages
486        // without starting I/O.
487        new_msgs_notify.notify_one();
488
489        let inner = InnerContext {
490            id,
491            blobdir,
492            running_state: RwLock::new(Default::default()),
493            sql: Sql::new(dbfile),
494            smeared_timestamp: SmearedTimestamp::new(),
495            oauth2_mutex: Mutex::new(()),
496            wrong_pw_warning_mutex: Mutex::new(()),
497            housekeeping_mutex: Mutex::new(()),
498            fetch_msgs_mutex: Mutex::new(()),
499            translated_stockstrings: stockstrings,
500            events,
501            scheduler: SchedulerState::new(),
502            ratelimit: RwLock::new(Ratelimit::new(Duration::new(3, 0), 3.0)), // Allow at least 1 message every second + a burst of 3.
503            quota: RwLock::new(BTreeMap::new()),
504            new_msgs_notify,
505            server_id: RwLock::new(None),
506            metadata: RwLock::new(None),
507            creation_time: tools::Time::now(),
508            last_error: parking_lot::RwLock::new("".to_string()),
509            migration_error: parking_lot::RwLock::new(None),
510            debug_logging: std::sync::RwLock::new(None),
511            push_subscriber,
512            push_subscribed: AtomicBool::new(false),
513            tls_session_store: TlsSessionStore::new(),
514            iroh: Arc::new(RwLock::new(None)),
515            self_fingerprint: OnceLock::new(),
516            self_public_key: Mutex::new(None),
517            connectivities: parking_lot::Mutex::new(Vec::new()),
518            pre_encrypt_mime_hook: None.into(),
519        };
520
521        let ctx = Context {
522            inner: Arc::new(inner),
523        };
524
525        Ok(ctx)
526    }
527
528    /// Starts the IO scheduler.
529    pub async fn start_io(&self) {
530        if !self.is_configured().await.unwrap_or_default() {
531            warn!(self, "can not start io on a context that is not configured");
532            return;
533        }
534
535        // The next line is mainly for iOS:
536        // iOS starts a separate process for receiving notifications and if the user concurrently
537        // starts the app, the UI process opens the database but waits with calling start_io()
538        // until the notifications process finishes.
539        // Now, some configs may have changed, so, we need to invalidate the cache.
540        self.sql.config_cache.write().await.clear();
541
542        self.scheduler.start(self).await;
543    }
544
545    /// Stops the IO scheduler.
546    pub async fn stop_io(&self) {
547        self.scheduler.stop(self).await;
548        if let Some(iroh) = self.iroh.write().await.take() {
549            // Close all QUIC connections.
550
551            // Spawn into a separate task,
552            // because Iroh calls `wait_idle()` internally
553            // and it may take time, especially if the network
554            // has become unavailable.
555            tokio::spawn(async move {
556                // We do not log the error because we do not want the task
557                // to hold the reference to Context.
558                let _ = tokio::time::timeout(Duration::from_secs(60), iroh.close()).await;
559            });
560        }
561    }
562
563    /// Restarts the IO scheduler if it was running before
564    /// when it is not running this is an no-op
565    pub async fn restart_io_if_running(&self) {
566        self.scheduler.restart(self).await;
567    }
568
569    /// Indicate that the network likely has come back.
570    pub async fn maybe_network(&self) {
571        if let Some(ref iroh) = *self.iroh.read().await {
572            iroh.network_change().await;
573        }
574        self.scheduler.maybe_network().await;
575    }
576
577    /// Returns true if an account is on a chatmail server.
578    pub async fn is_chatmail(&self) -> Result<bool> {
579        self.get_config_bool(Config::IsChatmail).await
580    }
581
582    /// Returns maximum number of recipients the provider allows to send a single email to.
583    pub(crate) async fn get_max_smtp_rcpt_to(&self) -> Result<usize> {
584        let is_chatmail = self.is_chatmail().await?;
585        let val = self
586            .get_configured_provider()
587            .await?
588            .and_then(|provider| provider.opt.max_smtp_rcpt_to)
589            .map_or_else(
590                || match is_chatmail {
591                    true => constants::DEFAULT_CHATMAIL_MAX_SMTP_RCPT_TO,
592                    false => constants::DEFAULT_MAX_SMTP_RCPT_TO,
593                },
594                usize::from,
595            );
596        Ok(val)
597    }
598
599    /// Does a single round of fetching from IMAP and returns.
600    ///
601    /// Can be used even if I/O is currently stopped.
602    /// If I/O is currently stopped, starts a new IMAP connection
603    /// and fetches from Inbox and DeltaChat folders.
604    pub async fn background_fetch(&self) -> Result<()> {
605        if !(self.is_configured().await?) {
606            return Ok(());
607        }
608
609        let address = self.get_primary_self_addr().await?;
610        let time_start = tools::Time::now();
611        info!(self, "background_fetch started fetching {address}.");
612
613        if self.scheduler.is_running().await {
614            self.scheduler.maybe_network().await;
615            self.wait_for_all_work_done().await;
616        } else {
617            // Pause the scheduler to ensure another connection does not start
618            // while we are fetching on a dedicated connection.
619            let _pause_guard = self.scheduler.pause(self).await?;
620
621            // Start a new dedicated connection.
622            let mut connection = Imap::new_configured(self, channel::bounded(1).1).await?;
623            let mut session = connection.prepare(self).await?;
624
625            // Fetch IMAP folders.
626            // Inbox is fetched before Mvbox because fetching from Inbox
627            // may result in moving some messages to Mvbox.
628            for folder_meaning in [FolderMeaning::Inbox, FolderMeaning::Mvbox] {
629                if let Some((_folder_config, watch_folder)) =
630                    convert_folder_meaning(self, folder_meaning).await?
631                {
632                    connection
633                        .fetch_move_delete(self, &mut session, &watch_folder, folder_meaning)
634                        .await?;
635                }
636            }
637
638            // Update quota (to send warning if full) - but only check it once in a while.
639            // note: For now this only checks quota of primary transport,
640            // because background check only checks primary transport at the moment
641            if self
642                .quota_needs_update(
643                    session.transport_id(),
644                    DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT,
645                )
646                .await
647                && let Err(err) = self.update_recent_quota(&mut session).await
648            {
649                warn!(self, "Failed to update quota: {err:#}.");
650            }
651        }
652
653        info!(
654            self,
655            "background_fetch done for {address} took {:?}.",
656            time_elapsed(&time_start),
657        );
658
659        Ok(())
660    }
661
662    /// Returns a reference to the underlying SQL instance.
663    ///
664    /// Warning: this is only here for testing, not part of the public API.
665    #[cfg(feature = "internals")]
666    pub fn sql(&self) -> &Sql {
667        &self.inner.sql
668    }
669
670    /// Returns database file path.
671    pub fn get_dbfile(&self) -> &Path {
672        self.sql.dbfile.as_path()
673    }
674
675    /// Returns blob directory path.
676    pub fn get_blobdir(&self) -> &Path {
677        self.blobdir.as_path()
678    }
679
680    /// Emits a single event.
681    pub fn emit_event(&self, event: EventType) {
682        {
683            let lock = self.debug_logging.read().expect("RwLock is poisoned");
684            if let Some(debug_logging) = &*lock {
685                debug_logging.log_event(event.clone());
686            }
687        }
688        self.events.emit(Event {
689            id: self.id,
690            typ: event,
691        });
692    }
693
694    /// Emits a generic MsgsChanged event (without chat or message id)
695    pub fn emit_msgs_changed_without_ids(&self) {
696        self.emit_event(EventType::MsgsChanged {
697            chat_id: ChatId::new(0),
698            msg_id: MsgId::new(0),
699        });
700    }
701
702    /// Emits a MsgsChanged event with specified chat and message ids
703    ///
704    /// If IDs are unset, [`Self::emit_msgs_changed_without_ids`]
705    /// or [`Self::emit_msgs_changed_without_msg_id`] should be used
706    /// instead of this function.
707    pub fn emit_msgs_changed(&self, chat_id: ChatId, msg_id: MsgId) {
708        logged_debug_assert!(
709            self,
710            !chat_id.is_unset(),
711            "emit_msgs_changed: chat_id is unset."
712        );
713        logged_debug_assert!(
714            self,
715            !msg_id.is_unset(),
716            "emit_msgs_changed: msg_id is unset."
717        );
718
719        self.emit_event(EventType::MsgsChanged { chat_id, msg_id });
720        chatlist_events::emit_chatlist_changed(self);
721        chatlist_events::emit_chatlist_item_changed(self, chat_id);
722    }
723
724    /// Emits a MsgsChanged event with specified chat and without message id.
725    pub fn emit_msgs_changed_without_msg_id(&self, chat_id: ChatId) {
726        logged_debug_assert!(
727            self,
728            !chat_id.is_unset(),
729            "emit_msgs_changed_without_msg_id: chat_id is unset."
730        );
731
732        self.emit_event(EventType::MsgsChanged {
733            chat_id,
734            msg_id: MsgId::new(0),
735        });
736        chatlist_events::emit_chatlist_changed(self);
737        chatlist_events::emit_chatlist_item_changed(self, chat_id);
738    }
739
740    /// Emits an IncomingMsg event with specified chat and message ids
741    pub fn emit_incoming_msg(&self, chat_id: ChatId, msg_id: MsgId) {
742        debug_assert!(!chat_id.is_unset());
743        debug_assert!(!msg_id.is_unset());
744
745        self.emit_event(EventType::IncomingMsg { chat_id, msg_id });
746        chatlist_events::emit_chatlist_changed(self);
747        chatlist_events::emit_chatlist_item_changed(self, chat_id);
748    }
749
750    /// Emits an LocationChanged event and a WebxdcStatusUpdate in case there is a maps integration
751    pub async fn emit_location_changed(&self, contact_id: Option<ContactId>) -> Result<()> {
752        self.emit_event(EventType::LocationChanged(contact_id));
753
754        if let Some(msg_id) = self
755            .get_config_parsed::<u32>(Config::WebxdcIntegration)
756            .await?
757        {
758            self.emit_event(EventType::WebxdcStatusUpdate {
759                msg_id: MsgId::new(msg_id),
760                status_update_serial: Default::default(),
761            })
762        }
763
764        Ok(())
765    }
766
767    /// Returns a receiver for emitted events.
768    ///
769    /// Multiple emitters can be created, but note that in this case each emitted event will
770    /// only be received by one of the emitters, not by all of them.
771    pub fn get_event_emitter(&self) -> EventEmitter {
772        self.events.get_emitter()
773    }
774
775    /// Get the ID of this context.
776    pub fn get_id(&self) -> u32 {
777        self.id
778    }
779
780    // Ongoing process allocation/free/check
781
782    /// Tries to acquire the global UI "ongoing" mutex.
783    ///
784    /// This is for modal operations during which no other user actions are allowed.  Only
785    /// one such operation is allowed at any given time.
786    ///
787    /// The return value is a cancel token, which will release the ongoing mutex when
788    /// dropped.
789    pub(crate) async fn alloc_ongoing(&self) -> Result<Receiver<()>> {
790        let mut s = self.running_state.write().await;
791        ensure!(
792            matches!(*s, RunningState::Stopped),
793            "There is already another ongoing process running."
794        );
795
796        let (sender, receiver) = channel::bounded(1);
797        *s = RunningState::Running {
798            cancel_sender: sender,
799        };
800
801        Ok(receiver)
802    }
803
804    pub(crate) async fn free_ongoing(&self) {
805        let mut s = self.running_state.write().await;
806        if let RunningState::ShallStop { request } = *s {
807            info!(self, "Ongoing stopped in {:?}", time_elapsed(&request));
808        }
809        *s = RunningState::Stopped;
810    }
811
812    /// Signal an ongoing process to stop.
813    pub async fn stop_ongoing(&self) {
814        let mut s = self.running_state.write().await;
815        match &*s {
816            RunningState::Running { cancel_sender } => {
817                if let Err(err) = cancel_sender.send(()).await {
818                    warn!(self, "could not cancel ongoing: {:#}", err);
819                }
820                info!(self, "Signaling the ongoing process to stop ASAP.",);
821                *s = RunningState::ShallStop {
822                    request: tools::Time::now(),
823                };
824            }
825            RunningState::ShallStop { .. } | RunningState::Stopped => {
826                info!(self, "No ongoing process to stop.",);
827            }
828        }
829    }
830
831    #[allow(unused)]
832    pub(crate) async fn shall_stop_ongoing(&self) -> bool {
833        match &*self.running_state.read().await {
834            RunningState::Running { .. } => false,
835            RunningState::ShallStop { .. } | RunningState::Stopped => true,
836        }
837    }
838
839    /*******************************************************************************
840     * UI chat/message related API
841     ******************************************************************************/
842
843    /// Returns information about the context as key-value pairs.
844    pub async fn get_info(&self) -> Result<BTreeMap<&'static str, String>> {
845        let secondary_addrs = self.get_secondary_self_addrs().await?.join(", ");
846        let all_transports: Vec<String> = ConfiguredLoginParam::load_all(self)
847            .await?
848            .into_iter()
849            .map(|(transport_id, param)| format!("{transport_id}: {param}"))
850            .collect();
851        let all_transports = if all_transports.is_empty() {
852            "Not configured".to_string()
853        } else {
854            all_transports.join(",")
855        };
856        let chats = get_chat_cnt(self).await?;
857        let unblocked_msgs = message::get_unblocked_msg_cnt(self).await;
858        let request_msgs = message::get_request_msg_cnt(self).await;
859        let contacts = Contact::get_real_cnt(self).await?;
860        let proxy_enabled = self.get_config_int(Config::ProxyEnabled).await?;
861        let dbversion = self
862            .sql
863            .get_raw_config_int("dbversion")
864            .await?
865            .unwrap_or_default();
866        let journal_mode = self
867            .sql
868            .query_get_value("PRAGMA journal_mode;", ())
869            .await?
870            .unwrap_or_else(|| "unknown".to_string());
871        let mdns_enabled = self.get_config_int(Config::MdnsEnabled).await?;
872        let bcc_self = self.get_config_int(Config::BccSelf).await?;
873        let sync_msgs = self.get_config_int(Config::SyncMsgs).await?;
874        let disable_idle = self.get_config_bool(Config::DisableIdle).await?;
875
876        let prv_key_cnt = self.sql.count("SELECT COUNT(*) FROM keypairs;", ()).await?;
877
878        let pub_key_cnt = self
879            .sql
880            .count("SELECT COUNT(*) FROM public_keys;", ())
881            .await?;
882        let fingerprint_str = match self_fingerprint(self).await {
883            Ok(fp) => fp.to_string(),
884            Err(err) => format!("<key failure: {err}>"),
885        };
886
887        let mvbox_move = self.get_config_int(Config::MvboxMove).await?;
888        let only_fetch_mvbox = self.get_config_int(Config::OnlyFetchMvbox).await?;
889        let folders_configured = self
890            .sql
891            .get_raw_config_int(constants::DC_FOLDERS_CONFIGURED_KEY)
892            .await?
893            .unwrap_or_default();
894
895        let configured_inbox_folder = self
896            .get_config(Config::ConfiguredInboxFolder)
897            .await?
898            .unwrap_or_else(|| "<unset>".to_string());
899        let configured_mvbox_folder = self
900            .get_config(Config::ConfiguredMvboxFolder)
901            .await?
902            .unwrap_or_else(|| "<unset>".to_string());
903
904        let mut res = get_info();
905
906        // insert values
907        res.insert("bot", self.get_config_int(Config::Bot).await?.to_string());
908        res.insert("number_of_chats", chats.to_string());
909        res.insert("number_of_chat_messages", unblocked_msgs.to_string());
910        res.insert("messages_in_contact_requests", request_msgs.to_string());
911        res.insert("number_of_contacts", contacts.to_string());
912        res.insert("database_dir", self.get_dbfile().display().to_string());
913        res.insert("database_version", dbversion.to_string());
914        res.insert(
915            "database_encrypted",
916            self.sql
917                .is_encrypted()
918                .await
919                .map_or_else(|| "closed".to_string(), |b| b.to_string()),
920        );
921        res.insert("journal_mode", journal_mode);
922        res.insert("blobdir", self.get_blobdir().display().to_string());
923        res.insert(
924            "selfavatar",
925            self.get_config(Config::Selfavatar)
926                .await?
927                .unwrap_or_else(|| "<unset>".to_string()),
928        );
929        res.insert("proxy_enabled", proxy_enabled.to_string());
930        res.insert("used_transport_settings", all_transports);
931
932        if let Some(server_id) = &*self.server_id.read().await {
933            res.insert("imap_server_id", format!("{server_id:?}"));
934        }
935
936        res.insert("is_chatmail", self.is_chatmail().await?.to_string());
937        res.insert(
938            "fix_is_chatmail",
939            self.get_config_bool(Config::FixIsChatmail)
940                .await?
941                .to_string(),
942        );
943        res.insert(
944            "is_muted",
945            self.get_config_bool(Config::IsMuted).await?.to_string(),
946        );
947        res.insert(
948            "private_tag",
949            self.get_config(Config::PrivateTag)
950                .await?
951                .unwrap_or_else(|| "<unset>".to_string()),
952        );
953
954        if let Some(metadata) = &*self.metadata.read().await {
955            if let Some(comment) = &metadata.comment {
956                res.insert("imap_server_comment", format!("{comment:?}"));
957            }
958
959            if let Some(admin) = &metadata.admin {
960                res.insert("imap_server_admin", format!("{admin:?}"));
961            }
962        }
963
964        res.insert("secondary_addrs", secondary_addrs);
965        res.insert(
966            "show_emails",
967            self.get_config_int(Config::ShowEmails).await?.to_string(),
968        );
969        res.insert(
970            "who_can_call_me",
971            self.get_config_int(Config::WhoCanCallMe).await?.to_string(),
972        );
973        res.insert(
974            "download_limit",
975            self.get_config_int(Config::DownloadLimit)
976                .await?
977                .to_string(),
978        );
979        res.insert("mvbox_move", mvbox_move.to_string());
980        res.insert("only_fetch_mvbox", only_fetch_mvbox.to_string());
981        res.insert(
982            constants::DC_FOLDERS_CONFIGURED_KEY,
983            folders_configured.to_string(),
984        );
985        res.insert("configured_inbox_folder", configured_inbox_folder);
986        res.insert("configured_mvbox_folder", configured_mvbox_folder);
987        res.insert("mdns_enabled", mdns_enabled.to_string());
988        res.insert("bcc_self", bcc_self.to_string());
989        res.insert("sync_msgs", sync_msgs.to_string());
990        res.insert("disable_idle", disable_idle.to_string());
991        res.insert("private_key_count", prv_key_cnt.to_string());
992        res.insert("public_key_count", pub_key_cnt.to_string());
993        res.insert("fingerprint", fingerprint_str);
994        res.insert(
995            "media_quality",
996            self.get_config_int(Config::MediaQuality).await?.to_string(),
997        );
998        res.insert(
999            "delete_device_after",
1000            self.get_config_int(Config::DeleteDeviceAfter)
1001                .await?
1002                .to_string(),
1003        );
1004        res.insert(
1005            "delete_server_after",
1006            self.get_config_int(Config::DeleteServerAfter)
1007                .await?
1008                .to_string(),
1009        );
1010        res.insert(
1011            "last_housekeeping",
1012            self.get_config_int(Config::LastHousekeeping)
1013                .await?
1014                .to_string(),
1015        );
1016        res.insert(
1017            "last_cant_decrypt_outgoing_msgs",
1018            self.get_config_int(Config::LastCantDecryptOutgoingMsgs)
1019                .await?
1020                .to_string(),
1021        );
1022        res.insert(
1023            "quota_exceeding",
1024            self.get_config_int(Config::QuotaExceeding)
1025                .await?
1026                .to_string(),
1027        );
1028        res.insert(
1029            "authserv_id_candidates",
1030            self.get_config(Config::AuthservIdCandidates)
1031                .await?
1032                .unwrap_or_default(),
1033        );
1034        res.insert(
1035            "sign_unencrypted",
1036            self.get_config_int(Config::SignUnencrypted)
1037                .await?
1038                .to_string(),
1039        );
1040        res.insert(
1041            "debug_logging",
1042            self.get_config_int(Config::DebugLogging).await?.to_string(),
1043        );
1044        res.insert(
1045            "last_msg_id",
1046            self.get_config_int(Config::LastMsgId).await?.to_string(),
1047        );
1048        res.insert(
1049            "gossip_period",
1050            self.get_config_int(Config::GossipPeriod).await?.to_string(),
1051        );
1052        res.insert(
1053            "webxdc_realtime_enabled",
1054            self.get_config_bool(Config::WebxdcRealtimeEnabled)
1055                .await?
1056                .to_string(),
1057        );
1058        res.insert(
1059            "donation_request_next_check",
1060            self.get_config_i64(Config::DonationRequestNextCheck)
1061                .await?
1062                .to_string(),
1063        );
1064        res.insert(
1065            "first_key_contacts_msg_id",
1066            self.sql
1067                .get_raw_config("first_key_contacts_msg_id")
1068                .await?
1069                .unwrap_or_default(),
1070        );
1071        res.insert(
1072            "stats_id",
1073            self.get_config(Config::StatsId)
1074                .await?
1075                .unwrap_or_else(|| "<unset>".to_string()),
1076        );
1077        res.insert(
1078            "stats_sending",
1079            stats::should_send_stats(self).await?.to_string(),
1080        );
1081        res.insert(
1082            "stats_last_sent",
1083            self.get_config_i64(Config::StatsLastSent)
1084                .await?
1085                .to_string(),
1086        );
1087        res.insert(
1088            "test_hooks",
1089            self.sql
1090                .get_raw_config("test_hooks")
1091                .await?
1092                .unwrap_or_default(),
1093        );
1094        res.insert(
1095            "std_header_protection_composing",
1096            self.sql
1097                .get_raw_config("std_header_protection_composing")
1098                .await?
1099                .unwrap_or_default(),
1100        );
1101        res.insert(
1102            "team_profile",
1103            self.get_config_bool(Config::TeamProfile).await?.to_string(),
1104        );
1105
1106        let elapsed = time_elapsed(&self.creation_time);
1107        res.insert("uptime", duration_to_str(elapsed));
1108
1109        Ok(res)
1110    }
1111
1112    /// Get a list of fresh, unmuted messages in unblocked chats.
1113    ///
1114    /// The list starts with the most recent message
1115    /// and is typically used to show notifications.
1116    /// Moreover, the number of returned messages
1117    /// can be used for a badge counter on the app icon.
1118    pub async fn get_fresh_msgs(&self) -> Result<Vec<MsgId>> {
1119        let list = self
1120            .sql
1121            .query_map_vec(
1122                "SELECT m.id
1123FROM msgs m
1124LEFT JOIN contacts ct
1125    ON m.from_id=ct.id
1126LEFT JOIN chats c
1127    ON m.chat_id=c.id
1128WHERE m.state=?
1129AND m.hidden=0
1130AND m.chat_id>9
1131AND ct.blocked=0
1132AND c.blocked=0
1133AND NOT(c.muted_until=-1 OR c.muted_until>?)
1134ORDER BY m.timestamp DESC,m.id DESC",
1135                (MessageState::InFresh, time()),
1136                |row| {
1137                    let msg_id: MsgId = row.get(0)?;
1138                    Ok(msg_id)
1139                },
1140            )
1141            .await?;
1142        Ok(list)
1143    }
1144
1145    /// Returns a list of messages with database ID higher than requested.
1146    ///
1147    /// Blocked contacts and chats are excluded,
1148    /// but self-sent messages and contact requests are included in the results.
1149    pub async fn get_next_msgs(&self) -> Result<Vec<MsgId>> {
1150        let last_msg_id = match self.get_config(Config::LastMsgId).await? {
1151            Some(s) => MsgId::new(s.parse()?),
1152            None => {
1153                // If `last_msg_id` is not set yet,
1154                // subtract 1 from the last id,
1155                // so a single message is returned and can
1156                // be marked as seen.
1157                self.sql
1158                    .query_row(
1159                        "SELECT IFNULL((SELECT MAX(id) - 1 FROM msgs), 0)",
1160                        (),
1161                        |row| {
1162                            let msg_id: MsgId = row.get(0)?;
1163                            Ok(msg_id)
1164                        },
1165                    )
1166                    .await?
1167            }
1168        };
1169
1170        let list = self
1171            .sql
1172            .query_map_vec(
1173                "SELECT m.id
1174                     FROM msgs m
1175                     LEFT JOIN contacts ct
1176                            ON m.from_id=ct.id
1177                     LEFT JOIN chats c
1178                            ON m.chat_id=c.id
1179                     WHERE m.id>?
1180                       AND m.hidden=0
1181                       AND m.chat_id>9
1182                       AND ct.blocked=0
1183                       AND c.blocked!=1
1184                     ORDER BY m.id ASC",
1185                (
1186                    last_msg_id.to_u32(), // Explicitly convert to u32 because 0 is allowed.
1187                ),
1188                |row| {
1189                    let msg_id: MsgId = row.get(0)?;
1190                    Ok(msg_id)
1191                },
1192            )
1193            .await?;
1194        Ok(list)
1195    }
1196
1197    /// Returns a list of messages with database ID higher than last marked as seen.
1198    ///
1199    /// This function is supposed to be used by bot to request messages
1200    /// that are not processed yet.
1201    ///
1202    /// Waits for notification and returns a result.
1203    /// Note that the result may be empty if the message is deleted
1204    /// shortly after notification or notification is manually triggered
1205    /// to interrupt waiting.
1206    /// Notification may be manually triggered by calling [`Self::stop_io`].
1207    pub async fn wait_next_msgs(&self) -> Result<Vec<MsgId>> {
1208        self.new_msgs_notify.notified().await;
1209        let list = self.get_next_msgs().await?;
1210        Ok(list)
1211    }
1212
1213    /// Searches for messages containing the query string case-insensitively.
1214    ///
1215    /// If `chat_id` is provided this searches only for messages in this chat, if `chat_id`
1216    /// is `None` this searches messages from all chats.
1217    ///
1218    /// NB: Wrt the search in long messages which are shown truncated with the "Show Full Message…"
1219    /// button, we only look at the first several kilobytes. Let's not fix this -- one can send a
1220    /// dictionary in the message that matches any reasonable search request, but the user won't see
1221    /// the match because they should tap on "Show Full Message…" for that. Probably such messages
1222    /// would only clutter search results.
1223    pub async fn search_msgs(&self, chat_id: Option<ChatId>, query: &str) -> Result<Vec<MsgId>> {
1224        let real_query = query.trim().to_lowercase();
1225        if real_query.is_empty() {
1226            return Ok(Vec::new());
1227        }
1228        let str_like_in_text = format!("%{real_query}%");
1229
1230        let list = if let Some(chat_id) = chat_id {
1231            self.sql
1232                .query_map_vec(
1233                    "SELECT m.id AS id
1234                 FROM msgs m
1235                 LEFT JOIN contacts ct
1236                        ON m.from_id=ct.id
1237                 WHERE m.chat_id=?
1238                   AND m.hidden=0
1239                   AND ct.blocked=0
1240                   AND IFNULL(txt_normalized, txt) LIKE ?
1241                 ORDER BY m.timestamp,m.id;",
1242                    (chat_id, str_like_in_text),
1243                    |row| {
1244                        let msg_id: MsgId = row.get("id")?;
1245                        Ok(msg_id)
1246                    },
1247                )
1248                .await?
1249        } else {
1250            // For performance reasons results are sorted only by `id`, that is in the order of
1251            // message reception.
1252            //
1253            // Unlike chat view, sorting by `timestamp` is not necessary but slows down the query by
1254            // ~25% according to benchmarks.
1255            //
1256            // To speed up incremental search, where queries for few characters usually return lots
1257            // of unwanted results that are discarded moments later, we added `LIMIT 1000`.
1258            // According to some tests, this limit speeds up eg. 2 character searches by factor 10.
1259            // The limit is documented and UI may add a hint when getting 1000 results.
1260            self.sql
1261                .query_map_vec(
1262                    "SELECT m.id AS id
1263                 FROM msgs m
1264                 LEFT JOIN contacts ct
1265                        ON m.from_id=ct.id
1266                 LEFT JOIN chats c
1267                        ON m.chat_id=c.id
1268                 WHERE m.chat_id>9
1269                   AND m.hidden=0
1270                   AND c.blocked!=1
1271                   AND ct.blocked=0
1272                   AND IFNULL(txt_normalized, txt) LIKE ?
1273                 ORDER BY m.id DESC LIMIT 1000",
1274                    (str_like_in_text,),
1275                    |row| {
1276                        let msg_id: MsgId = row.get("id")?;
1277                        Ok(msg_id)
1278                    },
1279                )
1280                .await?
1281        };
1282
1283        Ok(list)
1284    }
1285
1286    /// Returns true if given folder name is the name of the "DeltaChat" folder.
1287    pub async fn is_mvbox(&self, folder_name: &str) -> Result<bool> {
1288        let mvbox = self.get_config(Config::ConfiguredMvboxFolder).await?;
1289        Ok(mvbox.as_deref() == Some(folder_name))
1290    }
1291
1292    pub(crate) fn derive_blobdir(dbfile: &Path) -> PathBuf {
1293        let mut blob_fname = OsString::new();
1294        blob_fname.push(dbfile.file_name().unwrap_or_default());
1295        blob_fname.push("-blobs");
1296        dbfile.with_file_name(blob_fname)
1297    }
1298
1299    pub(crate) fn derive_walfile(dbfile: &Path) -> PathBuf {
1300        let mut wal_fname = OsString::new();
1301        wal_fname.push(dbfile.file_name().unwrap_or_default());
1302        wal_fname.push("-wal");
1303        dbfile.with_file_name(wal_fname)
1304    }
1305}
1306
1307#[cfg(test)]
1308mod context_tests;